Daily Archives

Articles indexed Thursday April 5 2012

Page 14/19 | < Previous Page | 10 11 12 13 14 15 16 17 18 19  | Next Page >

  • Testing if a list contains another list with Python

    - by None
    How can I test if a list contains another list. Say there was a function called contains: contains([1,2], [-1, 0, 1, 2]) # Returns [2, 3] (contains returns [start, end]) contains([1,3], [-1, 0, 1, 2]) # Returns False contains([1, 2], [[1, 2], 3) # Returns False contains([[1, 2]], [[1, 2], 3]) # Returns [0, 0] Edit: contains([2, 1], [-1, 0, 1, 2]) # Returns False contains([-1, 1, 2], [-1, 0, 1, 2]) # Returns False contains([0, 1, 2], [-1, 0, 1, 2]) # Returns [1, 3]

    Read the article

  • How to merge branches in Git by "hunk"

    - by user1316464
    Here's the scenario. I made a "dev" branch off the "master" branch and made a few new commits. Some of those changes are going to only be relevant to my local development machine. For example I changed a URL variable to point to a local apache server instead of the real URL that's posted online (I did this for speed during the testing phase). Now I'd like to incorporate my changes from the dev branch into the master branch but NOT those changes which only make sense in my local environment. I'd envisioned something like a merge --patch which would allow me to choose the changes I want to merge line by line. Alternatively maybe I could checkout the "master" branch, but keep the files in my working directory as they were in the "dev" branch, then do a git add --patch. Would that work?

    Read the article

  • Backbone events not firing (this.el undefined) & general feedback on use of the framework

    - by Leo
    I am very new to backbone.js and I am struggling a little. I figured out a way to get data from the server (in json) onto the screen successfully but am I doing it the right/best way? I know there is something wrong because the only view which contains a valid this.el is the parent view. I suspect that because of this, the events of the view are not firing ()... What is the best way forward? Here is the code: var surveyUrl = "/api/Survey?format=json&callback=?"; $(function () { AnswerOption = Backbone.Model.extend({}); AnswerOptionList = Backbone.Collection.extend({ initialize: function (models, options) { this.bind("add", options.view.render); } }); AnswerOptionView = Backbone.View.extend({ initialize: function () { this.answerOptionList = new AnswerOptionList(null, { view: this }); _.bindAll(this, 'render'); }, events: { "click .answerOptionControl": "updateCheckedState" //does not fire because there is no this.el }, render: function (model) { // Compile the template using underscore var template = _.template($("#questionAnswerOptionTemplate").html(), model.answerOption); $('#answerOptions' + model.answerOption.questionId + '>fieldset').append(template); return this; }, updateCheckedState: function (data) { //never hit... } }); Question = Backbone.Model.extend({}); QuestionList = Backbone.Collection.extend({ initialize: function (models, options) { this.bind("add", options.view.render); } }); QuestionView = Backbone.View.extend({ initialize: function () { this.questionlist = new QuestionList(null, { view: this }); _.bindAll(this, 'render'); }, render: function (model) { // Compile the template using underscore var template = _.template($("#questionTemplate").html(), model.question); $("#questions").append(template); //append answers using AnswerOptionView var view = new AnswerOptionView(); for (var i = 0; i < model.question.answerOptions.length; i++) { var qModel = new AnswerOption(); qModel.answerOption = model.question.answerOptions[i]; qModel.questionChoiceType = ChoiceType(); view.answerOptionList.add(qModel); } $('#questions').trigger('create'); return this; } }); Survey = Backbone.Model.extend({ url: function () { return this.get("id") ? surveyUrl + '/' + this.get("id") : surveyUrl; } }); SurveyList = Backbone.Collection.extend({ model: Survey, url: surveyUrl }); aSurvey = new Survey({ Id: 1 }); SurveyView = Backbone.View.extend({ model: aSurvey, initialize: function () { _.bindAll(this, 'render'); this.model.bind('refresh', this.render); this.model.bind('change', this.render); this.model.view = this; }, // Re-render the contents render: function () { var view = new QuestionView(); //{el:this.el}); for (var i = 0; i < this.model.attributes[0].questions.length; i++) { var qModel = new Question(); qModel.question = this.model.attributes[0].questions[i]; view.questionlist.add(qModel); } } }); window.App = new SurveyView(aSurvey); aSurvey.fetch(); }); -html <body> <div id="questions"></div> <!-- Templates --> <script type="text/template" id="questionAnswerOptionTemplate"> <input name="answerOptionGroup<%= questionId %>" id="answerOptionInput<%= id %>" type="checkbox" class="answerOptionControl"/> <label for="answerOptionInput<%= id %>"><%= text %></label> </script> <script type="text/template" id="questionTemplate"> <div id="question<%=id %>" class="questionWithCurve"> <h1><%= headerText %></h1> <h2><%= subText %></h2> <div data-role="fieldcontain" id="answerOptions<%= id %>" > <fieldset data-role="controlgroup" data-type="vertical"> <legend> </legend> </fieldset> </div> </div> </script> </body> And the JSON from the server: ? ({ "name": "Survey", "questions": [{ "surveyId": 1, "headerText": "Question 1", "subText": "subtext", "type": "Choice", "positionOrder": 1, "answerOptions": [{ "questionId": 1, "text": "Question 1 - Option 1", "positionOrder": 1, "id": 1, "createdOn": "\/Date(1333666034297+0100)\/" }, { "questionId": 1, "text": "Question 1 - Option 2", "positionOrder": 2, "id": 2, "createdOn": "\/Date(1333666034340+0100)\/" }, { "questionId": 1, "text": "Question 1 - Option 3", "positionOrder": 3, "id": 3, "createdOn": "\/Date(1333666034350+0100)\/" }], "questionValidators": [{ "questionId": 1, "value": "3", "type": "MaxAnswers", "id": 1, "createdOn": "\/Date(1333666034267+0100)\/" }, { "questionId": 1, "value": "1", "type": "MinAnswers", "id": 2, "createdOn": "\/Date(1333666034283+0100)\/" }], "id": 1, "createdOn": "\/Date(1333666034257+0100)\/" }, { "surveyId": 1, "headerText": "Question 2", "subText": "subtext", "type": "Choice", "positionOrder": 2, "answerOptions": [{ "questionId": 2, "text": "Question 2 - Option 1", "positionOrder": 1, "id": 4, "createdOn": "\/Date(1333666034427+0100)\/" }, { "questionId": 2, "text": "Question 2 - Option 2", "positionOrder": 2, "id": 5, "createdOn": "\/Date(1333666034440+0100)\/" }, { "questionId": 2, "text": "Question 2 - Option 3", "positionOrder": 3, "id": 6, "createdOn": "\/Date(1333666034447+0100)\/" }], "questionValidators": [{ "questionId": 2, "value": "3", "type": "MaxAnswers", "id": 3, "createdOn": "\/Date(1333666034407+0100)\/" }, { "questionId": 2, "value": "1", "type": "MinAnswers", "id": 4, "createdOn": "\/Date(1333666034417+0100)\/" }], "id": 2, "createdOn": "\/Date(1333666034377+0100)\/" }, { "surveyId": 1, "headerText": "Question 3", "subText": "subtext", "type": "Choice", "positionOrder": 3, "answerOptions": [{ "questionId": 3, "text": "Question 3 - Option 1", "positionOrder": 1, "id": 7, "createdOn": "\/Date(1333666034477+0100)\/" }, { "questionId": 3, "text": "Question 3 - Option 2", "positionOrder": 2, "id": 8, "createdOn": "\/Date(1333666034483+0100)\/" }, { "questionId": 3, "text": "Question 3 - Option 3", "positionOrder": 3, "id": 9, "createdOn": "\/Date(1333666034487+0100)\/" }], "questionValidators": [{ "questionId": 3, "value": "3", "type": "MaxAnswers", "id": 5, "createdOn": "\/Date(1333666034463+0100)\/" }, { "questionId": 3, "value": "1", "type": "MinAnswers", "id": 6, "createdOn": "\/Date(1333666034470+0100)\/" }], "id": 3, "createdOn": "\/Date(1333666034457+0100)\/" }, { "surveyId": 1, "headerText": "Question 4", "subText": "subtext", "type": "Choice", "positionOrder": 4, "answerOptions": [{ "questionId": 4, "text": "Question 4 - Option 1", "positionOrder": 1, "id": 10, "createdOn": "\/Date(1333666034500+0100)\/" }, { "questionId": 4, "text": "Question 4 - Option 2", "positionOrder": 2, "id": 11, "createdOn": "\/Date(1333666034507+0100)\/" }, { "questionId": 4, "text": "Question 4 - Option 3", "positionOrder": 3, "id": 12, "createdOn": "\/Date(1333666034507+0100)\/" }], "questionValidators": [{ "questionId": 4, "value": "3", "type": "MaxAnswers", "id": 7, "createdOn": "\/Date(1333666034493+0100)\/" }, { "questionId": 4, "value": "1", "type": "MinAnswers", "id": 8, "createdOn": "\/Date(1333666034497+0100)\/" }], "id": 4, "createdOn": "\/Date(1333666034490+0100)\/" }], "id": 1, "createdOn": "\/Date(1333666034243+0100)\/" })

    Read the article

  • fancybox image sometimes renders outside box

    - by Colleen
    I have the following django template: <script type="text/javascript" src="{{ STATIC_URL }}js/ jquery.fancybox-1.3.4.pack.js"></script> <link rel="stylesheet" href="{{ STATIC_URL }}css/ jquery.fancybox-1.3.4.css" type="text/css" media="screen" /> {% include "submission-form.html" with section="photos" %} <div class="commentables"> {% load thumbnail %} {% for story in objects %} <div class="image {% if forloop.counter|add:"-1"| divisibleby:picsinrow %}left{% else %}{% if forloop.counter| divisibleby:picsinrow %}right{% else %}middle{% endif %}{% endif %}"> {% if story.image %} {% thumbnail story.image size crop="center" as full_im %} <a rel="gallery" href="{% url post slug=story.slug %}"> <img class="preview" {% if story.title %} alt="{{ story.title }}" {% endif %} src="{{ full_im.url }}" full- image="{% if story.image_url %}{{ story.image_url }}{% else %} {{ story.image.url }}{% endif %}"> </a> {% endthumbnail %} {% else %} {% if story.image_url %} {% thumbnail story.image_url size crop="center" as full_im %} <a rel="gallery" href="{% url post slug=story.slug %}"> <img class="preview" {% if story.title %} alt="{{ story.title }}" {% endif %} src="{{ full_im.url }}" full- image="{{ story.image_url }}"> </a> {% endthumbnail %} {% endif %} {% endif %} </div> {% endfor %} {% if rowid != "last" %} <br style="clear: both" /> {% endif %} {% if not no_more_button %} <p style="text-align: right;" class="more-results"><a href="{% url images school_slug tag_slug %}">more...</a></p> {% endif %} </div> <script> $(document).ready(function(){ function changeattr(e){ var f = $(e.clone()); $(f.children()[0]).attr('src', $(f.children() [0]).attr("full-image")); $(f.children()[0]).attr('height', '500px'); return f[0].outerHTML; } $('.image a').each(function(idx, elem) { var e = $(elem); e.fancybox({ title: $(e.children()[0]).attr('alt'), content: changeattr(e) }); }); }); </script> and I'm occasionally getting weird display errors where the box will either not render anything at all (so it will show up as just a thin white bar, basically) or it will render only about 30 px wide, and position itself halfway down the page. In both cases, if I inspect element, I can see the "shadow" of the full picture, at the right size, with the right url. Image source doesnt' seem to make a difference, I'm getting no errors, and this is happening in both chrome and firefox. Does anyone have any ideas?

    Read the article

  • Accessing memory buffer after fread()

    - by xiongtx
    I'm confused as to how fread() is used. Below is an example from cplusplus.com /* fread example: read a complete file */ #include <stdio.h> #include <stdlib.h> int main () { FILE * pFile; long lSize; char * buffer; size_t result; pFile = fopen ( "myfile.bin" , "rb" ); if (pFile==NULL) {fputs ("File error",stderr); exit (1);} // obtain file size: fseek (pFile , 0 , SEEK_END); lSize = ftell (pFile); rewind (pFile); // allocate memory to contain the whole file: buffer = (char*) malloc (sizeof(char)*lSize); if (buffer == NULL) {fputs ("Memory error",stderr); exit (2);} // copy the file into the buffer: result = fread (buffer,1,lSize,pFile); if (result != lSize) {fputs ("Reading error",stderr); exit (3);} /* the whole file is now loaded in the memory buffer. */ // terminate fclose (pFile); free (buffer); return 0; } Let's say that I don't use fclose() just yet. Can I now just treat buffer as an array and access elements like buffer[i]? Or do I have to do something else?

    Read the article

  • How to inherit events between objects

    - by marduck19
    I need inherit events and properties for example move a picture around the form Y have this code to move the picture but y need create multiple images with the same behavior private void pictureBox_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { x = e.X; y = e.Y; } } private void pictureBox_MouseMove(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { pictureBox.Left += (e.X -x); pictureBox.Top += (e.Y - y); } }

    Read the article

  • writing into csv file

    - by arin
    I recived alarms in a form of text as the following NE=JKHGDUWJ3 Alarm=Data Center STALZ AC Failure Occurrence=2012/4/3 22:18:19 GMT+02:00 Clearance=Details=Cabinet No.=0, Subrack No.=40, Slot No.=0, Port No.=5, Board Type=EDS, Site No.=49, Site Type=HSJYG500 GSM, Site Name=Google1 . I need to fill it in csv file so later I can perform some analysis I came up with this namespace AlarmSaver { public partial class Form1 : Form { string filesName = "c:\\alarms.csv"; public Form1() { InitializeComponent(); } private void buttonSave_Click(object sender, EventArgs e) { if (!File.Exists(filesName)) { string header = "NE,Alarm,Occurrence,Clearance,Details"; File.AppendAllText(filesName,header+Environment.NewLine); } StringBuilder sb = new StringBuilder(); string line = textBoxAlarm.Text; int index = line.IndexOf(" "); while (index > 0) { string token = line.Substring(0, index).Trim(); line = line.Remove(0, index + 2); string[] values = token.Split('='); if (values.Length ==2) { sb.Append(values[1] + ","); } else { if (values.Length % 2 == 0) { string v = token.Remove(0, values[0].Length + 1).Replace(',', ';'); sb.Append(v + ","); } else { sb.Append("********" + ","); string v = token.Remove(0, values[0].Length + 1 + values[1].Length + 1).Replace(',', ';'); sb.Append(v + ","); } } index = line.IndexOf(" "); } File.AppendAllText(filesName, sb.ToString() + Environment.NewLine); } } } the results are as I want except when I reach the part of Details=Cabinet No.=0, Subrack No.=40, Slot No.=0, Port No.=5, Board Type=KDL, Site No.=49, Site Type=JDKJH99 GSM, Site Name=Google1 . I couldnt split them into seperate fields. as the results showing is as I want to split the details I want each element in details to be in a column to be somthin like its realy annoying :-) please help , thank you in advance

    Read the article

  • Cannot use ruby-debug19 with 1.9.3-p0?

    - by Stefan Kendall
    I run this: gem install ruby-debug19 And in my cucumber env.rb file, I have this: require 'ruby-debug' When I try to run, though, I get this exception: /home/skendall/.rvm/gems/ruby-1.9.3-p0/gems/ruby-debug-base19-0.11.25/lib/ruby_debug.so: undefined symbol: ruby_current_thread - /home/skendall/.rvm/gems/ruby-1.9.3-p0/gems/ruby-debug-base19-0.11.25/lib/ruby_debug.so (LoadError) What do I need to do to get ruby-debug to work with 1.9.3-p0?

    Read the article

  • Tracking Page views with the help of Flurry SDK?

    - by Shashank
    I have integrated mobile analytics in my iPhone app with the help of the Flurry analytics but I am not able to track page views. I have used the following code in my Application Delegate and passed an instance of UINavigationController in the place of navigationController [FlurryAPI logAllPageViews:navigationController]; But while checking the Page views in the Flurry website it is showing the message like this: You are not currently tracking Page View data. Is there something that I have to enable in the flurry website itself?

    Read the article

  • Passing data between android ListActivities in Java

    - by Will Janes
    I am new to Android! I am having a problem getting this code to work... Basically I Go from one list activity to another and pass the text from a list item through the intent of the activity to the new list view, then retrieve that text in the new list activity and then preform a http request based on value of that list item. Log Cat 04-05 17:47:32.370: E/AndroidRuntime(30135): FATAL EXCEPTION: main 04-05 17:47:32.370: E/AndroidRuntime(30135): java.lang.ClassCastException:android.widget.LinearLayout 04-05 17:47:32.370: E/AndroidRuntime(30135): at com.thickcrustdesigns.ufood.CatogPage$1.onItemClick(CatogPage.java:66) 04-05 17:47:32.370: E/AndroidRuntime(30135): at android.widget.AdapterView.performItemClick(AdapterView.java:284) 04-05 17:47:32.370: E/AndroidRuntime(30135): at android.widget.ListView.performItemClick(ListView.java:3731) 04-05 17:47:32.370: E/AndroidRuntime(30135): at android.widget.AbsListView$PerformClick.run(AbsListView.java:1959) 04-05 17:47:32.370: E/AndroidRuntime(30135): at android.os.Handler.handleCallback(Handler.java:587) 04-05 17:47:32.370: E/AndroidRuntime(30135): at android.os.Handler.dispatchMessage(Handler.java:92) 04-05 17:47:32.370: E/AndroidRuntime(30135): at android.os.Looper.loop(Looper.java:130) 04-05 17:47:32.370: E/AndroidRuntime(30135): at android.app.ActivityThread.main(ActivityThread.java:3691) 04-05 17:47:32.370: E/AndroidRuntime(30135): at java.lang.reflect.Method.invokeNative(Native Method) 04-05 17:47:32.370: E/AndroidRuntime(30135): at java.lang.reflect.Method.invoke(Method.java:507) 04-05 17:47:32.370: E/AndroidRuntime(30135): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907) 04-05 17:47:32.370: E/AndroidRuntime(30135): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:665) 04-05 17:47:32.370: E/AndroidRuntime(30135): at dalvik.system.NativeStart.main(Native Method) ListActivity 1 package com.thickcrustdesigns.ufood; import java.util.ArrayList; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONException; import org.json.JSONObject; import android.app.ListActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; public class CatogPage extends ListActivity { ListView listView1; Button btn_bk; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.definition_main); btn_bk = (Button) findViewById(R.id.btn_bk); listView1 = (ListView) findViewById(android.R.id.list); ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>(); nvp.add(new BasicNameValuePair("request", "categories")); ArrayList<JSONObject> jsondefs = Request.fetchData(this, nvp); String[] defs = new String[jsondefs.size()]; for (int i = 0; i < jsondefs.size(); i++) { try { defs[i] = jsondefs.get(i).getString("Name"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } uFoodAdapter adapter = new uFoodAdapter(this, R.layout.definition_list, defs); listView1.setAdapter(adapter); ListView lv = getListView(); lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { TextView tv = (TextView) view; String p = tv.getText().toString(); Intent i = new Intent(getApplicationContext(), Results.class); i.putExtra("category", p); startActivity(i); } }); btn_bk.setOnClickListener(new View.OnClickListener() { public void onClick(View arg0) { Intent i = new Intent(getApplicationContext(), UFoodAppActivity.class); startActivity(i); } }); } } **ListActivity 2** package com.thickcrustdesigns.ufood; import java.util.ArrayList; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONException; import org.json.JSONObject; import android.app.ListActivity; import android.os.Bundle; import android.widget.ListView; public class Results extends ListActivity { ListView listView1; enum Category { Chicken, Beef, Chinese, Cocktails, Curry, Deserts, Fish, ForOne { public String toString() { return "For One"; } }, Lamb, LightBites { public String toString() { return "Light Bites"; } }, Pasta, Pork, Vegetarian } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(R.layout.definition_main); listView1 = (ListView) findViewById(android.R.id.list); Bundle data = getIntent().getExtras(); String category = data.getString("category"); Category cat = Category.valueOf(category); String value = null; switch (cat) { case Chicken: value = "Chicken"; break; case Beef: value = "Beef"; break; case Chinese: value = "Chinese"; break; case Cocktails: value = "Cocktails"; break; case Curry: value = "Curry"; break; case Deserts: value = "Deserts"; break; case Fish: value = "Fish"; break; case ForOne: value = "ForOne"; break; case Lamb: value = "Lamb"; break; case LightBites: value = "LightBites"; break; case Pasta: value = "Pasta"; break; case Pork: value = "Pork"; break; case Vegetarian: value = "Vegetarian"; } ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>(); nvp.add(new BasicNameValuePair("request", "category")); nvp.add(new BasicNameValuePair("cat", value)); ArrayList<JSONObject> jsondefs = Request.fetchData(this, nvp); String[] defs = new String[jsondefs.size()]; for (int i = 0; i < jsondefs.size(); i++) { try { defs[i] = jsondefs.get(i).getString("Name"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } uFoodAdapter adapter = new uFoodAdapter(this, R.layout.definition_list, defs); listView1.setAdapter(adapter); } } Request package com.thickcrustdesigns.ufood; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONObject; import android.content.Context; import android.util.Log; import android.widget.Toast; public class Request { @SuppressWarnings("null") public static ArrayList<JSONObject> fetchData(Context context, ArrayList<NameValuePair> nvp) { ArrayList<JSONObject> listItems = new ArrayList<JSONObject>(); InputStream is = null; try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost( "http://co350-11d.projects02.glos.ac.uk/php/database.php"); httppost.setEntity(new UrlEncodedFormEntity(nvp)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); } catch (Exception e) { Log.e("log_tag", "Error in http connection" + e.toString()); } // convert response to string String result = ""; try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); InputStream stream = null; StringBuilder sb = null; while ((result = reader.readLine()) != null) { sb.append(result + "\n"); } stream.close(); result = sb.toString(); } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString()); } try { JSONArray jArray = new JSONArray(result); for (int i = 0; i < jArray.length(); i++) { JSONObject jo = jArray.getJSONObject(i); listItems.add(jo); } } catch (Exception e) { Toast.makeText(context.getApplicationContext(), "None Found!", Toast.LENGTH_LONG).show(); } return listItems; } } Any help would be grateful! Many Thanks EDIT Sorry very tired so missed out my 2nd ListActivity package com.thickcrustdesigns.ufood; import java.util.ArrayList; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONException; import org.json.JSONObject; import android.app.ListActivity; import android.os.Bundle; import android.widget.ListView; public class Results extends ListActivity { ListView listView1; enum Category { Chicken, Beef, Chinese, Cocktails, Curry, Deserts, Fish, ForOne { public String toString() { return "For One"; } }, Lamb, LightBites { public String toString() { return "Light Bites"; } }, Pasta, Pork, Vegetarian } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(R.layout.definition_main); listView1 = (ListView) findViewById(android.R.id.list); Bundle data = getIntent().getExtras(); String category = data.getString("category"); Category cat = Category.valueOf(category); String value = null; switch (cat) { case Chicken: value = "Chicken"; break; case Beef: value = "Beef"; break; case Chinese: value = "Chinese"; break; case Cocktails: value = "Cocktails"; break; case Curry: value = "Curry"; break; case Deserts: value = "Deserts"; break; case Fish: value = "Fish"; break; case ForOne: value = "ForOne"; break; case Lamb: value = "Lamb"; break; case LightBites: value = "LightBites"; break; case Pasta: value = "Pasta"; break; case Pork: value = "Pork"; break; case Vegetarian: value = "Vegetarian"; } ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>(); nvp.add(new BasicNameValuePair("request", "category")); nvp.add(new BasicNameValuePair("cat", value)); ArrayList<JSONObject> jsondefs = Request.fetchData(this, nvp); String[] defs = new String[jsondefs.size()]; for (int i = 0; i < jsondefs.size(); i++) { try { defs[i] = jsondefs.get(i).getString("Name"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } uFoodAdapter adapter = new uFoodAdapter(this, R.layout.definition_list, defs); listView1.setAdapter(adapter); } } Sorry again! Cheers guys!

    Read the article

  • Adding an unknown number of JComponents to a JPanel

    - by Matthew
    Good day, I am building an Applet (JApplet to be exact) and I sub divided that into two panels. The top panel is called DisplayPanel which is a custom class that extends JPanel. The bottom panel is called InputPanel which also extends JPanel. As mentioned above, I can add those two Panel's to the applet and they display fine. The next thing that I would like to do is have the InputPanel be able to hold a random number of JComponent Objects all listed veritcally. This means that the InputPanel should be able to have JButtons, JLabels, JTextFields etc thrown at it. I then want the InputPanel to display some sort of scrolling capability. The catch is that since these two panels are already inside my applet, I need the InputPanel to stay the same size as it was given when added to the Applet. So for example, if my applet (from the web-browser html code) was given the size 700,700, and then the DisplayPanel was 700 by 350, and the InputPanel was below it with the same dimensions, I want to then be able to add lots of JComponents like buttons, to the InputPanel and the panel would stay 700 x 350 in the same position that it is at, only the panel would have scroll bars if needed. I've played with many different combinations of JScrollPane, but just cannot get it. Thank you.

    Read the article

  • Combining ASP.NET controls with CSS

    - by Sniffer
    I am relatively new to website design and specifically working in ASP.NET, i am using CSS to style my site, but when i use ASP.NET Controls like GridView, Navigation controls, etc ... they are messed up by the style sheets, and you can't see that until you run the website, because the controls are translated to HTML and so affected by CSS in a way that you can't predict, how to solve this, and is there a better way to layout and desgin sites in ASP.NET.

    Read the article

  • folder deleting not working

    - by user1150440
    If System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(Server.MapPath("images/TravelogueGallery/" & getMaxID()))) Then System.IO.Directory.Delete(HttpContext.Current.Server.MapPath("images/TravelogueGallery/" & getMaxID()), True) End If I am using the above code snippet to delete a directory but i get this error "'G:\Projects\Latest\LTCIndia 05-04-12 1415\images\TravelogueGallery\19' is not a valid virtual path. " Whats wrong with the code?

    Read the article

  • C# Object Problem - Can't Solve It

    - by user612041
    I'm getting the error 'Object reference not set to an instance of an object'. I've tried looking at similar problems but genuinely cannot see what the problem is with my program. The line of code that I am having an error with is: labelQuestion.Text = table.Rows[0]["Question"].ToString(); Here is my code in its entirety: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data.OleDb; using System.Data.Sql; using System.Data.SqlClient; namespace Quiz_Test { public partial class Form1 : Form { public Form1() { InitializeComponent(); } String chosenAnswer, correctAnswer; DataTable table; private void Form1_Load(object sender, EventArgs e) { //declare connection string using windows security string cnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Hannah\\Desktop\\QuizQuestions.accdb"; //declare Connection, command and other related objects OleDbConnection conGet = new OleDbConnection(cnString); OleDbCommand cmdGet = new OleDbCommand(); //try //{ //open connection conGet.Open(); //String correctAnswer; cmdGet.CommandType = CommandType.Text; cmdGet.Connection = conGet; cmdGet.CommandText = "SELECT * FROM QuizQuestions ORDER BY rnd()"; OleDbDataReader reader = cmdGet.ExecuteReader(); reader.Read(); labelQuestion.Text = table.Rows[0]["Question"].ToString(); radioButton1.Text = table.Rows[0]["Answer 1"].ToString(); radioButton2.Text = table.Rows[0]["Answer 2"].ToString(); radioButton3.Text = table.Rows[0]["Answer 3"].ToString(); radioButton4.Text = table.Rows[0]["Answer 4"].ToString(); correctAnswer = table.Rows[0]["Correct Answer"].ToString(); ; conGet.Close(); } private void btnSelect_Click(object sender, EventArgs e) { String cnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Hannah\\Desktop\\QuizQuestions.accdb"; //declare Connection, command and other related objects OleDbConnection conGet = new OleDbConnection(cnString); OleDbCommand cmdGet = new OleDbCommand(); //try { //open connection conGet.Open(); cmdGet.CommandType = CommandType.Text; cmdGet.Connection = conGet; cmdGet.CommandText = "SELECT * FROM QuizQuestions ORDER BY rnd()"; // select all columns in all rows OleDbDataReader reader = cmdGet.ExecuteReader(); reader.Read(); if (radioButton1.Checked) { chosenAnswer = reader["Answer 1"].ToString(); } else if (radioButton2.Checked) { chosenAnswer = reader["Answer 2"].ToString(); } else if (radioButton3.Checked) { chosenAnswer = reader["Answer 3"].ToString(); } else { chosenAnswer = reader["Answer 4"].ToString(); } if (chosenAnswer == reader["Correct Answer"].ToString()) { //chosenCorrectly++; MessageBox.Show("You have got this answer correct"); //label2.Text = "You have got " + chosenCorrectly + " answers correct"; } else { MessageBox.Show("That is not the correct answer"); } } } } } I realise the problem isn't too big but I can't see how my declaration timings are wrong

    Read the article

  • Extracting a number from a 1-word string

    - by Kyle
    In this program I am trying to make, I have an expression (such as "I=23mm", or "H=4V") and I am trying to extract the 23 (or the 4) out of it, so that I can turn it into an integer. The problem I keep running into is that since the expression I am trying to take the numbers out of is 1 word, I cannot use split() or anything. One example I saw but wouldnt work was - I="I=2.7A" [int(s) for s in I.split() if s.isdigit()] This wouldnt work because it only takes the numbers are are delimited by spaces. If there was a number in the word int078vert, it wouldnt extract it. Also, mine doesnt have spaces to delimit. I tried one that looked like this, re.findall("\d+.\d+", "Amps= 1.4 I") but it didnt work either, because the number that is being passed is not always 2 digits. It could be something like 5, or something like 13.6. What code do I need to write so that if I pass a string, such as I="I=2.4A" or I="A=3V" So that I can extract only the number out of this string? (and do operations on it)? There are no spaces or other constant chars that I can delimit by.

    Read the article

  • How do I keep users from spoofing data through a form?

    - by Jonathan
    I have a site which has been running for some time now that uses a great deal of user input to build the site. Naturally there are dozens of forms on the site. When building the site, I often used hidden form fields to pass data back to the server so that I know which record to update. an example might be: <input type="hidden" name="id" value="132" /> <input type="text" name="total_price" value="15.02" /> When the form is submitted, these values get passed to the server and I update the records based on the data passed (i.e. the price of record 132 would get changed to 15.02). I recently found out that you can change the attributes and values via something as simple as firebug. So...I open firebug and change the id value to "155" and the price value to "0.00" and then submit the form. Viola! I view product number 155 on the site and it now says that it's $0.00. This concerns me. How can I know which record to update without either a query string (easily modified) or a hidden input element passing the id to the server? And if there's no better way (I've seen literally thousands of websites that pass the data this way), then how would I make it so that if a user changes these values, the data on the server side is not executed (or something similar to solve the issue)? I've thought about encrypting the id and then decrypting it on the other side, but that still doesn't protect me from someone changing it and just happening to get something that matches another id in the database. I've also thought about cookies, but I've heard that those can be manipulated as well. Any ideas? This seems like a HUGE security risk to me.

    Read the article

  • Identifying the parts of this typedef struct in C?

    - by Tommy
    Please help me identify the parts of this typdef struct and what each part does and how it can be used: typedef struct my_struct { int a; int b; int c; } struct_int, *p_s; struct_int struct_array[5]; my_struct is the...? struct_int is the...? *p_s is the...and can be used to point to what? struct_array is the...? Also, when creating the array of structs, why do we use struct_int instead of my_struct ? Thank You!

    Read the article

  • PHP & AJAX SEO - For users with javascript and non javascript

    - by RussellHarrower
    So I understand this may come across as a open question, but I need away to solve this issue. I can either make the site do ajax request that load the body content, or I can have links that re-loads the whole page. I need the site to be SEO compliant, and I would really like the header to not re-load when the content changes, the reason is that we have a media player that plays live audio. Is there away that if Google BOT or someone without ajax enabled it does the site like normal href but if ajax or javascript allowed do it the ajax way.

    Read the article

  • jQuery Tools - Range Input with Mousewheel support

    - by pspahn
    I've got a nice looking horizontal scroller that uses the Range Input feature of jQ Tools. Mouse wheel scrolling support would be awesome, and I'm sure it can work, just not sure how to get it set up. I've got the generic setup: var scroll = jQuery('#scroll'); jQuery(':range').rangeinput({ speed: 0, progress: true, onSlide: function(ev, step) { scroll.css({left: -step}); }, change: function(e, i) { scroll.animate({left: -i}, "fast"); } }); The doc page ( http://jquerytools.org/documentation/toolbox/mousewheel.html ) for mousewheel gives an example: $("#myelement").mousewheel(function(event, delta) { }); But I'm not sure how this hooks in. Other tools in the package simply allow the option: mousewheel: true Unfortunately that doesn't work on range input. Any advice appreciated. Thank you.

    Read the article

  • How can I install ruby on rails with rvm?

    - by yeahthatguyrightthere
    I've been searching around on how to install it through the terminal on my mac. I'm using snow leopard. When I use the command: rvm install 1.9.3 I've also followed the other procedures that led me up to this to install, right now the current version is 1.8.3 Error running './configure --prefix="/Users/jose/.rvm/usr" ', please read /Users/jose/.rvm/log/ruby-1.9.3-p125/yaml/configure.log Then it mentions something about xcode and autoreconf was not found in the PATH. Error running 'patch -F 25 -p1 -N -f <"/Users/jose/.rvm/patches/ruby/1.9.3/p125/xcode-debugopt-fix-e34840.diff"',please read /Users/jose/.rvm/log/ruby-1.9.3-p125/patch.apply.xcode-debugopt-fix-r34840.log rvm requires autoreconf to install the selected ruby interpreter however autoreconf was not found in the PATH I been trying for awhile now, and found out i need to have Xcode for snow leopard which I cannot find. So my last option will be to upgrade to lion but I don't know about upgrading. Kind of scared to upgrade and everything becomes buggy.

    Read the article

  • In browser trusted application Silverlight 5

    - by Philippe
    With the new Silverlight 5, we can now have a In-Browser elevated-trust application. However, I'm experiencing some problems to deploy the application. When I am testing the application from Visual Studio, everything works fine because it automatically gives every right if the website is hosted on the local machine (localhost, 127.0.0.1). I saw on MSDN that I have to follow 3 steps to make it work on any website: Signed the XAP - I did it following the Microsoft tutorial Install the Trusted publishers certificate store - I did it too following the Microsoft Tutorial Adding a Registry key with the value : AllowElevatedTrustAppsInBrowser. The third step is the one I am the most unsure about. Do we need to add this registry key on the local machine or on the server ? Is there any automatic function in silverlight to add this key or its better to make a batchfile? Even with those 3 steps, the application is still not working when called from another url than localhost. Does anybody has successfully implemented a In-browser elevated-trust application? Do you see what I'm doing wrong? Thank you very much! Philippe, Sources: - http://msdn.microsoft.com/en-us/library/gg192793(v=VS.96).aspx - http://pitorque.de/MisterGoodcat/post/Silverlight-5-Tidbits-Trusted-applications.aspx

    Read the article

  • How to fix the header and first row in a UITableView

    - by Arturo Guzman
    I´m new trying to make some apps using objective c, so I´ve an idea using uitableview but I don't imagine how can I get this. I´m trying to do something like you do in a spreadsheet where you have a fixed header and the first column too So when scroll the uitableview vertically the header will stay visible at top of the table and rows will change And finally when you scroll in horizontal direction the first cell of the row will stay visible and will change the header depending of how you scroll the uitableview I hope you could give me an idea how to get this, because I don't imagine how to do this, also I don´t have a lot of experience with this programming language. Thanks!

    Read the article

  • importing pywiiuse to test out

    - by Patrick Burton
    This is probably a simple problem. But I downloaded the pywiiuse library from here and I also downloaded the examples. However when I try to run one of the examples I end up with import issues. I'm not certain I have everything configured properly to run. One error I receive when trying to run example.py: Press 1&2 Traceback (most recent call last): File "example.py", line 73, in <module> wiimotes = wiiuse.init(nmotes) File "/home/thed0ctor/Descargas/wiiuse-0.12/wiiuse/__init__.py", line 309, in init dll = ctypes.cdll.LoadLibrary('libwiiuse.so') File "/usr/lib/python2.7/ctypes/__init__.py", line 431, in LoadLibrary return self._dlltype(name) File "/usr/lib/python2.7/ctypes/__init__.py", line 353, in __init__ self._handle = _dlopen(self._name, mode) OSError: libwiiuse.so: cannot open shared object file: No such file or directory I'm really just starting out with this library and don't really see any documentation on how to configure pywiiuse so any help is much appreciated.

    Read the article

  • Container of shared_ptr's but iterate with raw pointers

    - by Sean Lynch
    I have a class that holds a list containing boost::shared_ptrs to objects of another class. The class member functions that give access to the elemets in the list return raw pointers. For consistency I'd also like to be able to iterate with raw pointers instead of shared_ptrs. So when I dereference the list iterator, I'd like to get raw pointer, not a shared_ptr. I assume I need to write a custom iterator for this. Is this correct? If so can someone point me in the right direction - I've never done this before.

    Read the article

  • Physical Directories vs. MVC View Paths

    - by Rick Strahl
    This post falls into the bucket of operator error on my part, but I want to share this anyway because it describes an issue that has bitten me a few times now and writing it down might keep it a little stronger in my mind. I've been working on an MVC project the last few days, and at the end of a long day I accidentally moved one of my View folders from the MVC Root Folder to the project root. It must have been at the very end of the day before shutting down because tests and manual site navigation worked fine just before I quit for the night. I checked in changes and called it a night. Next day I came back, started running the app and had a lot of breaks with certain views. Oddly custom routes to these controllers/views worked, but stock /{controller}/{action} routes would not. After a bit of spelunking I realized that "Hey one of my View Folders is missing", which made some sense given the error messages I got. I looked in the recycle bin - nothing there, so rather than try to figure out what the hell happened, just restored from my last SVN checkin. At this point the folders are back… but… view access  still ends up breaking for this set of views. Specifically I'm getting the Yellow Screen of Death with: CS0103: The name 'model' does not exist in the current context Here's the full error: Server Error in '/ClassifiedsWeb' Application. Compilation ErrorDescription: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.Compiler Error Message: CS0103: The name 'model' does not exist in the current contextSource Error: Line 1: @model ClassifiedsWeb.EntryViewModel Line 2: @{ Line 3: ViewBag.Title = Model.Entry.Title + " - " + ClassifiedsBusiness.App.Configuration.ApplicationName; Source File: c:\Projects2010\Clients\GorgeNet\Classifieds\ClassifiedsWeb\Classifieds\Show.cshtml    Line: 1 Compiler Warning Messages: Show Detailed Compiler Output: Show Complete Compilation Source: Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.272 Here's what's really odd about this error: The views now do exist in the /Views/Classifieds folder of the project, but it appears like MVC is trying to execute the views directly. This is getting pretty weird, man! So I hook up some break points in my controllers to see if my controller actions are getting fired - and sure enough it turns out they are not - but only for those views that were previously 'lost' and then restored from SVN. WTF? At this point I'm thinking that I must have messed up one of the config files, but after some more spelunking and realizing that all the other Controller views work, I give up that idea. Config's gotta be OK if other controllers and views are working. Root Folders and MVC Views don't mix As I mentioned the problem was the fact that I inadvertantly managed to drag my View folder to the root folder of the project. Here's what this looks like in my FUBAR'd project structure after I copied back /Views/Classifieds folder from SVN: There's the actual root folder in the /Views folder and the accidental copy that sits of the root. I of course did not notice the /Classifieds folder at the root because it was excluded and didn't show up in the project. Now, before you call me a complete idiot remember that this happened by accident - an accidental drag probably just before shutting down for the night. :-) So why does this break? MVC should be happy with views in the /Views/Classifieds folder right? While MVC might be happy, IIS is not. The fact that there is a physical folder on disk takes precedence over MVC's routing. In other words if a URL exists that matches a route the pysical path is accessed first. What happens here is that essentially IIS is trying to execute the .cshtml pages directly without ever routing to the Controller methods. In the error page I showed above my clue should have been that the view was served as: c:\Projects2010\Clients\GorgeNet\Classifieds\ClassifiedsWeb\Classifieds\Show.cshtml rather than c:\Projects2010\Clients\GorgeNet\Classifieds\ClassifiedsWeb\Views\Classifieds\Show.cshtml But of course I didn't notice that right away, just skimming to the end and looking at the file name. The reason that /classifieds/list actually fires that file is that the ASP.NET Web Pages engine looks for physical files on disk that match a path. IOW, when calling Web Pages you drop the .cshtml off the Razor page and IIS will serve that just fine. So: /classifieds/list looks and tries to find /classifieds/list.cshtml and executes that script. And that is exactly what's happening. Web Pages is trying to execute the .cshtml file and it fails because Web Pages knows nothing about the @model tag which is an MVC specific template extension. This is why my breakpoints in the controller methods didn't fire and it also explains why the error mentions that the @model key word is invalid (@model is an MVC provided template enhancement to the Razor Engine). The solution of course is super simple: Delete the accidentally created root folder and the problem is solved. Routing and Physical Paths I've run into problems with this before actually. In the past I've had a number of applications that had a physical /Admin folder which also would conflict with an MVC Admin controller. More than once I ended up wondering why the index route (/Admin/) was not working properly. If a physical /Admin folder exists /Admin will not route to the Index action (or whatever default action you have set up, but instead try to list the directory or show the default document in the folder. The only way to force the index page through MVC is to explicitly use /Admin/Index. Makes perfect sense once you realize the physical folder is there, but that's easy to forget in an MVC application. As you might imagine after a few times of running into this I gave up on the Admin folder and moved everything into MVC views to handle those operations. Still it's one of those things that can easily bite you, because the behavior and error messages seem to point at completely different  problems. Moral of the story is: If you see routing problems where routes are not reaching obvious controller methods, always check to make sure there's isn't a physical path being mapped by IIS instead. That way you won't feel stupid like I did after trying a million things for about an hour before discovering my sloppy mousing behavior :-)© Rick Strahl, West Wind Technologies, 2005-2012Posted in MVC   IIS7   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

< Previous Page | 10 11 12 13 14 15 16 17 18 19  | Next Page >