Search Results

Search found 186 results on 8 pages for 'getitem'.

Page 3/8 | < Previous Page | 1 2 3 4 5 6 7 8  | Next Page >

  • ListView with button and check mark?

    - by jgelderloos
    So I have looked through a lot of other answers but have not been able to get my app to work how I want it. I basically want the list view that has the text and check mark to the right, but then an addition button to the left. Right now my list view shows up but the check image is never changed. Selector: <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_selected="true" android:drawable="@drawable/accept_on" /> <item android:drawable="@drawable/accept" /> </selector> Row xml: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/layout" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="10dp" android:background="#EEE"> <ImageButton android:id="@+id/goToMapButton" android:src="@drawable/go_to_map" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="left" /> <TextView android:id="@+id/itemName" android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="center_vertical" android:textColor="#000000" android:layout_marginTop="5dp" android:layout_marginBottom="5dp" android:layout_weight="1" /> <Button android:id="@+id/checkButton" android:background="@drawable/item_selector" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="right" /> </LinearLayout> MapAdapter: import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; public class MapAdapter extends ArrayAdapter<String>{ Context context; int layoutResourceId; String data[] = null; LayoutInflater inflater; LinearLayout layout; public MapAdapter(Context context, int layoutResourceId, String[] data) { super(context, layoutResourceId, data); this.layoutResourceId = layoutResourceId; this.context = context; this.data = data; inflater = LayoutInflater.from(context); } @Override public String getItem(int position) { return data[position]; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = new ViewHolder(); if(convertView == null) { convertView = inflater.inflate(R.layout.map_item_row, null); layout = (LinearLayout)convertView.findViewById(R.id.layout); holder.map = (ImageButton)convertView.findViewById(R.id.goToMapButton); holder.name = (TextView)convertView.findViewById(R.id.itemName); //holder.check = (Button)convertView.findViewById(R.id.checkButton); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } layout.setBackgroundColor(0x00000004); holder.name.setText(getItem(position)); return convertView; } static class ViewHolder { ImageButton map; TextView name; Button check; } }

    Read the article

  • Duplication of menu items with ViewPager and Fragments

    - by Julian
    I'm building an Android Application (minimum SDK Level 10, Gingerbread 2.3.3) with some Fragments in a ViewPager. I'm using ActionBarSherlock to create an ActionBar and android-viewpagertabs to add tabs to the ViewPager just like in the Market client. I have one global menu item that I want to be shown on every tab/fragment. On the first of the three tabs I want to have two additional menu items. But now two strange things happen: First if I start the app, everything seems to be fine, I can see all three menu items on the first page and only one item if i swipe to the second and third tab. But if I swipe back to the second tab from the third one, I can see all three items again which shouldn't happen. If I swipe back to the first and then again to the second tab, everything is fine again. The other strange thing is that every time I rotate the device, the menu items from the fragment are added again, even though they are already in the menu. Code of the FragmentActivity that displays the ViewPager and its tabs: public class MainActivity extends FragmentActivity { public static final String TAG = "MainActivity"; private ActionBar actionBar; private Adapter adapter; private ViewPager viewPager; private ViewPagerTabs tabs; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.volksempfaenger); actionBar = getSupportActionBar(); adapter = new Adapter(getSupportFragmentManager()); adapter.addFragment(getString(R.string.title_tab_subscriptions), SubscriptionGridFragment.class); // adding more fragments here viewPager = (ViewPager) findViewById(R.id.viewpager); viewPager.setAdapter(adapter); tabs = (ViewPagerTabs) findViewById(R.id.tabs); tabs.setViewPager(viewPager); } public static class Adapter extends FragmentPagerAdapter implements ViewPagerTabProvider { private FragmentManager fragmentManager; private ArrayList<Class<? extends Fragment>> fragments; private ArrayList<String> titles; public Adapter(FragmentManager fm) { super(fm); fragmentManager = fm; fragments = new ArrayList<Class<? extends Fragment>>(); titles = new ArrayList<String>(); } public void addFragment(String title, Class<? extends Fragment> fragment) { titles.add(title); fragments.add(fragment); } @Override public int getCount() { return fragments.size(); } public String getTitle(int position) { return titles.get(position); } @Override public Fragment getItem(int position) { try { return fragments.get(position).newInstance(); } catch (InstantiationException e) { Log.wtf(TAG, e); } catch (IllegalAccessException e) { Log.wtf(TAG, e); } return null; } @Override public Object instantiateItem(View container, int position) { FragmentTransaction fragmentTransaction = fragmentManager .beginTransaction(); Fragment f = getItem(position); fragmentTransaction.add(container.getId(), f); fragmentTransaction.commit(); return f; } } @Override public boolean onCreateOptionsMenu(Menu menu) { BaseActivity.addGlobalMenu(this, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { return BaseActivity.handleGlobalMenu(this, item); } } Code of the fragment that shall have its own menu items: public class SubscriptionGridFragment extends Fragment { private GridView subscriptionList; private SubscriptionListAdapter adapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } // ... @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.subscription_list, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // ... } }

    Read the article

  • Looking for suggestions on how to reuse AlertDialogs to confirm actions of contextual menus on the items of an ActivityList

    - by Ozone
    I use a ListActivity to display a list of items. The user can long-press an item in the list to display a contextual menu. This menu contains among other things an option to delete the long-pressed item. When the user selects this option, a dialog pops up asking for confirmation of the deletion. Upon confirmation, the item is deleted from the list. I would like to reuse the AlertDialog as much as possible. My attempts at using onPrepareDialog(int, View, Bundle) have been defeated by the fact that the Bundle is not passed to the DialogInterface.OnClickListener. I end up having to recreate a listener on every invocation. I see several ways to solve this: recreate the dialog on every occasion (pros: simple, cons: wasteful) keep the DialogInterface.OnClickListener in a field on the ListActivity and keep the item to be deleted as a field of the listener. (pros: no memory waste, cons: need to manage state). Q: is this safe? have onPrepareDialog update the title, and bind new View.OnClickListeners on the buttons of the AlertDialog. (pros: limit waste, cons: new View.OnClickListener on every invocation). If DialogInterface.OnClickListener accepted a Bundle, I wouldn't have to jump through hoops to keep track of the item being deleted. This is not a blocker, but I would love to see an elegant solution. I would love to hear your suggestions :) Here is the code for option #1, if you want to play with this: public class Example extends ListActivity { private static final int CONFIRM_DELETE_DIALOG = 1; private static final String POSITION_KEY = "position"; private ArrayAdapter<String> mAdapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mAdapter = new ArrayAdapter<String>( this, android.R.layout.simple_list_item_1, new String[] { "one", "two" }); setListAdapter(mAdapter); registerForContextMenu(getListView()); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); getMenuInflater().inflate(R.menu.my_lovely_menu, menu); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); switch (item.getItemId()) { case R.id.delete_item: Bundle bundle = new Bundle(); bundle.putInt(POSITION_KEY, info.position); showDialog(CONFIRM_DELETE_DIALOG, bundle); return true; default: return super.onContextItemSelected(item); } } @Override protected Dialog onCreateDialog(int id, Bundle args) { switch (id) { case CONFIRM_DELETE_DIALOG: final int position = args.getInt(POSITION_KEY); AlertDialog.Builder builder = new AlertDialog.Builder(); builder.setCancelable(false); builder.setTitle(String.format( getString(R.string.confirm_delete), mAdapter.getItem(position))); DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { switch (which) { case DialogInterface.BUTTON_POSITIVE: mAdapter.remove(mAdapter.getItem(position)); // Dismiss the dialog to ensure OnDismissListeners are notified. dialog.dismiss(); break; case DialogInterface.BUTTON_NEGATIVE: // Cancel the dialog to ensure OnCancelListeners are notified. dialog.cancel(); break; } // Remove the dialog so it is re-created next time it is required. removeDialog(CONFIRM_DELETE_DIALOG); } }; builder.setPositiveButton(android.R.string.yes, listener); builder.setNegativeButton(android.R.string.no, listener); return builder.create(); default: return super.onCreateDialog(id, args); } } }

    Read the article

  • ASP.NET and HTML5 Local Storage

    - by Stephen Walther
    My favorite feature of HTML5, hands-down, is HTML5 local storage (aka DOM storage). By taking advantage of HTML5 local storage, you can dramatically improve the performance of your data-driven ASP.NET applications by caching data in the browser persistently. Think of HTML5 local storage like browser cookies, but much better. Like cookies, local storage is persistent. When you add something to browser local storage, it remains there when the user returns to the website (possibly days or months later). Importantly, unlike the cookie storage limitation of 4KB, you can store up to 10 megabytes in HTML5 local storage. Because HTML5 local storage works with the latest versions of all modern browsers (IE, Firefox, Chrome, Safari), you can start taking advantage of this HTML5 feature in your applications right now. Why use HTML5 Local Storage? I use HTML5 Local Storage in the JavaScript Reference application: http://Superexpert.com/JavaScriptReference The JavaScript Reference application is an HTML5 app that provides an interactive reference for all of the syntax elements of JavaScript (You can read more about the application and download the source code for the application here). When you open the application for the first time, all of the entries are transferred from the server to the browser (all 300+ entries). All of the entries are stored in local storage. When you open the application in the future, only changes are transferred from the server to the browser. The benefit of this approach is that the application performs extremely fast. When you click the details link to view details on a particular entry, the entry details appear instantly because all of the entries are stored on the client machine. When you perform key-up searches, by typing in the filter textbox, matching entries are displayed very quickly because the entries are being filtered on the local machine. This approach can have a dramatic effect on the performance of any interactive data-driven web application. Interacting with data on the client is almost always faster than interacting with the same data on the server. Retrieving Data from the Server In the JavaScript Reference application, I use Microsoft WCF Data Services to expose data to the browser. WCF Data Services generates a REST interface for your data automatically. Here are the steps: Create your database tables in Microsoft SQL Server. For example, I created a database named ReferenceDB and a database table named Entities. Use the Entity Framework to generate your data model. For example, I used the Entity Framework to generate a class named ReferenceDBEntities and a class named Entities. Expose your data through WCF Data Services. I added a WCF Data Service to my project and modified the data service class to look like this:   using System.Data.Services; using System.Data.Services.Common; using System.Web; using JavaScriptReference.Models; namespace JavaScriptReference.Services { [System.ServiceModel.ServiceBehavior(IncludeExceptionDetailInFaults = true)] public class EntryService : DataService<ReferenceDBEntities> { // This method is called only once to initialize service-wide policies. public static void InitializeService(DataServiceConfiguration config) { config.UseVerboseErrors = true; config.SetEntitySetAccessRule("*", EntitySetRights.All); config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2; } // Define a change interceptor for the Products entity set. [ChangeInterceptor("Entries")] public void OnChangeEntries(Entry entry, UpdateOperations operations) { if (!HttpContext.Current.Request.IsAuthenticated) { throw new DataServiceException("Cannot update reference unless authenticated."); } } } }     The WCF data service is named EntryService. Notice that it derives from DataService<ReferenceEntitites>. Because it derives from DataService<ReferenceEntities>, the data service exposes the contents of the ReferenceEntitiesDB database. In the code above, I defined a ChangeInterceptor to prevent un-authenticated users from making changes to the database. Anyone can retrieve data through the service, but only authenticated users are allowed to make changes. After you expose data through a WCF Data Service, you can use jQuery to retrieve the data by performing an Ajax call. For example, I am using an Ajax call that looks something like this to retrieve the JavaScript entries from the EntryService.svc data service: $.ajax({ dataType: "json", url: “/Services/EntryService.svc/Entries”, success: function (result) { var data = callback(result["d"]); } });     Notice that you must unwrap the data using result[“d”]. After you unwrap the data, you have a JavaScript array of the entries. I’m transferring all 300+ entries from the server to the client when the application is opened for the first time. In other words, I transfer the entire database from the server to the client, once and only once, when the application is opened for the first time. The data is transferred using JSON. Here is a fragment: { "d" : [ { "__metadata": { "uri": "http://superexpert.com/javascriptreference/Services/EntryService.svc/Entries(1)", "type": "ReferenceDBModel.Entry" }, "Id": 1, "Name": "Global", "Browsers": "ff3_6,ie8,ie9,c8,sf5,es3,es5", "Syntax": "object", "ShortDescription": "Contains global variables and functions", "FullDescription": "<p>\nThe Global object is determined by the host environment. In web browsers, the Global object is the same as the windows object.\n</p>\n<p>\nYou can use the keyword <code>this</code> to refer to the Global object when in the global context (outside of any function).\n</p>\n<p>\nThe Global object holds all global variables and functions. For example, the following code demonstrates that the global <code>movieTitle</code> variable refers to the same thing as <code>window.movieTitle</code> and <code>this.movieTitle</code>.\n</p>\n<pre>\nvar movieTitle = \"Star Wars\";\nconsole.log(movieTitle === this.movieTitle); // true\nconsole.log(movieTitle === window.movieTitle); // true\n</pre>\n", "LastUpdated": "634298578273756641", "IsDeleted": false, "OwnerId": null }, { "__metadata": { "uri": "http://superexpert.com/javascriptreference/Services/EntryService.svc/Entries(2)", "type": "ReferenceDBModel.Entry" }, "Id": 2, "Name": "eval(string)", "Browsers": "ff3_6,ie8,ie9,c8,sf5,es3,es5", "Syntax": "function", "ShortDescription": "Evaluates and executes JavaScript code dynamically", "FullDescription": "<p>\nThe following code evaluates and executes the string \"3+5\" at runtime.\n</p>\n<pre>\nvar result = eval(\"3+5\");\nconsole.log(result); // returns 8\n</pre>\n<p>\nYou can rewrite the code above like this:\n</p>\n<pre>\nvar result;\neval(\"result = 3+5\");\nconsole.log(result);\n</pre>", "LastUpdated": "634298580913817644", "IsDeleted": false, "OwnerId": 1 } … ]} I worried about the amount of time that it would take to transfer the records. According to Google Chome, it takes about 5 seconds to retrieve all 300+ records on a broadband connection over the Internet. 5 seconds is a small price to pay to avoid performing any server fetches of the data in the future. And here are the estimated times using different types of connections using Fiddler: Notice that using a modem, it takes 33 seconds to download the database. 33 seconds is a significant chunk of time. So, I would not use the approach of transferring the entire database up front if you expect a significant portion of your website audience to connect to your website with a modem. Adding Data to HTML5 Local Storage After the JavaScript entries are retrieved from the server, the entries are stored in HTML5 local storage. Here’s the reference documentation for HTML5 storage for Internet Explorer: http://msdn.microsoft.com/en-us/library/cc197062(VS.85).aspx You access local storage by accessing the windows.localStorage object in JavaScript. This object contains key/value pairs. For example, you can use the following JavaScript code to add a new item to local storage: <script type="text/javascript"> window.localStorage.setItem("message", "Hello World!"); </script>   You can use the Google Chrome Storage tab in the Developer Tools (hit CTRL-SHIFT I in Chrome) to view items added to local storage: After you add an item to local storage, you can read it at any time in the future by using the window.localStorage.getItem() method: <script type="text/javascript"> window.localStorage.setItem("message", "Hello World!"); </script>   You only can add strings to local storage and not JavaScript objects such as arrays. Therefore, before adding a JavaScript object to local storage, you need to convert it into a JSON string. In the JavaScript Reference application, I use a wrapper around local storage that looks something like this: function Storage() { this.get = function (name) { return JSON.parse(window.localStorage.getItem(name)); }; this.set = function (name, value) { window.localStorage.setItem(name, JSON.stringify(value)); }; this.clear = function () { window.localStorage.clear(); }; }   If you use the wrapper above, then you can add arbitrary JavaScript objects to local storage like this: var store = new Storage(); // Add array to storage var products = [ {name:"Fish", price:2.33}, {name:"Bacon", price:1.33} ]; store.set("products", products); // Retrieve items from storage var products = store.get("products");   Modern browsers support the JSON object natively. If you need the script above to work with older browsers then you should download the JSON2.js library from: https://github.com/douglascrockford/JSON-js The JSON2 library will use the native JSON object if a browser already supports JSON. Merging Server Changes with Browser Local Storage When you first open the JavaScript Reference application, the entire database of JavaScript entries is transferred from the server to the browser. Two items are added to local storage: entries and entriesLastUpdated. The first item contains the entire entries database (a big JSON string of entries). The second item, a timestamp, represents the version of the entries. Whenever you open the JavaScript Reference in the future, the entriesLastUpdated timestamp is passed to the server. Only records that have been deleted, updated, or added since entriesLastUpdated are transferred to the browser. The OData query to get the latest updates looks like this: http://superexpert.com/javascriptreference/Services/EntryService.svc/Entries?$filter=(LastUpdated%20gt%20634301199890494792L) If you remove URL encoding, the query looks like this: http://superexpert.com/javascriptreference/Services/EntryService.svc/Entries?$filter=(LastUpdated gt 634301199890494792L) This query returns only those entries where the value of LastUpdated > 634301199890494792 (the version timestamp). The changes – new JavaScript entries, deleted entries, and updated entries – are merged with the existing entries in local storage. The JavaScript code for performing the merge is contained in the EntriesHelper.js file. The merge() method looks like this:   merge: function (oldEntries, newEntries) { // concat (this performs the add) oldEntries = oldEntries || []; var mergedEntries = oldEntries.concat(newEntries); // sort this.sortByIdThenLastUpdated(mergedEntries); // prune duplicates (this performs the update) mergedEntries = this.pruneDuplicates(mergedEntries); // delete mergedEntries = this.removeIsDeleted(mergedEntries); // Sort this.sortByName(mergedEntries); return mergedEntries; },   The contents of local storage are then updated with the merged entries. I spent several hours writing the merge() method (much longer than I expected). I found two resources to be extremely useful. First, I wrote extensive unit tests for the merge() method. I wrote the unit tests using server-side JavaScript. I describe this approach to writing unit tests in this blog entry. The unit tests are included in the JavaScript Reference source code. Second, I found the following blog entry to be super useful (thanks Nick!): http://nicksnettravels.builttoroam.com/post/2010/08/03/OData-Synchronization-with-WCF-Data-Services.aspx One big challenge that I encountered involved timestamps. I originally tried to store an actual UTC time as the value of the entriesLastUpdated item. I quickly discovered that trying to work with dates in JSON turned out to be a big can of worms that I did not want to open. Next, I tried to use a SQL timestamp column. However, I learned that OData cannot handle the timestamp data type when doing a filter query. Therefore, I ended up using a bigint column in SQL and manually creating the value when a record is updated. I overrode the SaveChanges() method to look something like this: public override int SaveChanges(SaveOptions options) { var changes = this.ObjectStateManager.GetObjectStateEntries( EntityState.Modified | EntityState.Added | EntityState.Deleted); foreach (var change in changes) { var entity = change.Entity as IEntityTracking; if (entity != null) { entity.LastUpdated = DateTime.Now.Ticks; } } return base.SaveChanges(options); }   Notice that I assign Date.Now.Ticks to the entity.LastUpdated property whenever an entry is modified, added, or deleted. Summary After building the JavaScript Reference application, I am convinced that HTML5 local storage can have a dramatic impact on the performance of any data-driven web application. If you are building a web application that involves extensive interaction with data then I recommend that you take advantage of this new feature included in the HTML5 standard.

    Read the article

  • Vectorizatoin of index operation for a scipy.sparse matrix

    - by celil
    The following code runs too slowly even though everything seems to be vectorized. from numpy import * from scipy.sparse import * n = 100000; i = xrange(n); j = xrange(n); data = ones(n); A=csr_matrix((data,(i,j))); x = A[i,j] The problem seems to be that the indexing operation is implemented as a python function, and invoking A[i,j] results in the following profiling output 500033 function calls in 8.718 CPU seconds Ordered by: internal time ncalls tottime percall cumtime percall filename:lineno(function) 100000 7.933 0.000 8.156 0.000 csr.py:265(_get_single_element) 1 0.271 0.271 8.705 8.705 csr.py:177(__getitem__) (...) Namely, the python function _get_single_element gets called 100000 times which is really inefficient. Why isn't this implemented in pure C? Does anybody know of a way of getting around this limitation, and speeding up the above code? Should I be using a different sparse matrix type?

    Read the article

  • UI-Automation cmdlet not finding the control

    - by sc_ray
    Hi, I am trying to test a WPF application using the UI-Automation framework that MSFT provides. There were a few powershell scripts written that invoked the cmdlets created to manipulate the visual controls of the application. There is a DropDown within my application that has an entry 'DropDownEntry'. In my cmdlet, I am trying to do something as follows: AutomationElement getItem = DropDown.FindFirst(TreeScope.Descendants, new AndCondition( new PropertyCondition(AutomationElement.ControlTypeProperty,ControlType.ListItem), new PropertyCondition(AutomationElement.NameProperty, "DropDownEntry",PropertyConditionFlags.IgnoreCase))); The above given snippet returns 'null' upon execution which essentially means that the above given logic was unable to find my dropdown entry. Can somebody tell me why this might be happening? I checked the name of my control and the values. Everything seems to be in order. I am not sure why this would be happening. Any help would be much appreciated. Thanks

    Read the article

  • How do you set a custom session when unit testing with wicket?

    - by vagabond
    I'm trying to run some unit tests on a wicket page that only allows access after you've logged in. In my JUnit test I cannot start the page or render it without setting the session. How do you set the session? I'm having problems finding any documentation on how to do this. WicketTester tester = new WicketTester(new MyApp()); ((MyCustomSession)tester.getWicketSession()).setItem(MyFactory.getItem("abc")); //Fails to start below, no session seems to be set tester.startPage(General.class); tester.assertRenderedPage(General.class);

    Read the article

  • Issues while downloading document from Sharepoint using JAVA

    - by Deepak Singh Rawat
    I am trying to download a file from Sharepoint 2007 sp2 document library using GetItem method of the Copy webservice. I am facing the following issues : In the local instance ( Windows Vista ) I can save only 10.5 Kb of any file. The webservice is returning only 10.5 Kb of data for any file. On the production server, I am able to List the documents using some credentials but when I am trying to download a document using the same credentials I get a 401 : Unauthorized message. I can download the document using the Sharepoint website successfully.

    Read the article

  • how to open a page in another browser instance by clicking on a link

    - by CoffeeCode
    i have a link <a id="DownloadLink" href='controller/action' target="_blank">Download File</a> that has to open a image in another tab or page. but it offers me to download the file. my action looks like this public FileContentResult GetSurveyFile(int Id) { if (Id == 0) return null; Survey survey = Repository.GetItem(Id); if (survey.File == null) return null; return File(survey.File.FileContent.ToArray(), survey.File.ContentType,survey.File.Name); } where the content type is an image/jpeg whats wrong?

    Read the article

  • Using *.html extension in dynamic UR's for SEO

    - by lostaman
    Hi all My situation is. I have a project planned to be built on ASP.NET MVC 2. And one of the major requirements is SEO optimization. A customer wants to use static-like URLs that end up with .html extension for this project that make URLs more SEO friendly. E.g. "mysite.com/about.html " or "mysite.com/items/getitem/5.html" etc. I wonder is there any benefit from SEO perspective to use .html extension in dynamic URLs? Are Google and other search engines rank work better with such URLs?

    Read the article

  • DEADLOCK_WRAP error when using Berkeley Db in python (bsddb)

    - by JiminyCricket
    I am using a berkdb to store a huge list of key-value pairs but for some reason when i try to access some of the data later i get this error: try: key = 'scrape011201-590652' contenttext = contentdict[key] except: print the error <type 'exceptions.KeyError'> 'scrape011201-590652' in contenttext = contentdict[key]\n', ' File "/usr/lib64/python2.5/bsddb/__init__.py", line 223, in __getitem__\n return _DeadlockWrap(lambda: self.db[key]) # self.db[key]\n', 'File "/usr/lib64/python2.5/bsddb/dbutils.py", line 62, in DeadlockWrap\n return function(*_args, **_kwargs)\n', ' File "/usr/lib64/python2.5/bsddb/__init__.py", line 223, in <lambda>\n return _DeadlockWrap(lambda: self.db[key]) # self.db[key]\n'] I am not sure what DeadlockWrap is but there isnt any other program or process accessing the berkdb or writing to it (as far as i know,) so not sure how we could get a deadlock, if its referring to that. Is it possible that I am trying to access the data to rapidly? I have this function call in a loop, so something like for i in hugelist: #try to get a value from the berkdb #do something with it I am running this with multiple datasets and this error only occurs with one of them, the largest one, not the others.

    Read the article

  • How to make a mutable ItemizedOverlay

    - by Hamy
    Hey all, I would like to make a Google map overlay with changable pins. An easy way to visualize this would be to think of a near real time overlay, where the pins are constantly changing location. However, I can't seem to think of a safe way to do this with the ItemizedOverlay. The problem seems to be the call to populate - If size() is called by some maps thread, and then my data changes, then the result when the maps call accesses getItem() can be an IndexOutOfBoundsException. Can anyone think of a better solution than overloading populate and wrapping super.populate in a synchronized block? Perhaps I could get better luck using a normal Overlay? The Itemized one seems to exist to manage the data for you, perhaps I am making a fundamental mistake by using it? Thanks for any help, my brain is hurting! Hamy

    Read the article

  • just-in-time list

    - by intuited
    I'd like to know if there is a class available, either in the standard library or in pypi, that fits this description. The constructor would take an iterator. It would implement the container protocol (ie _getitem_, _len_, etc), so that slices, length, etc., would work. In doing so, it would iterate and retain just enough values from its constructor argument to provide whatever information was requested. So if jitlist[6] was requested, it would call self.source.next() 7 times, save those elements in its list, and return the last one. This would allow downstream code to use it as a list, but avoid unnecessarily instantiating a list for cases where list functionality was not needed, and avoid allocating memory for the entire list if only a few members ended up being requested. It seems like a pretty easy one to write, but it also seems useful enough that it's likely that someone would have already made it available in a module.

    Read the article

  • KeyError this says that key(partner) is not in dict ?

    - by Ansh Jain
    I am trying to make an chat application using python and django. I almost complete it and its working fine for 8-10 minutes when two persons are chatting after that certain time it shows an error. here is the traceback : - Traceback (most recent call last): File "\Django_chat\django_chat\chat\views.py", line 55, in receive message = chatSession.getMessage(request.session['partner'],request.session['uid'],afterTime) File "C:\Python26\lib\site-packages\django\contrib\sessions\backends\base.py", line 47, in __getitem__ return self._session[key] KeyError: 'partner' here is the receive module :- def receive(request): message received by this user chatSession = chat() data = request.POST afterTime = data['lastMsgTime'] try: message = chatSession.getMessage(request.session['partner'],request.session['uid'],afterTime) except: #partnerId = virtual_users.objects.get(id=request.session['uid']).partner print('there is an error in receive request') traceback.print_exc(file=open("/myapp.log","a")) msg = serializers.serialize("json", message) return HttpResponse(msg) Please Help me :( thanks Ansh J

    Read the article

  • interface as a method parameter in Java

    - by PeterYu
    Hi all, I had an interview days ago and was thrown a question like this. Q: Reverse a linked list. Following code is given: public class ReverseList { interface NodeList { int getItem(); NodeList nextNode(); } void reverse(NodeList node) { } public static void main(String[] args) { } } I was confused because I did not know an interface object could be used as a method parameter. The interviewer explained a little bit but I am still not sure about this. Could somebody enlighten me?

    Read the article

  • Getting repeat values after copying 2-3 items to clipboard in android?

    - by Gurpreet singh
    I am using clipboard code like below in my app.Everything is working fine if i copy one item at a time.But when we copy 2-3 items one after other and paste somewhere it starts retrieving repeated past value from clipboard rather than the current value.After googling a lot i came to know that its a problem with Samsung phones and i need to clear clipboard history for that.But i could not find any way to clear clipboard history. Public void CopyToClipboard { int pos = (Integer) v.getTag(); StatusEntity obj=getItem(pos); ClipboardManager clipmanager= (ClipboardManager)getContext().getSystemService(getContext().CLIPBOARD_SERVICE); ClipData clip=ClipData.newPlainText("data",obj.getStatus()); clipmanager.setPrimaryClip(clip); Toast.makeText(getContext(), "Copied to clipboard", 1000).show(); } Hoping that anyone of you can help me regarding this .Any help would be appreciated.

    Read the article

  • No view for id for fragment

    - by guillaume
    I'm trying to use le lib SlidingMenu in my app but i'm having some problems. I'm getting this error: 11-04 15:50:46.225: E/FragmentManager(21112): No view found for id 0x7f040009 (com.myapp:id/menu_frame) for fragment SampleListFragment{413805f0 #0 id=0x7f040009} BaseActivity.java package com.myapp; import android.support.v4.app.FragmentTransaction; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.view.Menu; import android.view.MenuItem; import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu; import com.jeremyfeinstein.slidingmenu.lib.app.SlidingFragmentActivity; public class BaseActivity extends SlidingFragmentActivity { private int mTitleRes; protected ListFragment mFrag; public BaseActivity(int titleRes) { mTitleRes = titleRes; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(mTitleRes); // set the Behind View setBehindContentView(R.layout.menu_frame); if (savedInstanceState == null) { FragmentTransaction t = this.getSupportFragmentManager().beginTransaction(); mFrag = new SampleListFragment(); t.replace(R.id.menu_frame, mFrag); t.commit(); } else { mFrag = (ListFragment) this.getSupportFragmentManager().findFragmentById(R.id.menu_frame); } // customize the SlidingMenu SlidingMenu slidingMenu = getSlidingMenu(); slidingMenu.setMode(SlidingMenu.LEFT); slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN); slidingMenu.setShadowWidthRes(R.dimen.slidingmenu_shadow_width); slidingMenu.setShadowDrawable(R.drawable.slidingmenu_shadow); slidingMenu.setBehindOffsetRes(R.dimen.slidingmenu_offset); slidingMenu.setFadeDegree(0.35f); slidingMenu.setMenu(R.layout.slidingmenu); getActionBar().setDisplayHomeAsUpEnabled(true); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: toggle(); return true; } return super.onOptionsItemSelected(item); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } } menu.xml <?xml version="1.0" encoding="utf-8"?> <fragment xmlns:android="http://schemas.android.com/apk/res/android" android:name="com.myapp.SampleListFragment" android:layout_width="match_parent" android:layout_height="match_parent" > </fragment> menu_frame.xml <?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/menu_frame" android:layout_width="match_parent" android:layout_height="match_parent" /> SampleListFragment.java package com.myapp; import android.content.Context; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; public class SampleListFragment extends ListFragment { public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.list, null); } public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); SampleAdapter adapter = new SampleAdapter(getActivity()); for (int i = 0; i < 20; i++) { adapter.add(new SampleItem("Sample List", android.R.drawable.ic_menu_search)); } setListAdapter(adapter); } private class SampleItem { public String tag; public int iconRes; public SampleItem(String tag, int iconRes) { this.tag = tag; this.iconRes = iconRes; } } public class SampleAdapter extends ArrayAdapter<SampleItem> { public SampleAdapter(Context context) { super(context, 0); } public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.row, null); } ImageView icon = (ImageView) convertView.findViewById(R.id.row_icon); icon.setImageResource(getItem(position).iconRes); TextView title = (TextView) convertView.findViewById(R.id.row_title); title.setText(getItem(position).tag); return convertView; } } } MainActivity.java package com.myapp; import java.util.ArrayList; import beans.Tweet; import database.DatabaseHelper; import adapters.TweetListViewAdapter; import android.os.Bundle; import android.widget.ListView; public class MainActivity extends BaseActivity { public MainActivity(){ super(R.string.app_name); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final ListView listview = (ListView) findViewById(R.id.listview_tweets); DatabaseHelper db = new DatabaseHelper(this); ArrayList<Tweet> tweets = db.getAllTweets(); TweetListViewAdapter adapter = new TweetListViewAdapter(this, R.layout.listview_item_row, tweets); listview.setAdapter(adapter); setSlidingActionBarEnabled(false); } } I don't understand why the view menu_frame is not found because I have a view with the id menu_frame and this view is a child of the layout menu_frame.

    Read the article

  • Using *.html extension in dynamic URL's for SEO

    - by lostaman
    Hi all My situation is. I have a project planned to be built on ASP.NET MVC 2. And one of the major requirements is SEO optimization. A customer wants to use static-like URLs that end up with .html extension for this project that make URLs more SEO friendly. E.g. "mysite.com/about.html " or "mysite.com/items/getitem/5.html" etc. I wonder is there any benefit from SEO perspective to use .html extension in dynamic URLs? Are Google and other search engines rank work better with such URLs?

    Read the article

  • Making a PHP object behave like an array?

    - by Mark Biek
    I'd like to be able to write a PHP class that behaves like an array and uses normal array syntax for getting & setting. For example (where Foo is a PHP class of my making): $foo = new Foo(); $foo['fooKey'] = 'foo value'; echo $foo['fooKey']; I know that PHP has the _get and _set magic methods but those don't let you use array notation to access items. Python handles it by overloading __getitem__ and __setitem__. Is there a way to do this in PHP? If it makes a difference, I'm running PHP 5.2.

    Read the article

  • Simulating python's With statement in java

    - by drozzy
    Is there something like Python with context manager in Java? For example say I want to do something like the following: getItem(itemID){ Connection c = C.getConnection(); c.open(); try{ Item i = c.query(itemID); }catch(ALLBunchOfErrors){ c.close(); } c.close(); return c; } where in python I just have: with( C.getConnection().open() as c): Item i = c.query(itemID); return i;

    Read the article

  • grailsApplication not getting injected in a service , Grails 2.1.0

    - by vijay tyagi
    I have service in which i am accessing few configuration properties from grailsApplication I am injecting it like this class MyWebService{ def grailsApplication WebService webService = new WebService() def getProxy(url, flag){ return webService.getClient(url) } def getResponse(){ def proxy = getProxy(grailsApplication.config.grails.wsdlURL, true) def response = proxy.getItem(ItemType) return response } } When i call getProxy() method, i see this in tomcat logs No signature of method: org.example.MyWebService.getProxy() is applicable for argument types: (groovy.util.ConfigObject, java.lang.Boolean) values: [[:], true] Possible solutions: getProxy(), getProxy(java.lang.String, boolean), setProxy(java.lang.Object) which means grailsApplication is not getting injected into the service, is there any alternate way to access configuration object ? according to burtbeckwith's post configurationholder has been deprecated, can't think of anything else. Interestingly the very same service works fine in my local IDE(GGTS 3.1.0), that means locally grailsApplication is getting injected, but when i create a war to deploy to a standalone tomcat, it stops getting injected.

    Read the article

  • Create link to Sitecore Item

    - by Zooking
    I know I have done this before but I can't seem to remember where or how. I want to create a link to an Item in Sitecore. This code: Sitecore.Data.Items.Item itm = Sitecore.Context.Database.GetItem(someID); return itm.Paths.Path.ToString(); Produces the following string: http://localhost/sitecore/content/Home/Item1/Item11/thisItem I would like to have this string instead: http://localhost/Item1/Item11/thisItem.aspx What is the correct way to get the path to the item? In this case I can't use a normal Sitecore link: Sitecore.Web.UI.WebControls.Link

    Read the article

  • Class design question (Disposable and singleton behavior)

    - by user137348
    The Repository class has singleton behavior and the _db implements the disposable pattern. As excepted the _db object gets disposed after the first call and because of the singleton behavior any other call of _db will crash. [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)] public class Repository : IRepository { private readonly DataBase _db; public Repository(DataBase db) { _db = db; } public int GetCount() { using(_db) { return _db.Menus.Count(); } } public Item GetItem(int id) { using(_db) { return _db.Menus.FirstOrDefault(x=>x.Id == id); } } } My question is, is there any way to design this class to work properly without removing the singleton behavior? The Repositoryclass will be serving big amount of requests.

    Read the article

  • How to put Listview items into String Array?

    - by user2851687
    Im developing an app and as the title says how to put items of listview into String array, not string array to listview but listview to string array. I've been searching for this but what I only found is putting String array items into listview. Please help me thank you in advance. To clarify this thread, the question is how to put listview items into String array. Thanks. :D Codes public class DailyPlanTab extends Activity implements OnItemClickListener { ListView dailyPlanList; ArrayList<DailyManager> taskList = new ArrayList<DailyManager>(); DatabaseDailyPlan db; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.dailyplan_layout); dailyPlanList = (ListView) findViewById(R.id.lvDailyPlanList); dailyPlanList.setOnItemClickListener(this); ImageView add = (ImageView) findViewById(R.id.ivDailyPlanAdd); add.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent newDailyIntent = new Intent(getApplicationContext(), NewDailyPlan.class); startActivity(newDailyIntent); } }); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); taskList.clear(); db = new DatabaseDailyPlan(getApplicationContext()); db.getWritableDatabase(); ArrayList<DailyManager> tempList = db.getTask(); for (int i = 0; i < tempList.size(); i++) { String getTask = tempList.get(i).getDaily_name(); String getDate = tempList.get(i).getDaily_date(); int getId = tempList.get(i).getDaily_id(); DailyManager dm = new DailyManager(); dm.setDaily_name(getTask); dm.setDaily_date(getDate); dm.setDaily_id(getId); taskList.add(dm); } dailyPlanList.setAdapter(new ListAdapter(this)); // db.close(); } public class ListAdapter extends BaseAdapter { LayoutInflater inflater; ViewHolder viewHolder; public ListAdapter(Context c) { // TODO Auto-generated constructor stub inflater = LayoutInflater.from(c); } @Override public int getCount() { // TODO Auto-generated method stub return taskList.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return position; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub if (convertView == null) { convertView = inflater.inflate(R.layout.row_checklist_item, null); viewHolder = new ViewHolder(); viewHolder.taskTitle = (TextView) convertView .findViewById(R.id.tvCheckListItem); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } viewHolder.taskTitle.setText("" + taskList.get(position).getDaily_name()); return convertView; } } public class ViewHolder { TextView taskTitle, taskDate; } @Override public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) { // TODO Auto-generated method stub int taskId = taskList.get(position).getDaily_id(); String taskName = taskList.get(position).getDaily_name(); String taskDate = taskList.get(position).getDaily_date(); Intent newPlan = new Intent(getApplicationContext(), DailyPlan.class); newPlan.putExtra("task_id", taskId); newPlan.putExtra("task_name", taskName); startActivity(newPlan); } next is the information of the item inside the listview public class DailyPlan extends Activity implements OnItemClickListener { final ArrayList<DailyManager> savedItems = new ArrayList<DailyManager>(); ListView checkList; Boolean nextItem = false; TempManager tm; DatabaseTemp dbTemp; Intent i; int taskId = -1; String taskName = " ", taskDate = null; DatabaseDailyPlan db; DailyManager dm; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.saved_dailyplan); checkList = (ListView) findViewById(R.id.lvCheckList); // checkList.setOnItemClickListener(this); try { i = getIntent(); taskId = i.getExtras().getInt("task_id"); taskName = i.getExtras().getString("task_name"); Toast.makeText(getApplicationContext(), "From new id is" + taskId, 5000).show(); } catch (Exception e) { } Button addList = (Button) findViewById(R.id.bAddList); addList.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub // openDialog("", false, -1); } }); if (nextItem) { // openDialog("", false, -1); } } public void refresh() { DailyPlan.this.onResume(); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); savedItems.clear(); dbTemp = new DatabaseTemp(getApplicationContext()); dbTemp.getWritableDatabase(); db = new DatabaseDailyPlan(getApplicationContext()); db.getWritableDatabase(); if (taskId != -1) { // / For Load ArrayList<DailyManager> savedList = db.getList(taskId); for (int i = 0; i < savedList.size(); i++) { String savedListItems = savedList.get(i).getDaily_list(); String savedListTitle = savedList.get(i).getDaily_name(); String savedListDate = savedList.get(i).getDaily_date(); int savedListId = savedList.get(i).getDaily_id(); DailyManager dm = new DailyManager(); dm.setDaily_list(savedListItems); dm.setDaily_name(savedListTitle); dm.setDaily_date(savedListDate); dm.setDaily_id(savedListId); savedItems.add(dm); } } else { // / For New } checkList.setAdapter(new ListAdapter(this)); } public class ListAdapter extends BaseAdapter { LayoutInflater inflater; ViewHolder viewHolder; public ListAdapter(Context c) { // TODO Auto-generated constructor stub inflater = LayoutInflater.from(c); } @Override public int getCount() { // TODO Auto-generated method stub return savedItems.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return position; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub if (convertView == null) { convertView = inflater.inflate(R.layout.row_checklist_item, null); viewHolder = new ViewHolder(); viewHolder.checkListItem = (TextView) convertView .findViewById(R.id.tvCheckListItem); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } viewHolder.checkListItem.setText(savedItems.get(position) .getDaily_list() + position); final int temp = position; return convertView; } } private class ViewHolder { TextView checkListItem; } @Override public void onItemClick(AdapterView<?> arg0, View arg1, int item, long arg3) { // TODO Auto-generated method stub // openDialog(savedItems.get(item).getDaily_name(), true, // savedItems.get(item).getDaily_id()); } }

    Read the article

  • ASP.NET MVC for the php/asp noob

    - by dotjosh
    I was talking to a friend today, who's foremost a php developer, about his thoughts on Umbraco and he said "Well they're apparently working feverishly on the new version of Umbraco, which will be MVC... which i still don't know what that means, but I know you like it." I ended up giving him a ground up explanation of ASP.NET MVC, so I'm posting this so he can link this to his friends and for anyone else who finds it useful.  The whole goal was to be as simple as possible, not being focused on proper syntax. Model-View-Controller (or MVC) is just a pattern that is used for handling UI interaction with your backend.  In a typical web app, you can imagine the *M*odel as your database model, the *V*iew as your HTML page, and the *C*ontroller as the class inbetween.  MVC handles your web request different than your typical php/asp app.In your php/asp app, your url maps directly to a php/asp file that contains html, mixed with database access code and redirects.In an MVC app, your url route is mapped to a method on a class (the controller).  The body of this method can do some database access and THEN decide which *V*iew (html/aspx page) should be displayed;  putting the controller in charge and not the view... a clear seperation of concerns that provides better reusibility and generally promotes cleaner code. Mysite.com, a quick example:Let's say you hit the following url in your application: http://www.mysite.com/Product/ShowItem?Id=4 To avoid tedious configuration, MVC uses a lot of conventions by default. For instance, the above url in your app would automatically make MVC search for a .net class with the name "Product" and a method named "ShowItem" based on the pattern of the url.  So if you name things properly, your method would automatically be called when you entered the above url.  Additionally, it would automatically map/hydrate the "int id" parameter that was in your querystring, matched by name.Product.cspublic class Product : Controller{    public ViewResult ShowItem(int id)    {        return View();    }} From this point you can write the code in the body of this method to do some database access and then pass a "bag" (also known as the ViewData) of data to your chosen *V*iew (html page) to use for display.  The view(html) ONLY needs to be worried about displaying the flattened data that it's been given in the best way it can;  this allows the view to be reused throughout your application as *just* a view, and not be coupled to HOW the data for that view get's loaded.. Product.cspublic class Product : Controller{    public ViewResult ShowItem(int id)    {        var database = new Database();        var item = database.GetItem(id);        ViewData["TheItem"] = item;        return View();    }} Again by convention, since the class' method name is "ShowItem", it'll search for a view named "ShowItem.aspx" by default, and pass the ViewData bag to it to use. ShowItem.aspx<html>     <body>      <%        var item =(Item)ViewData["TheItem"]       %>       <h1><%= item.FullProductName %></h1>     </body></html> BUT WAIT! WHY DOES MICROSOFT HAVE TO DO THINGS SO DIFFERENTLY!?They aren't... here are some other frameworks you may have heard of that use the same pattern in a their own way: Ruby On Rails Grails Spring MVC Struts Django    

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8  | Next Page >