text
stringlengths
8
267k
meta
dict
Q: SQLite - Select and Integer type I have a problem. I want to access to an specific register in a SQLite table. String[] campos = new String[] {"codInterno"}; String[] arg2 = new String[] {strId}; Cursor c = db.query("Incidentes", campos, "codReg=?", arg2, null, null, null); so I need to have the register with field codInterno where codReg = strId ... thats no problem. Now i want to access an specific register, i have to put codInterno - 1, and access using a select where codInterno = codInterno - 1 .. This field is an integer, and always when i have to use a condition, i have to use an String array. How can i put an integer parameter as condition in a SELECT? A: In your arg2 parameter you should use something like String arg2[] = new { stdId, Integer.toString(codInterno) };
{ "language": "en", "url": "https://stackoverflow.com/questions/7599564", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get my wifi hotspot ssid in my current android system I have a problem that I couldn't find my wifi hotspot ssid in my Android system. I found many information from google, but nothing helpful. Please help me to solve it. A: Here: http://www.androidjavadoc.com/2.3/android/net/wifi/WifiManager.html is the full documentation on the WifiManager. Note that some of the methods are only available through inspection, as is the method you need getWifiApConfiguration. WifiManager wifimanager = (WifiManager) getSystemService(WIFI_SERVICE); Method[] methods = wifimanager.getClass().getDeclaredMethods(); for (Method m: methods) { if (m.getName().equals("getWifiApConfiguration")) { WifiConfiguration config = (WifiConfiguration)m.invoke(wifimanager); // here, the "config" variable holds the info, your SSID is in // config.SSID } } O, and because this stuff is marked hidden, it can change or be completely removed in any future version of Android. So, don't rely on it too much on "official" apps, unless you make that very clear. A: You can use WifiManager and WifiInfo for getting Wifi SSID WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); Log.d("wifiInfo", wifiInfo.toString()); Log.d("SSID",wifiInfo.getSSID()); Also add Permission in your Manifest file. <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"> </uses-permission> A: Have you tried using WifiInfo.getSSID() ? http://developer.android.com/reference/android/net/wifi/WifiInfo.html#getSSID%28%29
{ "language": "en", "url": "https://stackoverflow.com/questions/7599569", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: CanvasAuthorize C# SDK Infinite Loop I'm looking to try and get an MVC3 Canvas app working with the Facebook C# SDK, but am struggling to allow permissions - Below is my code, and when I open the app I get the 'Allow / Deny' dialog but when I click allow I get redirected to my app and the same dialog appears again (And again and so on no matter how many times I click allow)? I guess I am missing something obvious... If I take the user_groups permission out it works fine, I just can't access the persons groups. [CanvasAuthorize(Permissions = "user_groups")] public class HomeController : Controller { public ActionResult Index() { IFacebookApplication settings = FacebookApplication.Current; if (settings != null) { //CanvasPage = settings.CanvasPage; //AppId = settings.AppId; } FacebookWebContext facebookContext = FacebookWebContext.Current; FacebookSignedRequest signedRequest = facebookContext.SignedRequest; var client = new FacebookWebClient(facebookContext.AccessToken); dynamic me = client.Get("me"); var friends = client.Get("me/friends"); var groups = client.Get("me/groups"); ViewBag.Name = me.name; ViewBag.Id = me.id; JavaScriptSerializer sr = new JavaScriptSerializer(); var fbFriends = sr.Deserialize<FBFriends>(friends.ToString()); ViewData["friends"] = fbFriends.data; return View("Friends"); } } Any help, tips or code samples greatly appreciated. A: make sure u have set the appid and appsecret correctly. download the source code and checkout the "samples" folder, there are a bunch of asp.net mvc samples.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599574", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP recursion issue My idea is simple: if child->indent, if parent->make bold. Lets say p0 is the parent of p1 and p2, p3 and p4 are the childs of p1. p5 is the independent page like p0. So what i wanna get is p0 (bold font) [3px]p1(bold font) [ 6px ]p3 [ 6px ]p4 [3px]p2 p5 (bold font) The problem is, I can't figure out. how to realize my idea. Tried given functions. No success. It works but indents only first level childs. My recursive php function looks like that function generateOptions($parent, $level, $padding, $db) { $result=$db->query("SELECT id, name FROM menu WHERE parent='$parent' AND showinmenu!='0'"); if($level == 0) {$padding=''; $optstyle='bold';} else {$optstyle='std'; $padding='&nbsp;';} while($data=$result->fetch_row()){ echo generateOption($optstyle.'option', $data, $padding); generateOptions($data[0], $level++, $padding, $db); } } function generateOption($type,$data, $padding){ switch($type){ case 'boldoption': return '<option class="bold" value="'.$data[0].'">'.$padding.$data[1]."</option>\n"; break; case 'stdoption': return '<option class="std" value="'.$data[0].'">'.$padding.$data[1]."</option>\n"; break; } } And here is the screenshot of my db table. http://prntscr.com/39461 The final working result function generateOptions($parent, $level, $padding, $db) { $result=$db->query("SELECT id, name FROM menu WHERE parent='$parent' AND showinmenu!='0'"); $spacer = '&nbsp;&nbsp;'; $padding = str_repeat($spacer, $level); while($data=$result->fetch_row()){ $children_html = generateOptions($data[0], $level+1, $padding, $db); $optstyle = empty($children_html) ? 'std' : 'bold'; $html .= generateOption($optstyle.'option', $level, $data, $padding); $html .= $children_html; } return $html; } function generateOption($type, $level, $data, $padding){ $bgcolor=array('0'=>'#f66e02','1'=>'#FF9C4D', '2'=>'#FF9C4D'); $fontcolor=array('0'=>'#fff','1'=>'#000', '2'=>'#000'); switch($type){ case 'boldoption': return '<option class="bold" style="background-color:'.$bgcolor[$level].'; color:'.$fontcolor[$level].'" value="'.$data[0].'">'.$padding.$data[1]."</option>\n"; break; case 'stdoption': return '<option class="std" value="'.$data[0].'">'.$padding.$data[1]."</option>\n"; break; } } A: Your indentation problem you can easily solve by multiplying the $level by the number of pixels for a simple indent (3px in your case). For the bold problem you need a different approach as in your current code, you don't know if the item has any children. The solution to that would be to first get the children in a variable, then add the bold style if any exist, echo the item and only then process the children. Personally I would first get all data from the database in one pass, then build the hierarchical structure and then use a different function to generate the html. See for example this question for more details. Edit: Based on your updated question; you can easily optimize it and get rid of the query in the while loop (I'd still go for the option in the previous paragraph by the way...): * *Don't echo anything, just return a string from your function *Get rid of the query in the while function *Swap the echo and the function call lines The result in your function would be something like: .... $html = ''; while (...) { $children_html = generateOptions($data[0], $level+1, $padding, $db); $optstyle = empty($children_html) ? 'std' : 'bold'; $html .= generateOption($optstyle.'option', $data, $padding); $html .= $children_html; } return $html; and just do a echo generateOptions(...) where you called the function before. A: It looks like you might need to be adding more &nbps;'s to your padding where you're just assigning it to one space. else {$optstyle='std'; $padding='&nbsp;';} to else {$optstyle='std'; $padding .='&nbsp;';} A: You are trying to map a flat data structure (list) into a tree visually. Before you can do this in a simple manner, you need to gather the date that is influencing the display to the list. E.g. you could add a level per entry (1, 2 or 3), which looks like that being your recursive structure already! Then you pass the modified list to the display routine, that only needs to decide based on the level how to display the entry, for each level: * *font-weight: bold; *padding-left: 3px; font-weight: bold; *padding-left: 6px; The easiest thing to achieve that is to assing a class attribute to the elements parent HTML tag like level-1, level-2 etc.. You already have a $level variable, but I see an error, you increment it all the time, but you only need to pass the value: generateOptions($data[0], $level+1, $padding, $db); It might be that this already solves your issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599575", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Update products programmatically in Magento I'm working on a script that will create or update products in my catalog. The script works fine when the product needs to be created, but it fails when the product already exists in the database giving me (many times) the following messages : 2011-09-30T08:00:53+00:00 ERR (3): Recoverable Error: Argument 3 passed to Mage_Catalog_Model_Resource_Eav_Mysql4_Abstract::_canUpdateAttribute() must be an array, null given, called in ... 2011-09-30T08:00:53+00:00 ERR (3): Recoverable Error: Argument 3 passed to Mage_Eav_Model_Entity_Abstract::_canUpdateAttribute() must be an array, null given, called in ... 2011-09-30T08:00:53+00:00 ERR (3): Warning: array_key_exists() [function.array-key-exists]: The second argument should be either an array or an object in ... I've been looking at the method quoted in the message, but I can't find any reason why the script fails. The script first try to load a product using : $product = Mage::getModel('catalog/product')->loadByAttribute('sku', $sku); and then test if the product was retrieved using a simple if(!$product) { //creation }. All the code that follow the if statement is shared for creation or update and consists of setter calls on product object. Here is the code I use : $product = Mage::getModel('catalog/product')->loadByAttribute('sku', $sku); if(!$product) { // the product doesn't exist yet $product = new Mage_Catalog_Model_Product(); $product->setSku($sku); $product->setTypeId(Mage_Catalog_Model_Product_Type::TYPE_SIMPLE); $product->setCreatedAt(strtotime('now')); } // setters calls $product->setTeinte(trim((string)$record->web_teinte)); // ... // finally save the product $product->save(); Maybe someone has already faced the same problem. Any help is welcome ! Thank you. A: Chances are, in your "setter calls" you are trying to set something that cannot be directly set on $product. It could even be the "setTeinte" as I am not sure what that is trying to set. But as we cannot see all your code, it is a little difficult to say, so as I guide, take a look at the code below, which sets some information directly on the product and then stock levels. It does therefore, illustrate how certain data has to be set. I hope it helps. $SKU = (string)$XMLproduct->Sku; $product = Mage::getModel('catalog/product')->loadByAttribute('sku',$SKU); if ($product) { //Product found, so we need to update it in Magento. $product->setName((string)$XMLproduct->Name); $product->setPrice((real)$XMLproduct->SalePrice); //$product->setDescription((string)$XMLproduct->LongDescription); //$product->setShortDescription((string)$XMLproduct->Description); $product->save(); $productId = $product->getId(); $stockItem =Mage::getModel('cataloginventory/stock_item')->loadByProduct($productId); $stockItemId = $stockItem->getId(); $stockItem->setData('manage_stock', 1); $stockItem->setData('qty', (integer)$XMLproduct->QtyInStock); $stockItem->save(); echo $SKU," Updated: Name: '",(string)$XMLproduct->Name,"', Price: ",(real)$XMLproduct->SalePrice,", Stock level: ",$XMLproduct->QtyInStock,PHP_EOL; $updated++; } A: Adding Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID); before saving product solves the error. The sample code below updates product's cost. Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID); $productId = 160; $newCost = 80; $product = Mage::getModel('catalog/product')->load($productId); $product->setCost($newCost)->save(); A: Easy with Magento API, also can use methods.... example $data = array('qty'=>1, 'is_in_stock'=>1) $stockModel = new Mage_CatalogInventory_Model_Stock_Item_Api; $stockModel->update($product_id, $data); Also can set Admin mode Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID); A: //here what i use in codeigniter function updateProducts(){ $params = array('name' => 'adminhtml'); // frontend or adminhtml $this->load->library('magento', $params); error_reporting(E_ALL | E_STRICT); //$mageFilename = 'app/Mage.php'; //require_once $mageFilename; Mage::setIsDeveloperMode(true); umask(0); Mage::app(); Mage::app()->setCurrentStore(Mage::getModel('core/store')->load(Mage_Core_Model_App::ADMIN_STORE_ID)); $obj = new stdClass(); $obj->Sku = '25484684'; $obj->Name = 'test product 2'; $obj->SalePrice = 55; $obj->LongDescription = 'test product long decription.test product long decription.test product long decription.'; $obj->Description = 'short descrption'; $res = $this->updateMagentoProduct($obj); //dumb($res); } function updateMagentoProduct($XMLproduct){ $SKU = (string)$XMLproduct->Sku; $product = Mage::getModel('catalog/product')->loadByAttribute('sku',$SKU); if (!$product) {//insert new product $product = Mage::getModel('catalog/product'); $product->setSku($SKU); } //$product = new Mage_Catalog_Model_Product(); // Build the product $product->setAttributeSetId(4); // 4 means Default AttributeSet $product->setTypeId('simple'); $product->setName((string)$XMLproduct->Name); $product->setCategoryIds(array(2,3,4,5,6,7)); $product->setWebsiteIDs(array(1)); # Website id, 1 is default //$product->setWebsiteIds(array(Mage::app()->getStore(true)->getWebsite()->getId())); //$product->setWebsiteIDs(array(1)); # Website id, my is 1 (default frontend) $product->setDescription((string)$XMLproduct->LongDescription); $product->setShortDescription((string)$XMLproduct->Description); $product->setPrice((real)$XMLproduct->SalePrice); # Custom created and assigned attributes //$product->setHeight('my_custom_attribute1_val'); //$product->setWidth('my_custom_attribute2_val'); //$product->setDepth('my_custom_attribute3_val'); //$product->setType('my_custom_attribute4_val'); //Default Magento attribute $product->setWeight(1.0); $product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH); $product->setStatus(1); $product->setTaxClassId(0); # My default tax class /*$product->setStockData(array( 'is_in_stock' => 1, 'qty' => 99999 ));*/ $product->setCreatedAt(strtotime('now')); try { $product->save(); $productId = $product->getId(); $stockItem =Mage::getModel('cataloginventory/stock_item')->loadByProduct($productId); $stockItemId = $stockItem->getId(); $stockItem->setData('manage_stock', 1); $stockItem->setData('qty', 99999);//(integer)$XMLproduct->QtyInStock $stockItem->save(); echo '<h5>'.$SKU," Updated: Name: '",(string)$XMLproduct->Name,"', Price: ",(real)$XMLproduct->SalePrice,", Stock level: ",PHP_EOL.'</h5>'; } catch (Exception $ex) { //Handle the error echo '<h5>'.$ex->getMessage().'</h5>'; } // assign product to the default website return $product->save(); } A: <?php Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID); $product = Mage::getModel('catalog/product'); $product // ->setStoreId(1) //you can set data in store scope ->setWebsiteIds(array(1)) //website ID the product is assigned to, as an array ->setAttributeSetId(9) //ID of a attribute set named 'default' ->setTypeId('simple') //product type ->setCreatedAt(strtotime('now')) //product creation time // ->setUpdatedAt(strtotime('now')) //product update time ->setSku('testsku61') //SKU ->setName('test product21') //product name ->setWeight(4.0000) ->setStatus(1) //product status (1 - enabled, 2 - disabled) ->setTaxClassId(4) //tax class (0 - none, 1 - default, 2 - taxable, 4 - shipping) ->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH) //catalog and search visibility ->setManufacturer(28) //manufacturer id ->setColor(24) ->setNewsFromDate('06/26/2014') //product set as new from ->setNewsToDate('06/30/2014') //product set as new to ->setCountryOfManufacture('AF') //country of manufacture (2-letter country code) ->setPrice(11.22) //price in form 11.22 ->setCost(22.33) //price in form 11.22 ->setSpecialPrice(00.44) //special price in form 11.22 ->setSpecialFromDate('06/1/2014') //special price from (MM-DD-YYYY) ->setSpecialToDate('06/30/2014') //special price to (MM-DD-YYYY) ->setMsrpEnabled(1) //enable MAP ->setMsrpDisplayActualPriceType(1) //display actual price (1 - on gesture, 2 - in cart, 3 - before order confirmation, 4 - use config) ->setMsrp(99.99) //Manufacturer's Suggested Retail Price ->setMetaTitle('test meta title 2') ->setMetaKeyword('test meta keyword 2') ->setMetaDescription('test meta description 2') ->setDescription('This is a long description') ->setShortDescription('This is a short description') ->setMediaGallery (array('images'=>array (), 'values'=>array ())) //media gallery initialization ->addImageToMediaGallery('media/catalog/product/1/0/10243-1.png', array('image','thumbnail','small_image'), false, false) //assigning image, thumb and small image to media gallery ->setStockData(array( 'use_config_manage_stock' => 0, //'Use config settings' checkbox 'manage_stock'=>1, //manage stock 'min_sale_qty'=>1, //Minimum Qty Allowed in Shopping Cart 'max_sale_qty'=>2, //Maximum Qty Allowed in Shopping Cart 'is_in_stock' => 1, //Stock Availability 'qty' => 999 //qty ) ) ->setCategoryIds(array(3, 10)); //assign product to categories $product->save();
{ "language": "en", "url": "https://stackoverflow.com/questions/7599576", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Servlet 3.0 finalise? Is java servlet 3.0 finalised yet? I'm trying to implement comet and it would be a good idea to move on to Servlet 3.0. But I'm not sure if it'a way to move forward yet. Thanks A: Yes, it's finalised since 10 Dec 2009. http://jcp.org/en/jsr/detail?id=315 A: Yes it is: Final Release: 10 Dec, 2009 Status: Final http://jcp.org/en/jsr/detail?id=315
{ "language": "en", "url": "https://stackoverflow.com/questions/7599588", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: T-SQL - CROSS APPLY to a PIVOT? (using pivot with a table-valued function)? I have a table-valued function, basically a split-type function, that returns up to 4 rows per string of data. So I run: select * from dbo.split('a','1,a15,b20,c40;2,a25,d30;3,e50') I get: Seq Data 1 15 2 25 However, my end data needs to look like 15 25 so I do a pivot. select [1],[2],[3],[4] from dbo.split('a','1,a15,b20,c40;2,a25,d30;3,e50') pivot (max(data) for seq in ([1],[2],[3],[4])) as pivottable which works as expected: 1 2 --- --- 15 25 HOWEVER, that's great for one row. I now need to do it for several hundred records at once. My thought is to do a CROSS APPLY, but not sure how to combine a CROSS APPLY and a PIVOT. (yes, obviously the easy answer is to write a modified version that returns 4 columns, but that's not a great option for other reasons) Any help greatly appreciated. And the reason I'm doing this: the current query uses as scalar-valued version of SPLIT, called 12 times within the same SELECT against the same million rows (where the data string is 500+ bytes). So far as I know, that would require it scan the same 500bytes * 1000000rows, 12 times. A: This is how you use cross apply. Assume table1 is your table and Line is the field in your table you want to split SELECT * fROM table1 as a cross apply dbo.split(a.Line) as b pivot (max(data) for seq in ([1],[2],[3],[4])) as p
{ "language": "en", "url": "https://stackoverflow.com/questions/7599589", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: WinForm ListView Layout Issues enter code hereI'm having an issue with setting the layout for my ListView. I must be missing something simple. All I want is a list that has one item per row and instead its making the list run from left to right. public Form1() { InitializeComponent(); Items = new List<Item>(); listView1.FullRowSelect = true; this.listView1.Columns.Add("Path", listView1.Width, HorizontalAlignment.Left); } public void Blah(){ listView1.Items.Clear(); foreach (Item item in Items) { string s = String.Format("{1}", item.Type, item.Path); ListViewItem lvi = new ListViewItem(); lvi.Text = s; listView1.Items.Add(lvi); } } A: Found it.. add listView1.View = View.Details; to the constructor and magic happens. I hope this saves someone some time.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599598", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: difference between using extern and using a getter? I have a camera class that sets up two variables - a projection and a view matrix. I could either make these extern and include the header in anything I wanted to have access to the variables, or I could make a getter for them / pass references for these variables to anything that needed them. Is this simply a case of preference or are there real benefits to doing it a particular way? A: A getter has the advantage of not letting external code write in your variable (eg a pointer array can't be incremented). Otherwise, it's functionally the same, especially if it's for your own use. A: It is more a question of encapsulation. If your camera class is the only holder of these two matrices, it would be wise to make them available via getters and not with public attributes. This will, for example, allow you to subclass your camera and create other methods for your view and projection matrices.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599600", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Verifying a method called with certain derived parameter Consider the following snippet; public enum ReportType {Monthly,Quarterly} public class BaseReport { public ReportType ReportType {get;set;} } public class MonthlyReport : BaseReport { public String month = "January" public MonthlyReport() { ReportType = Monthly;} } public class Foo { public virtual void AddReport(BaseReport report); } [Test] public void Test1() { var mock = new Mock<Foo>(){CallBase =true}; var report = new MonthlyReport(); mock.Object.AddReport(report); } Well I am trying to verify if the AddReport() is called with certain parameter here; mock.Verify(x => x.AddReport(It.Is<MonthlyReport>(p => p.month == "January" && p.ReportType == ReportType.Monthly))); As I feared, it doesn't work with a MonthlyReport parameter for Is<> even though it is derived from BaseReport. If I use Is,then I can't use p.month in the expression, and I am not that proficient with c# to know whether I can use if(p is MonthlyReport) in a lambda expression or more importantly, it would work as intended. How can I approach this problem? Please note that the mock is partial, Although I can live with Setup approach with callbacks if it is neatly solves my problem. Any pointers would be greatly appreciated...
{ "language": "en", "url": "https://stackoverflow.com/questions/7599601", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I use Zend_Db_Table with multiple schemata and multiple deployments? My boss wants the application we are currently working on to be split across several schemata in the database, because he wants multiple applications -- some of which I have no control over -- to be able to access the data, following a naming convention like DeploymentPrefix_Category. For instance, there'd be a few schemata for production, Production_Foo, Production_Bar, and Production_Baz, and then the same for staging Staging_Foo, Staging_Bar, and Staging_Baz, and the same for development. The problem is that while Zend_Db_Table lets me specify a schema, it doesn't seem to let me generate that schema on the fly, which I would need to do to put that prefix on the schema. What's the best way to handle that? A: The issue of different configs for different environments is easily handled with Zend_Config. See the section on config in the quickstart: http://framework.zend.com/manual/en/learning.quickstart.create-project.html This allows you to specify different settings for each environment. As for the schemas, I'm guessing you have some tables that live in Production_Foo and others that live in Production_Bar. Consider extending Zend_Db_Table for each of these schemas and pointing to the correct database at the time of construction. Zend_Db_Table's constructor is defined as follows: public function __construct($config = array(), $definition = null) { ... } When we follow through to see where $definition leads it allows you to pass an array that is loaded into Zend_Db_Table_Definition. One of the options for this is the table name: /** * @param string $tableName * @param array $tableConfig * @return Zend_Db_Table_Definition */ public function setTableConfig($tableName, array $tableConfig) { // @todo logic here $tableConfig[Zend_Db_Table::DEFINITION_CONFIG_NAME] = $tableName; $tableConfig[Zend_Db_Table::DEFINITION] = $this; if (!isset($tableConfig[Zend_Db_Table::NAME])) { $tableConfig[Zend_Db_Table::NAME] = $tableName; } $this->_tableConfigs[$tableName] = $tableConfig; return $this; } As for your schema, you just pass in different set of options for the db adapter that points to the correct one. A: Well i'd argue that it's not "good" to have different table-names for different staging scenarios "Production_Foo" - "Staging_Foo" - "Testing_Foo".... just "Foo" is so much easier and more productive... But anyways: Personally i use the Table-Data-Gateway (i guess that's what it's called) - using Zend_Db_Table_Abstract extensions, so i would do it like this: class Application_Model_DbTable_Foo extends Zend_Db_Table_Abstract { public function __construct($config = array()) { $this->_name = Zend_Registry::get('config')->env_tbl_prefix.'Foo'; parent::__construct($config); } } Obviously this requires you to have the config stored to the registry and inside the config to define the key "env_tbl_prefix" with your environment prefixes "Production_", "Staging_", "Testing_", etc... Still, you're the developer, tell your boss to make life easier for all of you ^^ There's so many disadvantages using different table names depending on environment :\
{ "language": "en", "url": "https://stackoverflow.com/questions/7599606", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Accessing Data in Httphandler sent using post request I have created a httphandler. Everything is working fine If you take the request type GET. But I really don't want GET request due to security reasons. I am making a POST request using Jquery using following code: $.ajax({ type: "POST", async: false, url: "SaveAccounts", data: { a: "Sent Data" }, contentType: "application/json; charset=utf-8", dataType: "json", success: function OnSuccess(a) { alert(a); }, error: function OnError(request, status, error) { alert('Error: ' + request + ' ' + status + ' ' + error); }, complete: function () { } }); And the code for processing request is: context.Response.ContentType = "application/json; charset=utf-8" Dim s As String = context.Request.Params("a") context.Response.Write(JsonConvert.SerializeObject(s)) This code is returning 'null' in javascript alert in client side. Please note every thing is working fine when request type is changed to GET in $.ajax() function. I have also tried to access posted data using context.Request.Form("a") and context.request.SserverVariables("a") context.request.Params is a combined collection of 'Form', 'ServerVariables', 'Cookies' etc. Please tell me where I am going wrong...?? Thanks for looking.... A: This is working by just removing contentType and dataType specification from the request. Anything other than this will remain unchanged. A: Try data: { "a=Sent Data" }, e.g. from http://api.jquery.com/jQuery.ajax/ $.ajax({ type: "POST", url: "some.php", data: "name=John&location=Boston", success: function(msg){ alert( "Data Saved: " + msg ); } }); Also the HttpHandlers don't like JSON data so get rid of the contentType and the dataType. Escaping it - a more complete example var dataString = "{ 'first' : '" + escape($('#fname').val()) + "', 'mail' : '" + escape($('#tbMail1').val()) + "', 'mailinglist' : '" + $("input[name='ml']:checked").val() + "' }"; /*alert(dataString.replace('\',','\',\n'));*/ // just for debugging ;) $.ajax({ type: "POST", url: "myAjaxHandler.asmx/ProcessSampleForm", data: dataString, cache: false, contentType: "application/json; charset=utf-8", dataType: "json", success: function (msg) { $(".loadingimg").fadeOut(); window.location.replace(msg.d); }, error:function(xhr,err){ $(".loadingimg").fadeOut(); alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status); alert("responseText: " + xhr.responseText); } }); Taken from http://www.jphellemons.nl/post/JQuery-with-webform-input-validation-ajax-posting-json-to-aspnet-C.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7599607", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to analyze a java thread dump? I am trying to understand more about java, especially about memory management and threads. For this reason I have recently found interest in looking at thread dumps. Here are few lines taken from a web app using VisualVM, a built-in tool for java: "Finalizer" daemon prio=8 tid=0x02b3d000 nid=0x898 in Object.wait() [0x02d0f000] java.lang.Thread.State: WAITING (on object monitor) at java.lang.Object.wait(Native Method) - waiting on <0x27ef0288> (a java.lang.ref.ReferenceQueue$Lock) at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:118) - locked <0x27ef0288> (a java.lang.ref.ReferenceQueue$Lock) at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:134) at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:159) Locked ownable synchronizers: - None "Reference Handler" daemon prio=10 tid=0x02b3b800 nid=0x494 in Object.wait() [0x02cbf000] java.lang.Thread.State: WAITING (on object monitor) at java.lang.Object.wait(Native Method) - waiting on <0x27ef0310> (a java.lang.ref.Reference$Lock) at java.lang.Object.wait(Object.java:485) at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:116) - locked <0x27ef0310> (a java.lang.ref.Reference$Lock) First I have questions about some variable names: * *what does tid and nid mean? *What is the figure in squared parenthesis after Object.wait? Then for the stack trace itself: * *what does it mean waiting on <.....> (a java.lang....) and what's the number in <..> *what does it mean locked <.....> (a java.lang....) same question, what's in <..> I thought that the word locked was related in someway to a wait condition, however, I was wrong. In fact, I am wondering why locked is repeated three times, but the thread is in runnable state as seen in the same dump: "Thread-0" prio=6 tid=0x02ee3800 nid=0xc1c runnable [0x03eaf000] java.lang.Thread.State: RUNNABLE at java.io.FileInputStream.readBytes(Native Method) at java.io.FileInputStream.read(FileInputStream.java:199) at java.io.BufferedInputStream.read1(BufferedInputStream.java:256) at java.io.BufferedInputStream.read(BufferedInputStream.java:317) - locked <0x23963378> (a java.io.BufferedInputStream) at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:264) at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:306) at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:158) - locked <0x23968450> (a java.io.InputStreamReader) at java.io.InputStreamReader.read(InputStreamReader.java:167) at java.io.BufferedReader.fill(BufferedReader.java:136) at java.io.BufferedReader.readLine(BufferedReader.java:299) - locked <0x23968450> (a java.io.InputStreamReader) at java.io.BufferedReader.readLine(BufferedReader.java:362) at org.codehaus.plexus.util.cli.StreamPumper.run(StreamPumper.java:145) Then last of all, this was the worst of them: "CompilerThread0" daemon prio=10 tid=0x02b81000 nid=0x698 waiting on condition [0x00000000] java.lang.Thread.State: RUNNABLE This thread is in runnable state, but it's waiting on condition. What condition and what is 0x00000? Why the stack trace is so short without any evidence of the thread class? If you could answer to all my questions I would be very grateful. Thanks A: Further to @James Drinkard's excellent answer: Note that, depending on the underlying implementation, the java.lang.Thread.State of a thread that is blocked in a native method may be reported as RUNNABLE, where A thread in the runnable state is executing in the Java virtual machine but it may be waiting for other resources from the operating system such as processor. It turns out that this description also encompasses being blocked in an OS call such as a poll or read operation - presumably because there is no guarantee that the JVM can know when a native method call has blocked at the OS level. Many discussions of JVM thread dumps that I've seen either ignore this possibility completely, or blithely skim over it without considering the implications - not least of which is that monitoring tools may confusingly report that several such threads are 'running', and furthermore that they are all running at 100%. A: The TID is thead id and NID is: Native thread ID. This ID is highly platform dependent. It's the NID in jstack thread dumps. On Windows, it's simply the OS-level thread ID within a process. On Linux and Solaris, it's the PID of the thread (which in turn is a light-weight process). On Mac OS X, it is said to be the native pthread_t value. Go to this link: Java-level thread ID: for a definition and a further explanation of these two terms. On IBM's site I found this link: How to interpret a thread dump. that covers this in greater detail: It explains what that waiting on means: A lock prevents more than one entity from accessing a shared resource. Each object in Java™ has an associated lock (gained by using a synchronized block or method). In the case of the JVM, threads compete for various resources in the JVM and locks on Java objects. Then it describes the monitor as a special kind of locking mechanism that is used in the JVM to allow flexible synchronization between threads. For the purpose of this section, read the terms monitor and lock interchangeably. Then it goes further: To avoid having a monitor on every object, the JVM usually uses a flag in a class or method block to indicate that the item is locked. Most of the time, a piece of code will transit some locked section without contention. Therefore, the guardian flag is enough to protect this piece of code. This is called a flat monitor. However, if another thread wants to access some code that is locked, a genuine contention has occurred. The JVM must now create (or inflate) the monitor object to hold the second thread and arrange for a signaling mechanism to coordinate access to the code section. This monitor is now called an inflated monitor. Here is a more in-depth explanation of what you are seeing on the lines from the thread dump. A Java thread is implemented by a native thread of the operating system. Each thread is represented by a line in bold such as: "Thread-1" (TID:0x9017A0, sys_thread_t:0x23EAC8, state:R, native ID:0x6E4) prio=5 *The following 6 items explains this as I've matched them from the example, values in the brackets[]: * *name [Thread-1], *identifier [0x9017A0], *JVM data structure address [0x23EAC8], *current state [R], *native thread identifier [0x6E4], *and priority [5]. The "wait on" appears to be a daemon thread associated with the jvm itself and not the application thread perse. When you get an "in Object.wait()", that means the daemon thread, "finalizer" here, is waiting on a notification about a lock on an object, in this case it shows you what notification it's waiting on: "- waiting on <0x27ef0288> (a java.lang.ref.ReferenceQueue$Lock)" Definition of the ReferenceQueue is: Reference queues, to which registered reference objects are appended by the garbage collector after the appropriate reachability changes are detected. The finalizer thread runs so the garbage collection operates to clean up resources associated with an object. If I'm seeing it corectly, the finalizer can't get the lock to this object: java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:118) because the java object is running a method, so the finalizer thread is locked until that object is finished with it's current task. Also, the finalizer isn't just looking to reclaim memory, it's more involved than that for cleaning up resources. I need to do more study on it, but if you have files open, sockets, etc... related to an objects methods, then the finalizer is going to work on freeing those items up as well. What is the figure in squared parenthesis after Object.wait in the thread dump? It is a pointer in memory to the thread. Here is a more detailed description: C.4.1 Thread Information The first part of the thread section shows the thread that provoked the fatal error, as follows: Current thread (0x0805ac88): JavaThread "main" [_thread_in_native, id=21139] | | | | +-- ID | | | +------------- state | | +-------------------------- name | +------------------------------------ type +-------------------------------------------------- pointer The thread pointer is the pointer to the Java VM internal thread structure. It is generally of no interest unless you are debugging a live Java VM or core file. This last description came from: Troubleshooting Guide for Java SE 6 with HotSpot VM Here are a few more links on thread dumps: * *How Threads Work *How to Analyze a Thread Dump *Java Thread Dumps *Java VM threads *Stackoverflow question: How threads are mapped
{ "language": "en", "url": "https://stackoverflow.com/questions/7599608", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "105" }
Q: SQL Server CE - bad performance I'm developing an application that uses a SQL Server CE database and I am having trouble with the performance of the queries. For example, a simple query that gets the customer's last order: SELECT Customer.Name, Orders.Amount AS LastOrderAmount FROM Customers LEFT JOIN Orders ON Orders.OrderId IN (SELECT TOP(1) OrderId FROM Orders WHERE CustomerId = Customer.CustomerId ORDER BY OrderNum DESC) This query is incredibly slow. With only 30 costumers and about 300 orders it takes almost 10 seconds to finish! I'm querying using SqlCEDataAdapter. I also tried using SqlCeResultSet, but the difference is negligible. Also, I have an index on Orders.CustomerId (creating it didn't make much difference, though). Now, I'm not expecting miracles from SQL Server CE, but this is just terrible. So, is there something I can do to improve performance or is it just THAT slow? A: Try this: SELECT cus.Name , outerOrd.Amount AS LastOrderAmount FROM Customers cus LEFT JOIN Orders outerOrd on outerOrd.CustomerId = cus.CustomerId WHERE not exists (SELECT * FROM Orders innerOrd WHERE innerOrd.CustomerId = cus.CustomerId and innerOrd.OrderId > outerOrd.OrderId ) Edited, probably this is better: SELECT cus.Name , ord.Amount AS LastOrderAmount FROM Customers cus LEFT JOIN Orders ord on ord.CustomerId = cus.CustomerId WHERE ord.OrderId = (SELECT max(OrderId) FROM Orders WHERE CustomerId = cus.CustomerId )
{ "language": "en", "url": "https://stackoverflow.com/questions/7599611", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Choosing a clever solution: SQL Server or file processing for bulk data? We have a number of files generated from a test, with each file having almost 60,000 lines of data. Requirement is to calculate number of parameters with the help of data present in these files. There could be two ways of processing the data : * *Each file is read line-by-line and processed to obtain required parameters *The file data is bulk copied into the database tables and required parameters are calculated with the help of aggregate functions in the stored procedure. I was trying to figure out the overheads related to both the methods. As a database is meant to handle such situations, I am concerned with overheads which may be a problem when database grows larger. Will it affect the retrieval rate from the tables, consequently making the calculations slower? Thus will file processing be a better solution taking into account the database size? Should database partitioning solve the problem for large database? A: Did you consider using map-reduce (say under Hadoop maybe with HBase) to perform these tasks? If you're looking for high-throughput with big data volumes this is a very scaleable approach. Of course, not every problem can be addressed effectively using this paradigm and I don't know the details of your calculation. A: If you set up indexes correctly you won't suffer performance issues. Additionally, there is nothing stopping you loading the files into a table and running the calculations and then moving the data into an archive table or deleting it altogether. A: you can run a querty directly agianst the text file from SQL SELECT * FROM OPENROWSET('MSDASQL', 'Driver={Microsoft Text Driver (*.txt; *.csv)};DefaultDir=C:\;', 'SELECT * FROM [text.txt];') * *The distributed queries needs to be enabled to run this. Or as you mentioned you can load the data data to a table (using SSIS, BCP, the query above ..). You did not mentioned what does it mean that the database will be larger. 60k of lines for a table is not so much (meaning that it will perform well).
{ "language": "en", "url": "https://stackoverflow.com/questions/7599613", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Regarding an example illustrating the usage of generic class syntax In thinking in Java, page 566 gives the following example. class CountedInteger { private static long counter; private final long id = counter++; public String toString() { return Long.toString(id); } } public class FilledList<T> { private Class<T> type; public FilledList(Class<T> type) { this.type = type; } public List<T> create(int nElements) { List<T> result = new ArrayList<T>(); try { for(int i = 0; i < nElements; i++) result.add(type.newInstance()); } catch(Exception e) { throw new RuntimeException(e); } return result; } public static void main(String[] args) { FilledList<CountedInteger> fl = new FilledList<CountedInteger>(CountedInteger.class); System.out.println(fl.create(15)); } } I have three questions with respect to this example. 1) What is the usage of private Class type? Why is it private? 2) Why do the following, in particular " this.type = type;" public FilledList(Class<T> type) { this.type = type; } 3) The author claims: Notice that this class must assume that any type that it works with has a default constructor (one without arguments), and you’ll get an exception if that isn’t the case. I can not figure out how this statement was reflected in the above example. Thanks. A: 1) It doesn't have to be, but that's one of the things you do in Java--don't expose things that don't need to be exposed. 2) That sets the property to the parameter of the constructor--that's elemental Java. 3) Because of the type.newInstance() call; without a default (no-arg) constructor it will fail. A: * *It doesn't have to be private, but generally it is good to hide internal fields in your classes, unless you want them to be accessible from the outside. I would also put final modifier on type filed to prevent modification. *This line assigns value passed in the class constructor to the instance field named type. Keyword this indicates that it is a this instance field. *The type.newInstance() code will fail if corresponding type doesn't have a default constructor. BTW, the whole thing can be replaced with java.util.Collections.fill(list, value) call. A: * *The type is just another instance variable. It is declared private as to prevent access to it from outside of this class. *When an instance of this class FilledList is created, ie, when the constructor which takes 1 arg is called, the instance variable type is initilized with this arg value passed in the constuctor. *What type.newInstance() does is call the default no args constructor of this type, this would throw an exception if the default constructor is private. A: 1: all members of a class should be private or protected with respect to information hiding. But you dont have to do that 2: Inside any method ou have access to all parameters and all members-variables in that class. In this case the parameter-name is exactly the same as a member-variable. So in this case the parameter-name will win if you write type. this is pointing to the current instance and with this.type you indicate that you mean the member-variable and not the parameter. So this.type = type is in this case member = parameter. 3: newInstance with no parameters will call a default-constructor on T and if it doesn't exist an exception will be thrown. take a look at the link
{ "language": "en", "url": "https://stackoverflow.com/questions/7599623", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: GWT Spell Check I would like to implement a "spell check" for my GWT rich text area. I do understand that Firefox and other browsers automatically highlight words with misspellings, but I need to be able to warn the user before they submit a form that there are potential misspellings if they ignore the "squiggles". Is it possible to use a javascript call to see if the default Firefox spell checker has detected errors? I could use that to stop the form from being submitted with misspellings. Any thoughts out there? Thanks, Jeff A: Firstly, you cannot guarantee that your user is using Firefox (or a browser that has spellcheck). Secondly, I do not believe that you can access most browser-level components from your JavaScript code. You can find spellcheck libraries and call them accordingly. See SpellCheck.java as a starting point, but I'm sure there are many more.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599624", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: formulating an SSRS query to include zero/empty rows in a GROUP BY I'm working on a SSRS report and I'm having an issue with my Plant name not showing when there is no data available for the date range selected. The far left column, first row (technically the 2nd by the image) is where my plant name should appear at all times: Essentially the first image showed just my blank rows/columns. The first column, first row is where my plant name should be at all times. The remaining columns are my returned data based on date selection. The second image would show everything working as it should when there is data. I'm grouping by PlantCode in SSRS which is what gives my my plant name. I don't know how to get the plant name to appear even if there is not data available. Is this possible? I THOUGHT I could use something like iif(salesvolume is NOTHING, [PlantCODE],[PlantCode]) Here is the database query for the report SELECT PInv.[Plant_Numer], PInv.[Plant_Code], PInv.{Department_number], PInv.[Inventory_Volume], Pinv.[Inventory_Date], -- 'Last Inventory Date' pls.[Actual_Volume], pls.[Budget_Volume], ppf.[Good_Output_Product_Units] AS 'Production Volume', -- 'Next Day Production CASE WHEN coalesce (pls.[Acutal_Volume],0) = 0 and coalesce (pls.[Actual_Sales_Dollars],0) = 0 THEN 0 ELSE ((pls.[Actual_Sales_Dollars/pls.[Actual_Volume])) AS 'Average Price' -- 'Next Day Sales' FROM [TrueOpportunity].[dbo].[Production_Fact] pf inner join [TrueOpportunity].[dbo].[Production_Process_Fact] ppf on ppf.production_number = pf.production_number inner join [TrueOpportunity].[dbo].[Process] prc on prc.process_number = pf.process_number inner join [TrueOpportunity].[dbo].[Department] dpt on dpt.department_number = prc.department_number inner join [WoodProduction_New].[dbo].[Plywood_Layup_Sales] pls on pls.procesS_number = pf.procesS_number inner join [WoodProduction_New].[dbo].[Process_Inventory] Pinv on PInv.[Inventory_Date] = pf.date and pls.product_date = pf.date and dpt.department_number = pinv.department_number WHERE pf.date between @BeginningDate and @EndingDate A: I think you want to change your query so that Process Inventory is your primary table and all other tables are LEFT JOINED to that table. That way the Plant Number & Code will show up regardless of whether there is matching data in the other tables. This syntax is probably not completely correct, but I would start out by changing your FROM clause to look something like this: FROM [WoodProduction_New].[dbo].[Process_Inventory] Pinv LEFT JOIN [TrueOpportunity].[dbo].[Production_Fact] pf ON PInv.[Inventory_Date] = pf.date LEFT JOIN [TrueOpportunity].[dbo].[Production_Process_Fact] ppf ON ppf.production_number = pf.production_number LEFT JOIN [TrueOpportunity].[dbo].[Process] prc ON prc.process_number = pf.process_number LEFT JOIN [TrueOpportunity].[dbo].[Department] dpt ON dpt.department_number = prc.department_number AND dpt.department_number = pinv.department_number LEFT JOIN [WoodProduction_New].[dbo].[Plywood_Layup_Sales] pls ON pls.process_number = pf.process_number AND pls.product_date = pf.date Experiment with that and see if you can get it to display the data that you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599628", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I pass parameters to an asp.net function from an asp.net control inside an itemtemplate I have a vote button in a repeater and I want to use it by giving the post id which is in the same itemtemplate in a repeater/datalist. I can't pass the value I get from Eval() to the codebehind function because it takes 2 arguments which are sender and eventargs A: use OnCommand instead of OnClick: <asp:Button ID="btnVote" runat="server" Text="Vote" OnCommand="btnVote_Command" CommandArgument='<%#Eval("Column1")%>' /> In the code-behind: protected void btnVote_Command(object sender, CommandEventArgs e) { object column1 = e.CommandArgument; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7599630", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Pixel precise positioning and different browsers I am making one simple horizontal menu with CSS and simple unordered list. The HTML of the menu is following: <div id="navigation"> <div id="nav-holder"> <ul> <li><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Services</a></li> <li><a href="#">Clients</a></li> <li><a href="#">Portfolio</a></li> <li><a href="#">Contact</a></li> </ul> </div> </div> And CSS is as follows: #navigation { display: table; height: 35px; width: 100%; #position: relative; overflow: hidden; background: Black; } #nav-holder { #position: absolute; #top: 50%; display: table-cell; vertical-align: middle; } #navigation ul { #position: relative; #top: -50%; } #navigation ul li { float: left; } #navigation ul li a { padding: 5px 10px; margin-left: 2px; background-color: Red; text-decoration: none; font-family: Verdana; color: White; } I want the menu to have a 2px margin around all of the link elements. The problem I am facing is that while it renders itself fine in IE with all of the rights margins but both Chrome and Firefox (both are latest) are having the following issues: The problem does not seem to be related to only this particular implementation but Ive seen it rise up from veertically centering the links with line heights and so on too. I would like to find a way to have all of the margins to look the same or some way to avoid this problem all-together. A: Basically, I got this thing sorted out. I set the same line-height and height attribute to all of the following: ul, li, nav holder. I did it because when it was not done, all of these were rendered differently from browser to browser. In addition, I removed the positionings, vertical alignings, hav-holder div entirely and then some. A: try display: inline-block; for your #nav-holder
{ "language": "en", "url": "https://stackoverflow.com/questions/7599633", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get large photo URL in one API call? I want to display large photos in my Facebook app's feed view immediately. Is it possible to get the large photo src URL from a stream/feed using one API call? The photo id is returned in the stream/feed and one can of course then supply this photo id in an additional FQL or graph API call to retrieve all the information about that photo. However, is there a way using multi-query or batch calls to get a larger photo src url using one API roundtrip? A: I haven't tried this with stream/feed photos, but the generally accepted way of doing this is: http://graph.facebook.com/{ID of object}/picture If you want the "large" version, you would do: http://graph.facebook.com/{ID of object}/picture?type=large I'm not 100% sure if this would work for an actual photo (instead of a user profile picture or page profile pic), but I have a hunch it will - the only caveat is that you obviously must have a logged in user that is authorized to view the photo (unless it's public). A: If anybody is looking to this and type large is not enough, I found other solutions. Type large is kind of small anyway (close to 200px). You can get larger image by adding i.e. ?width=1000 or ?height=1000. Facebook will return picture closest to given dimension and preserve aspect ratio. When passing both dimenstions like ?width=1000&height=1000, facebook will cut image to given dimensions (in this case square). A: Use Facebook UserId (Oject ID) to get the picture. https://graph.facebook.com/173xxxx8635/picture?type=large&redirect=false which returns JSON data with picture URL. { "data": { "is_silhouette": false, "url": "https://fbcdn-profile-a.akamaihd.net/xxx/xyz/1cc066a2cae3f301d" } } A: A good trick with the new api is to get the pic_cover field from the event table and to process it according to the size you want to use A: I found when I was having this trouble that it turned out to be the picture I was downloading rather than the size I was setting it. If for example I downloaded all my photos with a request of [FBRequestConnection startWithGraphPath:@"/me/photos?fields=created_time,name,picture&type=tagged" parameters:nil HTTPMethod:@"GET" completionHandler:^(FBRequestConnection * connection, id result, NSError *error) { NSDictionary * userData = (NSDictionary *)result; NSMutableArray * array = [[NSMutableArray alloc] initWithArray:userData[@"data"]]; for (NSDictionary * dict in eventsToAdd) { UIImage * image = dict[@"picture"] } }]; I am using the dictionary key search "picture" as I want the picture. This though will get me a lower quality picture than if I searched for "source" in this search: [FBRequestConnection startWithGraphPath:@"/me/photos?fields=created_time,name,source&type=tagged" parameters:nil HTTPMethod:@"GET" completionHandler:^(FBRequestConnection * connection, id result, NSError *error) { NSDictionary * userData = (NSDictionary *)result; NSMutableArray * array = [[NSMutableArray alloc] initWithArray:userData[@"data"]]; for (NSDictionary * dict in eventsToAdd) { UIImage * image = dict[@"source"] } }]; If you go on the Facebook API explorer and search for photos and then click on the picture and source jpg links you can see the difference in size and quality. Since changing this method I have managed to get rid of using the type parameters as it doesn't seem to make a different. Note: I am using iPhone and not iPad or a larger screen so I don't know how this affects bigger screens. A: The answer by @streetlogics works fine but only on pictures that have {object_id}. http://graph.facebook.com/{object_id}/picture But I also wanted large pictures for the feed's shared links, which sometimes don't have {object_id}. I finally realized that the {picture} thumbnail URL contains the encoded URL for the original site's large image: https://external.xx.fbcdn.net/safe_image.php?d=AQBe9UvGd0vPbAHP&w=130&h=130&url=http%3A%2F%2Fskift.com%2Fwp-content%2Fuploads%2F2015%2F12%2Fpollution.jpg&cfs=1 --> contains --> http://skift.com/wp-content/uploads/2015/12/pollution.jpg So I made a loop that checks for {object_id} and if not present then extracts the URL from {picture}: if(isset($post['object_id'])) { echo "http://graph.facebook.com/".$post['object_id']."/picture"; } elseif(isset($post['picture'])) { echo urldecode(preg_replace('/&cfs.*/', '', preg_replace('/.*url=/', '', $post['picture']))); } else { echo "no_large_image"; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7599638", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "39" }
Q: How can I programatically recreate these Websphere logs due to Unsynchronized access to HashMap We have few components in our project extending the HashMap Due to unsynchronized access to the HashMap object we are getting the logs like the below one in Production: ThreadMonitor W WSVR0605W:Thread "webcontainer:5" has been active for 864096 milliseconds and may be hung.There is/are 5 thread(s) in the total server that may be hung. at java.util.HashMap.findNonNullKeyEntry(HashMap.java:525) at java.util.HashMap.putImpl(HashMap.java:622) at java.util.HashMap.put(HashMap.java:605 )....... I want to recreate this for the testing purpose and tried spawning different threads putting and getting the HashMap object, but still no breakthroughs. Also, I have set loadfactor to 0.1 so that resizing of the HashMap will occur more frequently,which we are analysing is causing the issue(Structural changes in the HahMap). We are using IBM java version 6 Could anyone help me on this? A: I think you can refer to the code by gwoolsey at the url below [http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6611637] I hope this will help. I was able to reproduce the problem with this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599639", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android: RuntimeException with PreferenceScreen and Custom Attributes from inside a Library Project I recently split my project and created a library project and a main project. Having a preferences screen that has custom attributes, i removed the preferences with custom attributes from my preferences.xml, put them into their own xml files, included them back into the preferences.xml file and redefined the individual files in the main project (the process is detailed in the answer to another question here. The project build and run properly. However, I am getting a RuntimeException whenever i try to open the preferences screen. Removing the prefs with custom attrs fixes the problem, so i have traced it back to there. Unfortunately there is no useful information in the exception. attrs.xml (exists in lib project) <?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="numberpickerPref"> <attr name="maxValue" format="integer" /> <attr name="minValue" format="integer" /> </declare-styleable> </resources> preferences.xml (also in lib project) <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" > <PreferenceCategory android:title="@string/pref_VibrationSettingsTitle"> <CheckBoxPreference android:key="@string/pref_vibrateFlagKey" android:title="@string/pref_VibrateTitle" android:summary="@string/pref_VibrateSummary" android:defaultValue="false" /> <include layout="@layout/pref_vibrate_on" /> <include layout="@layout/pref_vibrate_off" /> </PreferenceCategory> </PreferenceScreen> pref_vibrate_off.xml (defined in both lib and main projects) (only diff is the my namespace, one points to the lib, the other the main project) <?xml version="1.0" encoding="utf-8"?> <!-- Stupid workaround because Android still has a bug where custom attributes in a library cause the executable project problems when building: https://stackoverflow.com/questions/4461407/help-with-a-custom-view-attributes-inside-a-android-library-project --> <com.me.numberpicker.NumberPickerPreference xmlns:android="http://schemas.android.com/apk/res/android" xmlns:my="http://schemas.android.com/apk/res/com.me.myapp.lib" android:key="@string/pref_vibrateOffPeriodKey" android:title="@string/pref_VibrateOffTitle" android:summary="@string/pref_VibrateOffSummary" my:maxValue="@string/MaxVibratorOffPeriodInS" my:minValue="@string/MinVibratorOffPeriodInS" android:defaultValue="@string/DefaultVibratorOffPeriodInS" /> MyPreferencesActivity.java public class MegalarmPreferencesActivity extends PreferenceActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); } } All the strings are properly defined in the lib project. If i'm missing anything, let me know please. The preferences were working fine until i split up my project into a lib and main. Many thanks! Sean A: PreferenceActivity.onCreate can throw RuntimeExceptions internally that the IDE might catch (if configured to do so), but they are also caught internally. For instance, a missing layout_width tag in the default theme seems to cause an exception. If the RuntimeException is not percolating back to your code don't worry about it. If it is, could you update your question to include the exception message and stack trace?
{ "language": "en", "url": "https://stackoverflow.com/questions/7599643", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Windows symbolic link ASP.NET app repository We are hosting huge app for our cutomers. There are diffrent configuration and contents (images, user files). But the core code, directories structure, databse scheme is this same for every client. I'm looking for a way to create one core code repository, so all clientes will use it. We do updates often, so this will make our live easyer. The idea is to create the repo and In clients directories create just symbolic links to that repo direcories: bin, App_Resources, Css, SystemImages etc. Is this a good idea? Will ASP.NET MVC app handle this correctly, or I've to add some code for it handle the 'virtual direcotories'? A: I would suggest that you take a look Single-tenant and Multi-tenant applications even if you say that your code base is the same for every one. Here is a nice Multi-Tenancy ASP.NET example I would also suggest that you check http://appHarbour.com as you can easily push changes from your master repository to appHarbour using Git or Mercurial. Regarding your exact question, I also keep static files in a custom scheme under Amazon S3, so each client can upload there own files, plus the ones I have and all is based on a single location that does not put more resources just to delivery static files. You can see my live web application using this technique checking the View Source.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599645", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: My div does not exists after loading my pixel I have a pixel and when I load it, it says: a call to document.write() from an asynchronously-loaded external script was ignored and then displays: document.getElementById('gospixel') is null Here's my pixel code: <script name="gospix" src="http://www.example.com/p/gospixel.js"> and in that file: gos_f=42; gos_a1='a2'; gos_u=window.location.href; gos_k='6gZYlfy7Y7Q'; gos_rt='3_s'; document.write(unescape("%3Cscript src='http://example.com/p/gosuna.js' type='text/javascript'%3E%3C/script%3E")); Thanks for your help! A: Don't use document.write. view this thread: Why is document.write considered a "bad practice"? Instead, use dynamic object like document.createElement and appendChild. http://www.dustindiaz.com/add-and-remove-html-elements-dynamically-with-javascript/ This will slove your error. A: apparently, the browser is ignoring the autowrite from the import (for security reasons, so an imported script can't modify your page), so you should try making the insert on demand in gospixel replace the last line with function insertScript(){ document.write(unescape("%3Cscript src='http://example.com/p/gosuna.js' type='text/javascript'%3E%3C/script%3E")); } and then on some other part of the html <script type="text/javascript"> insertScript(); </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7599646", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: php scanning content for specific keywords As part of a CMS admin, I would like to scan new articles for specific keyphrases/tags that are stored in a mysql db. I am proficient enough to be able to pull the list of keywords out, loop through them and do stripos, and substr_count to build an array of the found keywords. but the average article is about 700 words and there are 16,000 tags and growing so currently the loop takes about 0.5s which was longer than I had hoped, and will only ever get longer. Is there a better way of doing this? Even if this type of procedure has a special name, that could help. I have PHP 5.3 on Fedora, it is also on dedicated servers so I don't have any shared host issues. EDIT - I am such a scatterbrain, I swore blind that I copy and pasted some code! clearly not $found = array(); while($row = $pointer->fetch_assoc()) { if(stripos($haystack, $row["Name"]) ) { $found[$row["Name"]] = substr_count( $haystack, $row["Name"]); } } arsort($found); I think I explained myself badly, because I want to do the procedure on new articles they are currently not in the database, so I was just going to use $_POST in an ajax request, rather than saving the article to the DB first. A: http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html is exactly what you are looking for if you don't want to use a search engine script such as sphinx/solr. A: It sounds like your code looks something like this: foreach($keywords as $keyword){ if(strpos($keyword, $articleText) != -1){ $foundKeywords[] = $keyword; } } Something you may consider since the keywords array is so large and will continue to grow is to switch your processing to loop through the words in the text instead of the keywords array. Something like this: $textWords = explode(" ", $articleText); foreach($textWords as $word){ if( array_search($word, $keywords) && !array_search($word, $foundKeywords) ){ $foundKeywords[] = $word; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7599648", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Deploying Jenkins within Glassfish throw Exception I'm trying to deploy Jenkins 1.432 to GlassFish Server Open Source Edition 3.1.1 (build 12), running in Ubuntu 10.04. It throws this error: java.lang.RuntimeException: Installation Problem??? Couldn't load messages: Can't find bundle for base name com.sun.org.apache.xerces.internal.impl.xpath.regex.message, locale en_US at com.sun.org.apache.xerces.internal.impl.xpath.regex.RegexParser.setLocale(RegexParser.java:93) The locale ubuntu command returns: LANG=en_US.UTF-8 I don't know what to do. I googled many thing, without really founding something. Classpath problem ? Right permission ? Missing jar in jvm ? A: I finaly decided to deploy Jenkins outside Glassfish, with the debian package. I guess my Glassfish install is missing a language package (?), but I am not sure.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599656", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: iPhone-MPMediaPlayer disable seek forward button I would like to remove or disable the seek forward button from the MPMediaPlayer. I have tried to enumerate all the views but apparently I could not find this button. Does anyone have any idea? Thanks. A: You could always provide a custom control panel, you can hide the default controls with playerController.controlStyle = MPMovieControlStyleNone; Then add a subview containing your interface and just link buttons to play/pause start/stop rewinding, and there's an open source implementation of the variable speed slider (OBSlider). You will also need to register for some MP notifications: MPMovieDurationAvailableNotification MPMoviePlayerLoadStateDidChangeNotification MPMoviePlayerPlaybackDidFinishNotification MPMoviePlayerPlaybackStateDidChangeNotification A: The only way I found is to add a transparent button over the seek forward button. Here is the code: - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; UIButton *button = [[UIButton alloc] init]; if(UIInterfaceOrientationIsLandscape(self.interfaceOrientation)) [button setFrame:CGRectMake(535, 599, 90, 60)]; else [button setFrame:CGRectMake(407, 855, 90, 60)]; [button setBackgroundColor:[UIColor clearColor]]; [button setAlpha:0.7]; [button setTag:1200]; [self.moviePlayer.view addSubview:button]; [button release]; } - (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration { if(UIInterfaceOrientationIsLandscape(toInterfaceOrientation)) { UIButton *button = (UIButton *)[self.moviePlayer.view viewWithTag:1200]; [button setFrame:CGRectMake(535, 599, 90, 60)]; } else { UIButton *button = (UIButton *)[self.moviePlayer.view viewWithTag:1200]; [button setFrame:CGRectMake(407, 855, 90, 60)]; } } This is for IPAD ONLY! If you would like to do the same on iPhone, please change the position of the transparent button.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599657", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Telerik RadGrid Visible Property Not Working as Expected I have two image buttons that hide and show a radgrid depending on what the client wants to see. When a button is clicked, the grid.visible property is set to true or false. The problem is that when I click the button the first time, the page posts back and does not work. Then I click a couple more times, and it shows only a horizontal line (I assume it is the grid not databound). I click a few more times and the grid shows and hides perfectly. However, when the user navigates away from the page and then comes back to this page, I get the same problem. Any help would be appreciated. .aspx <div class="RegistrationHistoryGrid" > <telerik:RadGrid ID="rgRegistrationHistory" Width="100%" ShowHeader="true" AutoGenerateColumns="false" OnSelectedIndexChanged="rgRegistrationHistory_SelectedIndexChanged" AllowCustomPaging="true" AllowSorting="True" AllowPaging="True" PageSize="10" runat="server" Gridlines="None" CellSpacing="0" onneeddatasource="rgRegistrationHistory_OnNeedDataSource" > <ClientSettings AllowColumnsReorder="True" ReorderColumnsOnClient="True" EnableRowHoverStyle="true" EnablePostBackOnRowClick="true"> <Selecting AllowRowSelect="True" /> </ClientSettings> <MasterTableView Width="100%" Summary="RadGrid table" DataKeyNames="ClientID, LastName, FirstName, Gender,DateOfBirth,Address"> <Columns> <telerik:GridBoundColumn HeaderText="Period" Reorderable="false" UniqueName="Period" DataField="Period"/> <telerik:GridBoundColumn HeaderText="Plate" Reorderable="false" UniqueName="Plate" DataField="Plate"/> <telerik:GridBoundColumn HeaderText="Comment" Reorderable="false" UniqueName="Comment" DataField="Comment"/> </Columns> <SortExpressions> <telerik:GridSortExpression FieldName="LastName" SortOrder="Ascending" /> </SortExpressions> </MasterTableView> <PagerStyle Mode="NextPrevAndNumeric" /> <FilterMenu EnableImageSprites="False"></FilterMenu> <HeaderContextMenu CssClass="GridContextMenu GridContextMenu_Default"></HeaderContextMenu> </telerik:RadGrid> </div> .cs protected void rgRegistrationHistory_OnNeedDataSource(object sender, GridNeedDataSourceEventArgs e) { List<int> fakeList = new List<int>(); rgRegistrationHistory.DataSource = fakeList; } protected void imgChevronClosed_Click(object sender, ImageClickEventArgs e) { imgChevronOpen.Visible = true; imgChevronClosed.Visible = false; rgRegistrationHistory.Visible = false; } protected void imgChevronOpen_Click(object sender, ImageClickEventArgs e) { imgChevronOpen.Visible = false; imgChevronClosed.Visible = true; rgRegistrationHistory.Visible = true; } A: You have to rebind the grid when you toggle its visibility. See this article on the matter. A: You can try consolidating your logic, and doing something like this instead: Markup: <asp:ImageButton ID="imgToggleGrid" runat="server" ImageUrl="~/images/hide.png" OnClick="imgToggleGrid_Click" /> <asp:PlaceHolder ID="plcGrid" runat="server"> <!-- GRID --> </asp:PlaceHolder> Code-behind: protected void imgToggleGrid_Click(object sender, EventArgs e) { plcGrid.Visible = !plcGrid.Visible; imgToggleGrid.ImageUrl = String.Format("~/images/{0}", plcGrid.Visible ? "hide.png" : "show.png"); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7599659", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Text floats out of its div I'm dealing with a text who goes out of its div. I've coded the frontpage. So, no matter how long the main content is, it should force the sub-content (the grey area and the footer) to move down. You see how the dummy text is acting URL http://nicejob.is/clients/pizzahollin/www/divproblem.htm I've accomplish this before but somehow it's not working now. A: You've set an explicit height on that div. For it to reshape itself to its content, you'll need to set height:auto. (or never set its height in the first place) EDIT: As ANeve said, you'll need to remove the height on both .article and .opentext, as well you'll need to put a clear:left on .lower-container to push the footer down. A: Just use wordwrap: break-word; for the div and it will break the word to the next line. A: You have set the height property of your .article and .opentext divs. If you remove this property, the content should expand accordingly. However, you will also need to adjust the positioning of your background image. You should set the background image of .footer itself, rather than relying on one statically-sized background image for the entire page. A: If you have an element that only contains floating elements, the container's height will be zero. To fix this you can add a clearing div (<div style="clear:both"></div>). If you add a clearing div at the end of the #under-content section, it will automatically adjust the height of the section to it's contents. The other issue you have is that you are using relative positioning on your .opentext div elements. When you set a 'top' property, it actually pushes the content down, causing it to overlap with your #lower-container. You're better off using the 'margin-top' property, which will expand the size the .opentext div to fit all the contents. So in short: * *Add <div style="clear:both"></div> at the end of the #under-content <section> *Change the 'top:82px' to 'margin-top:82px' on your .opentext div I hope this helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/7599663", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: DataGrid.Items filled with Null data I'm trying to fill a asp.DataGrid with data from a DB2 database. The problem I'm getting is that the data is coming back null. The weird thing is, the records themselves (seem to) load from the database, as when I step through the code while debugging, the DataGrid.Items.Count = the number of records I have in the database itself. Additionally, while troubleshooting, I've added an asp.Label that's initially hidden to display the number of records found in the DataGrid itself, and each time it displays the correct number of records. Here's my code: protected void Page_Load(object sender, EventArgs e) { dta_grd = new DataGrid(); dta_grd = Ex_DLL.GetData("select * from tstint/m02"); Lbl_Dsply.Visible = true; if (Supp_Data.Items.Count == 0) { Lbl_Dsply.Text = "No Records Found!"; } else { Lbl_Dsply.Text += dta_grd.Items.Count.ToString(); } } Ex_DLL is simply the name of a library that does all the connections to the Database itself. The Code for Ex_DLL.GetData(): public static DataGrid GetData(string str_sql) { //EX_Global.DB2_Conn("DEV") is just an internal connection function that houses //the connection settings. iDB2Connection db2_conn = EX_Global.DB2_Conn("DEV"); iDB2Command db2_cmd = null; iDB2DataAdapter db2_adpt = null; DataSet dta_ds = new DataSet(); DataGrid ret_val = new DataGrid(); try { if (db2_conn.State != System.Data.ConnectionState.Open) { db2_conn.Open(); } db2_cmd = new iDB2Command(str_sql, db2_conn); db2_adpt = new iDB2DataAdapter(db2_cmd); db2_adpt.Fill(dta_ds); ret_val.DataSource = dta_ds; ret_val.DataBind(); db2_conn.Close(); } catch (Exception) { } return ret_val; } Now, when I read them individually using idb2DataReader, it's actually reading from the database, but there's just something lost in translation from reading the database to filling the DataGrid itself. Any ideas? A: There are two problems (may be more) I can see: * *You instantiate the DataGrid control during page execution but forget to add it to page's Controls collection. *You missed Datasource property and DataBind() method. In design environment, add a "PlaceHolder" control on a page (.aspx) (Say PlaceHolder1) protected void Page_Load(object sender, EventArgs e) { dta_grd = new DataGrid(); dta_grd.DataSource = Ex_DLL.GetData("select * from tstint/m02"); dta_grd.DataBind(); // this method populates the DataGrid from assigned datasource PlaceHolder1.Controls.Add(dta_grd); Lbl_Dsply.Visible = true; if (Supp_Data.Items.Count == 0) { Lbl_Dsply.Text = "No Records Found!"; } else { Lbl_Dsply.Text += dta_grd.Items.Count.ToString(); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7599666", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Importing csv into Numpy datetime64 I am trying out the latest version of numpy 2.0 dev: np.__version__ Out[44]: '2.0.0.dev-aded70c' I am trying to import CSV data that looks like this: date,system,pumping,rgt,agt,sps,eskom_import,temperature,wind,pressure,weather 2007-01-01 00:30,481.9,,,,,481.9,15,SW,1040,Fine 2007-01-01 01:00,471.9,,,,,471.9,15,SW,1040,Fine 2007-01-01 01:30,455.9,,,,,455.9,,,, etc. by using the following code: convertdict = {0: lambda s: np.datetime64(s, 'm'), 1: lambda s: float(s or 0), 2: lambda s: float(s or 0), 3: lambda s: float(s or 0), 4: lambda s: float(s or 0), 5: lambda s: float(s or 0), 6: lambda s: float(s or 0), 7: lambda s: float(s or 0), 8: str, 9: str, 10: str} dt = [('date', np.datetime64),('system', float), ('pumping', float),('rgt', float), ('agt', float), ('sps', float) ,('eskom_import', float),('temperature', float), ('wind', str), ('pressure', float), ('weather', str)] a = np.recfromcsv(fp, dtype=dt, converters=convertdict, usecols=range(0-11), names=True) The dtype it generates for a.date is 'object': array([2007-01-01T00:30+0200, 2007-01-01T01:00+0200, 2007-01-01T01:30+0200, ..., 2007-12-31T23:00+0200, 2007-12-31T23:30+0200, 2008-01-01T00:00+0200], dtype=object) But I need it to be datetime64, like in this example (but including hrs and minutes): array(['2011-07-11', '2011-07-12', '2011-07-13', '2011-07-14', '2011-07-15', '2011-07-16', '2011-07-17'], dtype='datetime64[D]') It seems that the CSV import creates an embedded object datetype for 'date' rather than a datetime64 data type. Any ideas on how to fix this? Grové A: I think the trick to avoid the generic 'object' type is to avoid using the recfromcsv function. Manually reading in your data file and parsing the information yields the requested dtype='datetime64[m]' import numpy as np dt = np.dtype([ ('date', '<M8[m]'), ('system', '<f8'), ('pumping', '<f8'), ('rgt', '<f8'), ('agt', '<f8'), ('sps', '<f8'), ('eskom_import','<f8'), ('temperature', '<f8'), ('wind', np.str), ('pressure', '<f8'), ('weather', np.str) ]) numfields = len(dt.fields.keys()) data = np.zeros(numlines, dtype=dt) fid = open('data.csv', 'rb') count = 0 try: fieldnames = fid.readline().strip().split(',') #Header for line in fid: parsedline = line.strip().split(',') data['date'][count] = np.datetime64(parsedline[0], 'm') data['system'][count] = np.double(parsedline[1]) data['pumping'][count] = np.double(parsedline[2]) data['rgt'][count] = np.double(parsedline[3]) data['agt'][count] = np.double(parsedline[4]) data['sps'][count] = np.double(parsedline[5]) data['eskom_import'][count] = np.double(parsedline[6]) data['temperature'][count] = np.double(parsedline[7]) data['wind'][count] = np.str(parsedline[8]) data['pressure'][count] = np.double(parsedline[9]) data['weather'][count] = np.str(parsedline[10]) count += 1 finally: fid.close() >>> data['date'] array(['2007-01-01T00:30-0500', '2007-01-01T01:00-0500', '2007-01-01T00:30-0500', '2007-01-01T01:00-0500', '2007-01-01T00:30-0500', '2007-01-01T01:00-0500', '2007-01-01T00:30-0500', '2007-01-01T01:00-0500'], dtype='datetime64[m]') You could definitely improve upon this code by making use of your "convertdict" and iterating over the parsedline but the idea is the same.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599667", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to custom init an EAGLView? In my iOS project, glView ends up with height=0 and width=0 even though CGRect frame correctly gets the screen's dimensions in the previous line. - (void) applicationDidFinishLaunching:(UIApplication*)application { CGRect frame = [[UIScreen mainScreen] bounds]; EAGLView *glView = [EAGLView viewWithFrame:frame pixelFormat:kEAGLColorFormatRGB565 depthFormat:0 preserveBackbuffer:NO sharegroup:nil multiSampling:NO numberOfSamples:0 ]; } Is there some other way I need to create my EAGLView *glView in order for it to be init'ed properly? A: You will have to add the glView to a UIWindow. Check out the app delegate code in the Cocos2D project templates.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599670", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MS Access 2007 Append query trouble I have an append query that is trying to append some records to one of my tables. However, I am getting an error that says “didn’t add 1200 records due to key violations.” 1200 is the total number of records I am trying to append. I don’t understand why I am getting this error because all of my columns in the destination table allow duplicates (even though this append query doesn’t duplicate any information), and if I copy the structure of the table and append the records to that, everything works. The problem seems to be that I am appending data to a table which already has existing data. Can someone please offer some suggestions for how I can work around this? Thanks A: Verify you haven't overlooked any unique indexes on your table. Save this procedure in a standard module and call it from the Immediate Window with the name of your destination table. Public Sub InspectIndexes(ByVal pTable As String) Dim db As DAO.Database Dim i As Long Dim j As Long Dim strFields As String Set db = CurrentDb With db.TableDefs(pTable) Debug.Print "Indexes.Count = "; .Indexes.Count For i = 0 To (.Indexes.Count - 1) With .Indexes(i) Debug.Print i + 1 & ": Index Name = "; .name If .Primary Then Debug.Print vbTab & "Primary Key (Unique)" Else Debug.Print vbTab & "Unique: "; .Unique End If Debug.Print vbTab & "Fields.Count = "; .Fields.Count strFields = vbNullString For j = 0 To (.Fields.Count - 1) strFields = strFields & "; " & .Fields(j).name Next j strFields = Mid(strFields, 3) Debug.Print vbTab & "Fields: "; strFields End With Next i End With Set db = Nothing End Sub Here is sample output where tblFoo has 3 indexes: primary key (unique by definition) on id; a unique index on num_field1 and num_field2; and a non-unique index on parent_id. InspectIndexes "tblfoo" Indexes.Count = 3 1: Index Name = both_num_fields Unique: True Fields.Count = 2 Fields: num_field1; num_field2 2: Index Name = parent_id Unique: False Fields.Count = 1 Fields: parent_id 3: Index Name = pkey Primary Key (Unique) Fields.Count = 1 Fields: id
{ "language": "en", "url": "https://stackoverflow.com/questions/7599671", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Create WCF service client with specified address without specifying configuration name Is there a way to create an instance of a WCF service client in C# with a specified endpoint address without specifying a configuration name? By default, clients have these constructors: public ServiceClient() public ServiceClient(string endpointConfigurationName) public ServiceClient(string endpointConfigurationName, string remoteAddress) Obviously, there is a default configuration, because of the first constructor. What I want is to only specify the 2nd parameter of the final constructor. Right now, I'm struggling through reading the configuration elements of using ConfigurationManager to figure it out, but it seems horribly cumbersome. Is there a cleaner way? A: Your generated client should also have a constructor that looks like this: public ServiceClient( System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) : base(binding, remoteAddress) { } You can call this one without an endpoint configuration. A: If you want to actually just want to call a service without having to know everything there is to know about WCF services and configuration handling, in C # you can just do... String url = "http:\\somehost:someport\\pathToSomeService"; EndpointAddress address = new EndpointAddress(url); Binding binding = new BasicHttpBinding(); YourClient client = new YourClient(binding, address); // Call your client methods client.SomeMethod(parm1, parm2); The above assumes you generated a service reference and does not require configuration information to exist anywhere, not in the generated service reference, not in the DLL and not in the executable. No configuration. None. I use the above in a true standalone service proxy dll. It is standalone in the truest sense of the word as it is completely configurable with no dependence on the calling executable to provide anything. A: I prefer not to use the endpoint configuration in the .config file. I normally do something like this: BasicHttpBinding basicbinding = new BasicHttpBinding(); basicbinding.SendTimeout = TIMEOUT; basicbinding.OpenTimeout = TIMEOUT; ServiceClient client = new ServiceClient(basicbinding, new EndpointAddress(new Uri("http://xxxxx"))); A: Well, you could use the default constructor, but then you'd have to manually program in all of the configuration settings. By specifying the configuration name, the service client will automatically load the configuration in from the .config file, all you need to know is which configuration to use (you can have multiple, e.g. one for HTTP and another for Net.Tcp). The remoteAddress, of course, just tells WCF where to make the connection. If you are having trouble configuring the client settings themselves, make sure you're using the WCF Service Configuration tool. It works for both the service config as well as the client config.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599677", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Jqgrid Master Detail don't send the appropriate info I'm searching about my problem here and find some tips, but doesn't work anyway, my problem is this: In the jqgrid Javascrip, I send as setGridParam this: {url:'myurl/myfunction/'+ id, page:1, datatype:"json"} but, the Jgqgrid still doesn't sending to my controller the Id for make a selection of the details, It´s always null..... I tried everyting and the problem persist, please help me. Here's my Javascript: <script type="text/javascript"> jQuery(document).ready(function() { jQuery("#list").jqGrid({ url: '/Master/GridData/', datatype: 'json', mtype: 'GET', colNames: ['Id', 'Descripción'], colModel: [ { name: 'Id', index: 'Id', width: 50 }, { name: 'Descripcion', index: 'Descripcion', width: 80, sortable: true, editable: true, edittype: "text", editoptions: { maxlength: "100"} } ], pager: jQuery('#pager'), autowidth: true, rowList: [5, 10, 20, 50], sortname: 'Id', sortorder: "asc", viewrecords: true, caption: '<b>Listado de Masters</b>', onSelectRow: function(ids) { if (ids != null) { var data = $("#list").getRowData(ids); jQuery("#DetailList").setGridParam({ url: "/Master/DetailGridData/" + data.Id, page: 1, datatype: 'json' }) .setCaption("<b>Details of Master : " + data.Descripcion+"</b>") .trigger('reloadGrid'); } } }).navGrid(pager, { edit: false, add: false, del: false, refresh: true, search: false }); jQuery("#DetailList").jqGrid ({ height: 100, datatype: "json", colNames: ['Id', 'Descripción', 'Modelo'], colModel: [ { name: 'Id', index: 'Id', width: 50 }, { name: 'Descripcion', index: 'Descripcion', width: 80, sortable: true, editable: true, edittype: "text", editoptions: { maxlength: "100"} }, { name: 'Modelo', index: 'Modelo', width: 80, sortable: true, editable: true, edittype: "text", editoptions: { maxlength: "100"} } ], rowNum: 5, rowList: [5, 10, 20], pager: jQuery('#DetailPager'), sortname: 'Id', viewrecords: true, sortorder: "desc" }).navGrid('#DetailPager', { add: false, edit: false, del: false, search: false }); }); </script> And here's my Controller Code: public ActionResult GridData(string sidx, string sord, int? page, int? rows) { List<Master> ms = new List<Master>(); ms = MasterRepository.GetAll().ToList<Master>(); int pageIndex = Convert.ToInt32(page) - 1; int totalrecords = ms.Count(); int totalpages = (int)Math.Ceiling((decimal)totalrecords / (decimal)rows); var jsonData = new { sidx = "Id", sord = "asc", page = 1, records = 25, rows = ( from ch in ms select new { id = ch.Id, cell = new string[] { ch.Id.ToString(), ch.Descripcion, } }).ToArray(), }; return Json(jsonData, JsonRequestBehavior.AllowGet); } public ActionResult DetailGridData(string IdMaster, string sidx, string sord, int? page, int? rows) { int IdCh = Convert.ToInt32(IdMaster); IList<Detail> det = new List<Detail>(); det = DetailRepository.GetByMaster(IdCh).ToList<Detail>(); int pageIndex = Convert.ToInt32(page) - 1; int totalrecords = det.Count(); var jsonData = new { sidx = "Id", sord = "asc", page = 1, records = 25, rows = ( from bah in det select new { id = bah.Id, cell = new string[] { bah.Id.ToString(), bah.Descripcion, bah.Modelo } }).ToArray(), }; return Json(jsonData, JsonRequestBehavior.AllowGet); } } } A: I think you should verify routes.MapRoute which you added to the route table. Do you really use IdMaster parameter or you should rename it to Id? It can be that you just forget to add the custom rule. Another problem which I could see is the syntax error: you use .navGrid(pager, {... instead of .navGrid('#pager', {... (the variable pager in undefined). Another possible problem is possible id duplicates. Be sure that ids of the detail grid has another values as the ids from the master grid. Because ids are strings you can for example use prefixes for the ids: like 'm_'+ch.Id for the master grid and 'd_'+bah.Id for details grid. Some more remarks: * *sidx and sord should not be included in the JSON response of the server. Instead of that total should be included. See here for more information. *I recommend you to use datatype: "local" instead of datatype: "json" for the details grid definition. It will prevent attempt to load data at the grid initialization. *I recommend you to use pager: '#pager' instead of pager: jQuery('#pager'). *I recommend you to use key: true in the 'Id' column. In the case you will don't need to send Id values twice. If you would use additionally jsonReader: {cell:''} you can remove cell property like id property from the rows data. So you can use about the following from ch in ms select new { new string[] { ch.Id.ToString(), ch.Descripcion }}).ToList(). See here or here for example. *I recommend you to use error handling on the jqGrid at the beginning of your code. See the UPDATED part of the answer with the demo project. Displaying of error messages can save many time of your debugging. The demo could be interesting for you as a ASP.NET MVC code example which use jqGrid. A: i think there is a issue in url string format. it should be like jQuery("#DetailList").setGridParam({ url: "/Master/DetailGridData/?id=" + data.Id, page: 1, datatype: 'json' }) A: I have finally found the solution, thanks for the suggestion aamir and Oleg. I had to do was the following: First change the name Id in the MasterGrid by IdMaster, so there is no confusion with the Id of the Detail Grid, then correct the line where setGridParam is sent by the following: jQuery("#DetailList").setGridParam({ datatype: 'json', url: "/Master/DetailGridData?IdMaster=" + data.IdMaster, page: 1 }) That was it and now everything works fine...!! ;) Thanks again aamir and Oleg... you save my day..!!
{ "language": "en", "url": "https://stackoverflow.com/questions/7599681", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How add custom text to AddressBook contacts in iPhone? I have working in a app for iPhone and I am getting de AddressBook contacts. I got it access to contact, but I wish add some text in some contacts (like WhatsApp), something like this: Could someone help me please? Thank you very much. A: See the Table View Programming Guide, especially this section. You will want to use UITableViewCellStyleSubtitle.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599684", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Should I use one form on page or generate a form per item? I want to display a list of items. Each item would have an edit and a delete icon next to it. For obvious reasons I want to trigger the delete action with HTTP POST. With jQuery, I would bind links to trigger form.submit. However I'm not sure if I should generate a form next to each item or use just one form. Below are pros and cons of two approaches as I see them. Form Per Item: * *easy to generate; *no need to fiddle in JS to set action and input value. Single Form: * *makes more sense semantically; *requires client JS to set hidden input; *requires client JS to set form action (e.g. id + '/delete/). What is there to add? What is the preferred pattern in modern HTML apps? A: The main disadvantage I see in having a single form enclosing all list elements is that you can end up with a huge POST if the list is long. As an advantage, you could mark multiple elements for deletion (checkboxes, for instance) and perform a single delete request. I'd go for either * *A single form for each list element. This would make deletion of multiple elements impossible, but would keep POST sizes minimal. *Using a single form, but in a way that doesn't include all the list elements. For instance, having a delete only form with a single hidden element in it, into which you would put all the id's marked for deletion with JS manipulation. As a side note, you could also skip forms and perform the needed interactions through ajax. This would improve user experience notably. Take into account that forms would still be needed to provide fallback mechanisms in case it was required. A: I have used checkboxes in the past. This is better for usability, and each checked checkbox can pass its own ID to the form processing script. A: In the end, I decided to go with AJAX via jQuery.ajax. The reason is semantically I don't even have forms—I have buttons. Therefore, jQuery is an easier solution as it allows to keep posting logic in one place (as opposed to scattering it across HTML and JS). I assigned row class to each semantical row and put corresponding database IDs in HTML5 data attribute called data-row-id for each row. <div class="row" data-item-id="{{ product.id }}"> <!-- ... ---> <a href="#" class="delete-btn"><img src="/img/delete.png" alt="Delete"></a> </div> Then I have something alone the lines of $('.delete-btn').click(function() { var row = $(this).closest('.row'); var id = row.data('item-id'); $.ajax({ url: id + '/delete/', type: 'POST' }); row.fadeOut().slideUp(); return false; } in my $() load handler. This solution scales beautifully across the whole codebase because you only have to set row class and data-item-id attribute and the buttons will “just work”.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599687", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SEO URL rewriting ASP.NET I already have an ASP.NET Web Site I want to change my site to be more SEO url friendly. I want to change ex. this site: www.mydomain.aspx?articleID=5 to: www.mydomain/article/learningURLrewrite - articlename needs to be read from DB How do I accomplish this? I have already tried with some articles from Google which mentions IhttpModule without any luck. My goal is to have a class responsible for redirecting based on folderpath(like this): string folderpath = "my folderpath" (could be articles, products etc.) string id = Request.QueryString["id"].ToString(); if(folderpath.equals("articles")) { string name = //find name from id in DB //redirect user to www.mydomain/article/name } if(folderpath.equals("products")) { string name = //find name from id in DB //redirect user to www.mydomain/products/name } Also I want to remove the aspx extension A: You can use routing with ASP.NET WebForms too. The steps are: * *Add the route (or routes) at application start. //In Global.asax void Application_Start(object sender, EventArgs e) { RouteTable.Routes.MapPageRoute("My Routename", "{*name}", "~/Article.aspx"); } *Create the Article.aspx as a normal webform *In the code for Article.aspx, you can access the url path like this: public void Page_Load(object sender, EventArgs e) { var thePath = RouteData.Values["name"]; // Lookup the path in the database... } A: This posting tells you exactly how to use asp.net 4's routing engine - give it a whirl - if you have a specific problem in implementing it let us know. http://weblogs.asp.net/dotnetstories/archive/2011/01/03/routing-in-asp-net-4-0-web-forms.aspx Since you need specific parameter usage, you can define the parameters to get sent to your page. For that see: http://msdn.microsoft.com/en-us/library/cc668177.aspx and How to: Access URL Parameters in a Routed Page A: If you are using ASP.NET 4, then you should look into URL Routing. You would end up setting up custom routes like so: routes.MapPageRoute( "View Article", // Route name "Articles/{*ArticleName}", // Route URL "~/Articles.aspx" // Web page to handle route ); And you write out the new links like so: Page.GetRouteUrl("View Article", new { ArticleName= NAMEFROMDATABASE }); Unfortunately I won't give you a summary of how to build your entire site, but 2 really good places to start are an article by Scott Gu, and one on 4 Guys. A: If you are using .net 3.5 or less then you can use these * *http://urlrewriting.net *http://urlrewriter.net I use the second one, in all my projects made in .net 3.5 if using .net 4.0 then you can do these * *URL routing ( I think it does not support sub domain rewriting) *URL Rewrite 2.0 ( works with IIS 7 only) UPDATE Add these lines below the appSettings tag <rewriter configSource="URLRewriter.config"/> Then create separate file named as URLRewriter.config And in that you can write like this (Add processing stop for the files not to be rewritten i.e images and js, etc) <rewrite url="^(/.+(\.gif|\.png|\.jpg|\.ico|\.pdf|\.css|\.js|\.flv|\.eot|\.svg|\.ttf|\.woff|\.txt|\.doc|\.docx|\.pdf|\.xls|\.xlsx|\.xml)(\?.+)?)$" to="$1" processing="stop" /> <rewrite url="~/article/([^/.]+)" to="~/articledetail.aspx?articlename=$1" /> Then you would get the article name in the query string like this string articlename = Request.QueryString["articlename"]; And the menu or other location of the site where you want to put the link to article, you can add an the AppSettings so that later on if you want to change the url pattern you can change it easily from the configs only, <add key ="ArticalDetailsURL" value="/article/{0}" /> Then, in the page you can do like this string articleName = "TestArticle"; lnkMenuLink.NavigateUrl = string.Format(ConfigurationSettings.AppSettings["ArticalDetailsURL"], articleName); Thanks and Regards, Harsh Baid
{ "language": "en", "url": "https://stackoverflow.com/questions/7599689", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Java EJB interfaces Could anyone explain me how do the functions inside the HOME and REMOTE interfaces relate to the Bean object? The interfaces are instanciated so that the functions are used. But the functions body rests only in the Bean object. What am I missing? A: The actual EJB instances will typically be instances of java.lang.reflect.Proxy that delegate calls to the bean's implementation class after doing their transaction-, clustering- and security-stuff. A: The Java EE container is dealing with those details for you. It knows to find the bean implementation when a call is made to that interface. It hides all the magic from you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599695", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Show LiteralControl in GridView dynamically I create an html and set it to a literalControl. Then I'm trying to insert this literalControl in a repeater's ItemTemplate. But when I do this, it is seen as "System.Web.UI.LiteralControl" text, not the html inside. Here's the code: <asp:Repeater> //SomeColumns <ItemTemplate> <%# GetPriorityBox(DataBinder.Eval(Container.DataItem, "StartDate"), DataBinder.Eval(Container.DataItem, "EndDate") %> </ItemTemplate> </asp:Repeater> It is seen from the browser like: SomeColumn | SomeColumn | System.Web.UI.LiteralControl A: Add a .Text to the end of that statement... it won't inject a control using <%# %> notation. It will only inject markup, so you have to inject the text only. If you want the control injected, tap into ItemDataBound event, and programmably add the control. HTH. A: Just add the markup directly to the ItemTemplate. Change your GetPriorityBox method to return the Text property of the LiteralControl.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599696", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQL Array within a cell I have a cell that contains an array of characters seperated by commas i.e. "1,2,3,4,5" My question is, is it possible to remove a particular element of the array such as if I wanted to remove "1" then the cell would then become "2,3,4,5" or remove "3" and it becomes "1,2,4,5" I want to perform this task within SQL either as a function or a stored procedure, any help is much appreciated. A: Sure, it'd just be some basic string REPLACE() calls: http://msdn.microsoft.com/en-us/library/ms186862.aspx However, since you have to manipulate individual bits of this data field separately from the rest of the field, it's a good candidate for getting normalized into its own child table.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599697", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Reliably Sending Emails Through Gmail SMTP I have a C# application that sends emails through smtp.gmail.com. If I ever send about 20 emails, I start getting errors like The server response was: 4.7.0 Temporary System Problem. Try again later (WS) Usually, about 17 messages out of 20 ever end up getting sent. Note that I am not saying 20 messages were sent and only 17 were successfully delivered, I mean that only 17 actually even try to get sent. I can't find much specific info on this error, but I assume this is related to some kind of a gmail throttling limit, because I don't see this error if I only send like 1-5 emails at a time. Can someone confirm what this means and why it happens?
{ "language": "en", "url": "https://stackoverflow.com/questions/7599701", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Handle APNS Remote Notifications while in Background I have implemented all recommended methods in AppDelegate to get working Remote Notifications service. I can accept them while running, while launching and while turned off. But there is an issue, since I can't work with many received notifications while in background. I can work only with latest notification. What is recommended manual to do that? How can I got all notifications received while in background? Is it only solvable via manual call to my service provider (sender of apns data)? A: With all the projects I've worked on there hasn't been a way to locally store this information if the push notification is dismissed. In all those cases we used a small file on the server that the app would connect to and pull when it became active again. There was also some place in the app where the user could see all their notifications which, again, were stored on the server for quick retrieval. With the way I understand push notifications to be setup, if the notification is dismissed the system discards it. It'll perform anything it's supposed to do (such as update the badge number and play the correct sound) but any additional information specific to that notification is lost. A: Not sure if this helps, but if you just want to know how many notifications you have missed while you were in background. You can create a variable which contains notification number and store this in the app every time you handle notification. When you come out of background and receive a new notification you can subtract the new number with the stored number to find out the number of missed notifications. I don't think there is a way where iOS can give you complete data associated with all the notification device have received while the app was in background. A: The best solution is to keep a list of sent notifications with all relevant data on your server, so the app can access that data when it launches. Sending multiple notifications with data that is not stored on the server can be risky, because the application only receives the notification when the user opens the app from that notification, so if they tap on one notification, the app will only every receive that one. If you have them all in a list on your server, the app can simply go and pull that list down, and process it, making sure no data is lost.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599704", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Jquery: probleme with $.ajax (json datatype) I have a problem to refresh a bloc in my page. Here is the request: > $("#pwd_lost_link").click(function(){ alert('1'); $.ajax({ type : 'POST', url: 'test.php', dataType: 'json', data :{"nom" : "akbar"}, success : function(data){ $("#main_bloc").append(data.msg); alert('2'); }, error : function(XMLHttpRequest, textStatus, errorThrown) { alert(XMLHttpRequest.responseText); alert(errorThrown); } }); }) and here is the php file <?php $return['nom'] = "ffrfrfrfr"; echo json_encode($return) ?> It doesn't work. It give me a status error ( 0 ) and the page is automatically reloaded Thanks Michaël A: Confusing question Michael, not sure what you mean by "the page is automatically reloaded" but you should do 2 things: In the $.ajax() method, make sure your success called back is handling the data correctly. You are looking for data.msg but I don't see where .msg comes from. $.ajax({ type: "GET", contentType: "application/json; charset=utf-8", data: {}, dataType: "json", url: url, success: function(data) { // parse data object so you can see what's being returned ex. alert(data) or alert(data[0]) or alert(data.nom) }, error: function (xhr, status, error) { // XHR DOM reference: http://www.w3schools.com/dom/dom_http.asp // check for errors ex. alert(xhr.statusText); } }); On the PHP side, you may want to debug there to see what is being received and what you are sending back. Aside from that using an XHR viewer like Firebug or Chrome's built-in utility (CTRL+SHIFT+I) can be very helpful. And on a final note, if pwd_lost_link is a link elment a id="pwd_lost_link" href="..." then you will have to stop the browser from following the link before you process the AJAX. $("#pwd_lost_link").click(function(e) { e.preventDefault(); alert('1'); $.ajax({ ... }); If you aren't seeing the '1' being alerted then that is definitely your first problem. A: You're trying to access data.msg, but your PHP script is only creating data.nom. So data.msg doesn't exist. Try changing data.msg to data.nom and see if this does what you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599706", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Checkout the git commit corresponding to a certain revision from the old SVN repository? I migrated my repository from SVN to git. I used THIS site. Now I have a bug in revision X. How do I checkout from my git repository, knowing only the revision number from my old SVN repo? Thank you for your Help. A: You can find the git commit that corresponds to the Subversion revision with the git svn find-rev subcommand. For example, if you're looking for the commit that corresponds to Subversion revision 3431 you can do: $ git svn find-rev r3431 42ed8bcf690fd0c655c5cee91b09258318fc56e8 Then, to checkout that revision, just use the object name from the first line, e.g. if it's: commit 42ed8bcf690fd0c655c5cee91b09258318fc56e8 Author: torstenrohlfing <torstenrohlfing@42a5c34f-2066-0410-bec5-ba365beb4995> Date: Fri Sep 9 17:11:38 2011 +0000 FIX: do not update time stamps on pre-existing files that did not get updated. git-svn-id: https://www.nitrc.org/svn/cmtk/trunk@3431 42a5c34f-2066-0410-bec5-ba365beb4995 You can do: git checkout 42ed8bcf69 ... to try that revision. (Note that this will detach HEAD, so if you don't know what that means, it would be worth searching for "detached HEAD" first :))
{ "language": "en", "url": "https://stackoverflow.com/questions/7599707", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Refining results of an existing search query in Android In my Android app, I want to execute a query against a content provider, and then refine that search (I have two WHERE clause strings). The records that should be returned by the second query are a subset of the rows returned by the first query. My current solution is like this: Cursor cursor1 = query (myUri, myProjection, where1, null, null); //do stuff Cursor cursor2 = query (myUri, myProjection, where2, null, null); //do other stuff If I do this, the second query run is not very efficient at all (it searches the full database, just like the first). I would like the second query to run only against the rows that are returned in cursor1. Can this be done, and how? The android documentation states that queries may be cached if I use the same (parameterised) where string, with different parameters. Could this be useful, or is there a totally different way to do it? A: Check CursorAdapter. It implements Filterable interface and contains a few interesting methods: setFilterQueryProvider and getFilterQueryProvider. I haven't used CursorAdapter, but if it is similar to other adapters (or custom adapters implementing Filterable) then it is exactly what you need. UPDATE Here is an example: http://www.outofwhatbox.com/blog/2010/11/android-simpler-autocompletetextview-with-simplecursoradapter/ The part you are interested in is this: adapter.setFilterQueryProvider(new FilterQueryProvider() { public Cursor runQuery(CharSequence constraint) { // Search for states whose names begin with the specified letters. Cursor cursor = mDbHelper.getMatchingStates( (constraint != null ? constraint.toString() : null)); return cursor; } }); As it returns new Cursor instance I assume that it does hit DB one more time. You might implement your own search logic by iterating cursor and looking for matches. You will have to write some benchmark to see if it is worth avoiding hitting database with a new Query as by manually iterating Cursor you will be hitting database harder. Remember that you do not actually retrieve data (row/record) from DB unless you explicitly ask for it (by calling any of the readXXX() on a Cursor). BTW you might be interested in ORMLite
{ "language": "en", "url": "https://stackoverflow.com/questions/7599718", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: real time output in php Possible Duplicate: How to make For Loop Real Time in PHP I think when we run php script,web server wait until end of script and after that will return output. for example if following script doesn't have output. set_time_limit(0); $i = 0; while(1) { $i++; if ($i%10 == 0) echo 'Salam'; } How can I have real time output?I mean the script is not ended yet,but it echoed somethings. A: Have a look at flush(). A: Call flush when you want the current output to be displayed. If you are using output buffering, you also need to call ob_flush.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599719", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Caching in a console application I need to cache a generic list so I dont have to query the databse multiple times. In a web application I would just add it to the httpcontext.current.cache . What is the proper way to cache objects in console applications? A: In a class-level variable. Presumably, in the main method of your console app you instantiate at least one object of some sort. In this object's class, you declare a class-level variable (a List<String> or whatever) in which you cache whatever needs caching. A: Here is a very simple cache class I use in consoles that has self clean up and easy implementation. The Usage: return Cache.Get("MyCacheKey", 30, () => { return new Model.Guide().ChannelListings.BuildChannelList(); }); The Class: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Timers; namespace MyAppNamespace { public static class Cache { private static Timer cleanupTimer = new Timer() { AutoReset = true, Enabled = true, Interval = 60000 }; private static readonly Dictionary<string, CacheItem> internalCache = new Dictionary<string, CacheItem>(); static Cache() { cleanupTimer.Elapsed += Clean; cleanupTimer.Start(); } private static void Clean(object sender, ElapsedEventArgs e) { internalCache.Keys.ToList().ForEach(x => { try { if (internalCache[x].ExpireTime <= e.SignalTime) { Remove(x); } } catch (Exception) { /*swallow it*/ } }); } public static T Get<T>(string key, int expiresMinutes, Func<T> refreshFunction) { if (internalCache.ContainsKey(key) && internalCache[key].ExpireTime > DateTime.Now) { return (T)internalCache[key].Item; } var result = refreshFunction(); Set(key, result, expiresMinutes); return result; } public static void Set(string key, object item, int expiresMinutes) { Remove(key); internalCache.Add(key, new CacheItem(item, expiresMinutes)); } public static void Remove(string key) { if (internalCache.ContainsKey(key)) { internalCache.Remove(key); } } private struct CacheItem { public CacheItem(object item, int expiresMinutes) : this() { Item = item; ExpireTime = DateTime.Now.AddMinutes(expiresMinutes); } public object Item { get; private set; } public DateTime ExpireTime { get; private set; } } } } A: // Consider this psuedo code for using Cache public DataSet GetMySearchData(string search) { // if it is in my cache already (notice search criteria is the cache key) string cacheKey = "Search " + search; if (Cache[cacheKey] != null) { return (DataSet)(Cache[cacheKey]); } else { DataSet result = yourDAL.DoSearch(search); Cache[cacheKey].Insert(result); // There are more params needed here... return result; } } Ref: How do I cache a dataset to stop round trips to db? A: Keep it as instance member of the containing class. In web app you can't do this since page class's object is recreated on every request. However .NET 4.0 also has MemoryCache class for this purpose. A: There a many ways to implement caches, depending of what exactly you are doing. Usually you will be using a dictionary to hold cached values. Here is my simple implementation of a cache, which caches values only for a limited time: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CySoft.Collections { public class Cache<TKey,TValue> { private readonly Dictionary<TKey, CacheItem> _cache = new Dictionary<TKey, CacheItem>(); private TimeSpan _maxCachingTime; /// <summary> /// Creates a cache which holds the cached values for an infinite time. /// </summary> public Cache() : this(TimeSpan.MaxValue) { } /// <summary> /// Creates a cache which holds the cached values for a limited time only. /// </summary> /// <param name="maxCachingTime">Maximum time for which the a value is to be hold in the cache.</param> public Cache(TimeSpan maxCachingTime) { _maxCachingTime = maxCachingTime; } /// <summary> /// Tries to get a value from the cache. If the cache contains the value and the maximum caching time is /// not exceeded (if any is defined), then the cached value is returned, else a new value is created. /// </summary> /// <param name="key">Key of the value to get.</param> /// <param name="createValue">Function creating a new value.</param> /// <returns>A cached or a new value.</returns> public TValue Get(TKey key, Func<TValue> createValue) { CacheItem cacheItem; if (_cache.TryGetValue(key, out cacheItem) && (DateTime.Now - cacheItem.CacheTime) <= _maxCachingTime) { return cacheItem.Item; } TValue value = createValue(); _cache[key] = new CacheItem(value); return value; } private struct CacheItem { public CacheItem(TValue item) : this() { Item = item; CacheTime = DateTime.Now; } public TValue Item { get; private set; } public DateTime CacheTime { get; private set; } } } } You can pass a lambda expression to the Get method, which retrieves values from a db for instance. A: You might be able to just use a simple Dictionary. The thing that makes the Cache so special in the web environment is that it persists and is scoped in such a way that many users can access it. In a console app, you don't have those issues. If your needs are simple enough, the dictionary or similar structures can be used to quickly lookup values you pull out of a database. A: Use Singleton Pattern. http://msdn.microsoft.com/en-us/library/ff650316.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7599732", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: wordpress image path changing dependent on file I'm having problems with the paths to my first wordpress theme. Post images and stuff not related to css is located in wordpress_folder/blog-images/ and in index.php when I link to images I use this path: blog-images/img.jpg The problem is now that when I want to link to the same image from another file (not index.php) in this case single.php wich displays one blog post, the correct path is now ../../../blog-images/img.jpg This is causing problems in the includes like sidebar etc. sidebar.php works fine when called from index.php but the images path is changed if sidebar.php is called from single.php. Does anyone know what's going on? A: If you are creating these links from within php scripts, I would suggest using the site_url() function to get the URL for your wordpress install and then appending your images path to the end of that. If you are editing static theme files like css, then you should use /wordpress_folder/blog_images/img.jpg. Something like <img src="<?php echo site_url() ?>/blog_images/img.jpg" /> should be sufficient from theme files. The reason that paths are chaning is because if you are in wordpress_folder then the path blog_images/img.jpg resolves to wordpress_folder/blog_images/img.jpg but if you are on a post that has the url yoursite.com/wordpress_folder/2011/09/category/my_great_post then the path would resolve to wordpress_folder/2011/09/category/blog_images/img.jpg which is obviously incorrect. For this reason you should try to use the absolute path or full URL so that no matter what file/folder/url you are linking from, the path will always be correct. The main downside you may run into is that if you were to change the name of your wordpress folder, or remove it altogether, then you may need to make a lot of edits to reflect that. But in any case, you should put the / in front of your path so that it can be referenced the same from everywhere. Also check out the site_url() reference page, it lists some other helpful functions at the bottom that may be useful to you. A: I thought this was a little unclear from drew's answer, so I am adding a little bit more in a separate answer. His advice is sound and I agree with him. If you prepend a url with a / then it will navigate based on your site url. Without the slash it uses relative navigation. So here are some examples for www.mydomain.com //always shows the image located at http://www.mydomain.com/myfolder/pic.png //no matter what the url is <img src="/myfolder/pic.png" /> //shows the image located relative to the current path //if current url is http://www.mydomain.com/posts/ then the image will come from //http://www.mydomain.com/posts/myfolder/pic.png <img src="myfolder/pic.png" /> If you are creating links dynamically from php side then you will want to use site_url(). If you are creating links to your theme directory folder then you will want to use bloginfo('template_directory')
{ "language": "en", "url": "https://stackoverflow.com/questions/7599736", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Monodroid - GC.Collect fails without any reason I have an application with 4 tabs (TabActivity). By some reasons I call GC.Collect every time user switches tab (overriding OnPause Activity's method). Sometimes (approximately 1 time from 50-100 calls, but sometimes this happens when application just started) my application hangs in this moment. Here is part of my code: protected override void OnPause(){ base.OnPause(); try{ Android.Util.Log.Info("----","GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);"); GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); Android.Util.Log.Info("----","GC.Collect Finished"); }catch(Exception exc){ Android.Util.Log.Info("exc.Message",exc.Message); Android.Util.Log.Info("exc.StackTrace",exc.StackTrace); throw exc; } } And here is corresponding Android log output //Previous GC.Collect call, it's all ok I/---- ( 7796): GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); D/dalvikvm( 7796): GetMethodID: method not found: Landroid/widget/EditText;.monodroidAddReference:(Ljava/lang/Object;)V D/dalvikvm( 7796): GC_EXPLICIT freed 962 objects / 42472 bytes in 112ms I/---- ( 7796): GC.Collect Finished //On another call fails I/---- ( 7796): GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced); I/mono ( 7796): Stacktrace: I/mono ( 7796): I/mono ( 7796): at System.GC.Collect (int) <0x0001f> I/mono ( 7796): at System.GC.Collect (int,System.GCCollectionMode) <0x00017> I/mono ( 7796): at PixelsAndroid.CustomActivity.OnPause () <0x00067> I/mono ( 7796): at Android.App.Activity.n_OnPause (intptr,intptr) <0x00037> I/mono ( 7796): at (wrapper dynamic-method) object.908cefd4-40eb-4dd1-97cd-f731b2ada74a (intptr,intptr) <0x0002b> I/mono ( 7796): at (wrapper native-to-managed) object.908cefd4-40eb-4dd1-97cd-f731b2ada74a (intptr,intptr) <0xffffffff> No any exception to been thrown, no any visible reason to fail. Application just hangs, after few seconds I get Android OS alert: "Oppps, your application got stuck. Force close or wait?" Anybody faced with it? A: There was a bug in some old versions of monodroid: if you call GC.Collect and an http request in a parallel threads, this caused crash. Update to a latest version of monodroid. A: Having to do a GC.Collect() under any circumstance is a bad code smell. Figure out the underlying reason and perform corrective rearchitecture.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599737", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Express/Node.js - How to save an array of objects within one Model Possible Duplicate: Mongoose - Form to save model with embedded documents I have a simple Mongoose schema with BlogPosts and Feeds embedded within those BlogPosts. So each BlogPost can have several Feed objects. Right now my HTML form allows me to correctly save one 'Feed' when I create a BlogPost, BUT I would like to be able to add many Feeds. How should I change my HTML/controller? Thanks much! web.js app.post('/blogpost/new', function(req, res){ var post = new BlogPost(req.body.post) post.feeds.push(req.body.feed); post.save(function() { res.redirect('/blogposts'); }); }); /blogpost/new <form method="post"> <input type="text" name="blogpost[title]"/> <textarea name="feed[name]"></textarea> <textarea name="feed[key]"></textarea> <textarea name="feed[name]"></textarea> <textarea name="feed[key]"></textarea> </form> schema var Feed = new Schema({ name : { type: String } , key : { type: String } }); var BlogPost = new Schema({ title : { type: String, required: true, index: { unique: true } } , feeds : [Feed] }); How do I make it so that this form stores two 'Feeds' in the blogpost object it creates? right now it would save One Feed in the data with two name values and two key values. Thanks much! A: When you do something like this: <textarea name="feed[name]"></textarea> <textarea name="feed[key]"></textarea> <textarea name="feed[name]"></textarea> <textarea name="feed[key]"></textarea> You are basically saying "I need a textbox for feed's name, feed's key, feed's name, feed's key which is obviously incorrect. If you did feed[0][name]...feed[1][name] that would say "i need a textbox for the first feed...i need a textbox for the second feed" Since you are breaking the parent and child up, rather than handling them as sub objects, you'll need to push each into the blogPost.feeds and save it. Just be careful with that approach, especially when editing, because you are simply adding new objects ontop of what could already be an existing array of feeds.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599739", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How do I recognize EOF in Java Sockets? I want to recognize end of data stream in Java Sockets. When I run the code below, it just stuck and keeps running (it stucks at value 10). I also want the program to download binary files, but the last byte is always distinct, so I don't know how to stop the while (pragmatically). String host = "example.com"; String path = "/"; Socket connection = new Socket(host, 80); PrintWriter out = new PrintWriter(connection.getOutputStream()); out.write("GET "+ path +" HTTP/1.1\r\nHost: "+ host +"\r\n\r\n"); out.flush(); int dataBuffer; while ((dataBuffer = connection.getInputStream().read()) != -1) System.out.println(dataBuffer); out.close(); Thanks for any hints. A: Actually your code is not correct. In HTTP 1.0 each connection is closed and as a result the client could detect when an input has ended. In HTTP 1.1 with persistent connections, the underlying TCP connection remains open, so a client can detect when an input ends with 1 of the following 2 ways: 1) The HTTP Server puts a Content-Length header indicating the size of the response. This can be used by the client to understand when the reponse has been fully read. 2)The response is send in Chunked-Encoding meaning that it comes in chunks prefixed with the size of each chunk. The client using this information can construct the response from the chunks received by the server. You should be using an HTTP Client library since implementing a generic HTTP client is not trivial (at all I may say). To be specific in your code posted you should have followed one of the above approaches. Additionally you should read in lines, since HTTP is a line terminated protocol. I.e. something like: BufferedReader in =new BufferedReader(new InputStreamReader( Connection.getInputStream() ) ); String s=null; while ( (s=in.readLine()) != null) { //Read HTTP header if (s.isEmpty()) break;//No more headers } } By sending a Connection: close as suggested by khachik, gets the job done (since the closing of the connection helps detect the end of input) but the performance gets worse because for each request you start a new connection. It depends of course on what you are trying to do (if you care or not) A: * *You should use existing libraries for HTTP. See here. *Your code works as expected. The server doesn't close the connection, and dataBuffer never becomes -1. This happens because connections are kept alive in HTTP 1.1 by default. Use HTTP 1.0, or put Connection: close header in your request. For example: out.write("GET "+ path +" HTTP/1.1\r\nHost: "+ host +"\r\nConnection: close\r\n\r\n"); out.flush(); int dataBuffer; while ((dataBuffer = connection.getInputStream().read()) != -1) System.out.print((char)dataBuffer); out.close();
{ "language": "en", "url": "https://stackoverflow.com/questions/7599742", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Benefit of having an abstract class implement an interface? I recently asked this question on if I should implement interfaces or abstract classes. Scottm gave answer suggesting I use both, but I am still unsure why I would want to do this. Is there a benefit in the long term? What are advantages of doing it that way? Here are some benefits I think: * *I can add methods to abstract class without breaking the implementation, but with interfaces, I would break it. *I can inherit from multiple interfaces, but only one abstract class *Abstract class allows me to define standard behavior, but override it if I want to. Here is another question. If I implement an interface, should the interface only contain methods that all sub-classes can do? And if I need extra logic, I would create a concrete class or abstract class with more specific implementations. A: This approach gives you the best of both worlds - the flexibility of interfaces with the helpful option of a base class. By requiring only that consumers implement your interface, you are not forcing them to lose the only inheritance slot open to their class (C# not allowing multiple inheritance). But by additionally offering an abstract base class, you can give them a "leg up", perhaps by implementing some helper functionality that is likely to be a common requirement to most implementations of your interface - for example this could be achieved using a Template Method pattern. There are several examples in the .NET Framework itself of both an interface and a base class being exposed. For example System.ComponentModel.IComponent and System.ComponentModel.Component Here is another question. If I implement an interface, should the interface only contain methods that all sub-classes can do? Yes. You're essentially describing the Interface Segregation Principle. A: The interface would define the contract. Any implementer (either directly or via an abstract implementer) would conform to this contract. An abstract class means you could reuse parts of an implementation across concrete implementations - you could have more than one abstract class, implemented differently. A: I'm assuming C# here because the other question had a C# tag The obvious benefit is that in the future you have another class, that already inherits from a base class, and you want to pass that to a method that accepts the . . . You can't do put first base class in there, because C# doesn't all multiple inheritance, so you can never pass object that subclasses a different class in there. You can however put interface in there, because the new object can always implement the Interface, even if it logically should derive from the base class. Having both means the base class can implement the interface, that suits you now because you can put common logic in there, you don't need to repeat yourself, or have a heap of static methods in a "helper" class. Also in the future if you have other classes that you want to use, they don't have to inherit the base class, then can just implement the interface. Hope this makes sense :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7599744", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: rails 3.0.3 activerecord wants to pluralize certain mysql tables all of a sudden This is in development mode. ActiveRecord::StatementInvalid. This is an example: I have a model called DisplayAds. Now activerecord wants to query the table as display_adses instead of display_ads. I have another model called Media. Activerecord use to query the table medias. Now it wants to query a table called medium. I know that DisplayAds is not the proper naming convention but it was working until now. I realize I can fix this by putting set_table_name in the model. I have not upgraded rails and everything has been working fine for months. I have a live production version of this site and it is not experiencing this problem. I do git status and I do not see any config files as being modified. What could I have done to start this happening? How can I stop it? A: Have you recently upgraded from 2.3.5/8 to 3.0.x? I had the same problem (same thing with medias). You'll want to add irregular Inflections in your config/initializers/inflections.rb file ActiveSupport::Inflector.inflections do |inflect| inflect.irregular 'media', 'medias' inflect.irregular 'display_ad', 'display_ads' ... end
{ "language": "en", "url": "https://stackoverflow.com/questions/7599746", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Javascript class inheritence I am trying to learn how to work with 'classes' in javascript. Here is my code: function Shape(x, y) { this.x= x; this.y= y; } Shape.prototype.toString= function() { return 'Shape at '+this.x+', '+this.y; }; function Circle(x, y, r) { Shape.call(this, x, y); // invoke the base class's constructor function to take co-ords this.r= r; } Circle.prototype= $.extend(true, {}, Shape.prototype); Circle.prototype.toString= function() { return 'Circular '+Shape.prototype.toString.call(this)+' with radius '+this.r; } var c = new Circle(1,2,3); alert(c); Is there a way to define the Shape's toString function inside it's constructor, or it does not make sense in this situation? A: Base on my understanding: * *When you move .toString() into the constructor then .toString() becomes an explicit member of your instance. hence any call to .toString() will fire that explicit member. Example: http://jsfiddle.net/paptamas/qDSkj/ * *But when you define that as a prototype, (in the absence of an explicit member called .toString()), any call to .toString() method will fire .toString() function that is defined for the type of calling object (Circle in your case). Example: http://jsfiddle.net/paptamas/cbnLB/ In other words, explicit members have priority over prototype definitions and when you say this.toString = function() ... you are defining that function as a member of your instance (as oppose to member of your type - which is in a way not optimized as well). Regards.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599751", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: What is the most efficient and concurrent way to implement a public API for an existing command-line program? An existing command-line program generates some output when called with some parameters, and then exits. I would like to modify this program to run on an event loop, and listen through a public API (could be in same machine). There seem to be multiple ways of implementing this: * *make the API external to the program and do system calls *turn the program into a library, and include the necessary functionality into the API itself *local sockets (like a TCP line server, for eg.) *HTTP server (producing JSON, XML, etc) Considering efficiency under load, concurrency and scalability, what would be the best approach? A: Api-design also depends on the clients, maybe you can give some more information: * *kind of client (real user, technical client polling things, etc.) *trust-level of clients (open to anyone, closed set of clients to be authenticated) Regarding scalability requirements: * *how many users *expected load (peak + average) Another idea could be a simple ssh-server so anyone can execute the script from outside: $ ssh user@yourhost.com yourCLIProgram.sh -param1 value1 -param2 value2 Then you don't need a overhead of event-listening loop. What does the program do in more detail?
{ "language": "en", "url": "https://stackoverflow.com/questions/7599753", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Threadreference.isalive = true but in the threads window its location is [In a sleep, wait or join] I have a simple function that launches a thread with a modal form and then waits to the form to be closed. private static bool GetSomeText() { Thread threadx = new Thread(GetSomeTextx); threadx.SetApartmentState(ApartmentState.STA); threadx.Start(); int i = 0; const int secs = 6000; while (threadx.IsAlive && i < secs) { Thread.Sleep(1000); i++; } if (i >= secs) //timeout { try { threadx.Abort(); } catch { } MessageBox.Show("Timeout etc."); return false; } else { return CheckText(Constants.inputedtext); } } private static void GetSomeTextx() { WindowWrapper window = new WindowWrapper(Fun.GetForegroundWindow()); FormGetSomeText epa = new FormGetSomeText { displaytext=Constants.displaytext}; epa.ShowDialog(window); Constants.inputedtext= epa.inputedtext; } The problem is that after closing the window the thread exits GetSomeTextx() but remains in the limbo... After that if i put a break in "while (threadx.IsAlive && i < secs)" i see that threadx.IsAlive its true and in the debug window the offending thread location is: [In a sleep, wait or join] and if i do a rightclick --> switch to thread it shows "No source Available" and clicking in Show Disassembly shows "No disassembly available." This code is almost a 1:1 copy (in the other one there are 2 textboxes instead of 1) of another case that i have to get values this way and it works correctly... What could it be? Postdata: Tried already adding Thread.CurrentThread.Abort at the end of GetSomeTextx without result... A: To wait for the thread to complete, call Join: private static bool GetSomeText() { Thread threadx = new Thread(GetSomeTextx); threadx.SetApartmentState(ApartmentState.STA); threadx.Start(); // Wait for thread to exit threadx.Join(); If you want to support reporting when there's a timeout, call the Join overload that lets you specify timeout value.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599754", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: django url tag: Caught NoReverseMatch while rendering #urls.py places_url_regex = ur''' ^places ( (?:/types/(?P<types>\d+(?:-\d+)*)) | (?:/cuisines/(?P<cuisines>\d+(?:-\d+)*)) | (?:/avg-bills/(?P<avg_bills>\d+(?:-\d+)*)) | (?:/cities/(?P<cities>\d+(?:-\d+)*)) | (?:/sectors/(?P<sectors>\d+(?:-\d+)*)) | (?:/streets/(?P<streets>\d+(?:-\d+)*)) | (?:/special/(?P<special>[cabins|calian|children\-animation|children\-room|parking|summer\-verandah|vip-room|wifi|smokers\-room]+)) | (?:/with/(?P<w>[discounts]+)) | (?:/page/(?P<page>\d+)) )* /$ ''' places_url_regex = re.sub( ur'\s+', '', places_url_regex ) urlpatterns = patterns( '', url( places_url_regex, 'app.places.views.places', name = 'url_places' ), ) #views.py def places(request, page = 1, special = '', types = '', cuisines = '', avg_bills = '', cities = '', sectors = '', streets = '', w = ''): ... if I manually open url /places/types/10/ in address bar or in template {% url url_places %} it's works, but in template {% url url_places types=10 %} raises exception: Caught NoReverseMatch while rendering: Reverse for 'url_places' with arguments '()' and keyword arguments '{'types': 10}' not found. Why and how to fix ? A: Have a read of how to handle URLs with Django https://docs.djangoproject.com/en/dev/topics/http/urls/#example
{ "language": "en", "url": "https://stackoverflow.com/questions/7599757", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CSS3D Transforms: Losing element interactivity I'm creating a 3D cube that can be rotated with keyboard controls. But after rotation, portions of each face lose interactivity (mouse events don't register on contained elements). Anyone know what might cause that issue? It's difficult to explain, so here's a link to a test site: http://joe-morgan.net/projects/matrix3d/ It only works in Safari and Chrome, of course. Joe Morgan A: Joe, What's happening is, you have two elements on the exact same z-coordinate. Namely, the <li class="cube active"> and the <section> faces within it. Here, we're not talking css's z-index, but css3's translated z-coordinate. When the browser encounters two planes occupying quite literally the same exact space, things can get messy. Since you don't want to have the li element shadowing your cube face's hover event, you should change your "active" classes CSS. On line 77 of main.js you set it with the code: vars.activeCube.css("-webkit-transform", action); A quick fix would be to create an "action2" variable that stores the same matrix3d as you do in main.js, but translated -1px in the z coordinate. Set the css with vars.activeCube.css("-webkit-transform", action2); and everything should work as expected. Let me know if this fixes your issue
{ "language": "en", "url": "https://stackoverflow.com/questions/7599758", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MySQL select all last added query Im trying to select all the items that are recently added. I have to find what is the last added exam (sometimes more that one as shown below) Here is an example of the DB. id name start_date end_date duration 4 Exam August 2011 24.8.2011 0000-00-00 20 3 Exam July 2011 28.7.2011 0000-00-00 20 5 Exam August 2011 24.8.2011 0000-00-00 20 6 Exam August 2011 24.8.2011 0000-00-00 20 25 Exam September 2011 26.9.2011 07.10.2011 20 26 Exam September 2011 26.9.2011 07.10.2011 20 27 Exam September 2011 26.9.2011 07.10.2011 20 And here is the query that im using, my question is is there a better way to do it? Some optimization? SELECT * FROM me_tests WHERE name = ( SELECT name FROM me_tests ORDER BY start_date DESC LIMIT 1 ) The second query will find the name of the last added (same as start date) one, will pass it to the first select and will select all the other tests based on the name. A: SELECT * FROM me_tests ORDER BY start_date DESC LIMIT 1 Or - SELECT * FROM me_tests WHERE start_date = (SELECT MAX(start_date) FROM me_tests); A: I would use SELECT * FROM me_tests ORDER BY start_date DESC LIMIT 1 ... except using * is bad, so you should name all the columns you want to retrieve. A: What if the last added items were added at the same time but have different names? In that case I would think you would want a query like this. SELECT * FROM me_tests WHERE start_date = (SELECT start_date FROM me_tests ORDER BY start_date DESC LIMIT 1)
{ "language": "en", "url": "https://stackoverflow.com/questions/7599760", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to use variable across contexts in rspec In below code every call to subscriber_with_99_users creates a new subscriber with 99 users, which I don't want. How can I fix this to only create the subscriber once and return it in all subsequent calls or is there a better way to do this. describe "#as_json" do context "in 'users' path for a subscriber with 99 users" do let(:presenter_options) { { path: 'users', page: 1, per_page: 10 } } let(:subscriber_with_99_users) { if (@subs_with_99_users) @subs_with_99_users else @subs_with_99_users = get_subscriber_with_many_users 99 end } subject { subscriber_presenter.as_json.fetch('users').length } context "and pagination with page size of 10" do {1 => 10, 10 => 9, 11 => 0, 100 => 0}.each do |page, count| context "for page #{page}" do let(:subscriber_presenter) { Fabricate(:subscriber_presenter, subscriber: subscriber_with_99_users, options: presenter_options.merge(page: page)) } it "returns #{count} users" do should == count end end end end end end A: If you're trying to do things across contexts you'll probably want to turn off transactional fixtures. This is easily done ActiveSupport::TestCase.use_transactional_fixtures = false Although it would probably be better if you could strategically set up your variables in a Before block: https://www.relishapp.com/rspec/rspec-core/v/2-13/docs/hooks/before-and-after-hooks!
{ "language": "en", "url": "https://stackoverflow.com/questions/7599763", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Scrollable div inside table cell using css I want to be able to set a max width on the div and have the overflow be handled with scroll-bars. This works in FF, but not in IE or chrome so well... the scrolling part seems to work OK but the width of the table doesn't adjust like it does in FF, the width is still accounting for the scrollable div in chrome and IE. FF the main table adjusts perfectly. I realize that you're not supposed to use a <div> inside of a <span> etc, just want ideas on how to accomplish this overflow... jsFiddle Here is my example: <div> <table style="width: 100%"> <tr> <td>foo</td> <td>bar</td> </tr> <tr> <td colspan="2" class="uiTest"> <span> <div class="uiTableContainer"> <table class="uiTable" cellspacing="0"> <tbody> <tr class="uiTableRow"> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td class="uiTableAction"> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td class="uiTableAction"> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td class="uiTableAction"> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td class="uiTableAction"> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td class="uiTableAction"> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td class="uiTableAction"> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> <td> foo </td> </tr> </tbody> </table> </div> </span> </td> </tr> <tr> <td>foo</td> <td>bar</td> </tr> </table> </div> And the css: .uiTable{ border: 1px solid red; width: 100%; } .uiTableContainer{ max-width: 200px; overflow: auto; } A: Is it necessary that you use "max-width" ? I am getting good results in IE when using "width" instead. Try: http://jsfiddle.net/NCB3a/ Tested in IE8 and FF6.0.2 Edit: Or to keep the max-width value, I guess this would also work: max-width: 200px !important; width:200px;
{ "language": "en", "url": "https://stackoverflow.com/questions/7599765", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Django - coercing to Unicode I am having a unicode problem and, as everytime I have something related I'm completely lost.. One of my Django template renders a TypeError : Exception Value: coercing to Unicode: need string or buffer, long found The line giving trouble is just a string ( which I want to use in a mysql query) : query = unicode('''(SELECT asset_name, asset_description, asset_id, etat_id, etat_name FROM Asset LEFT OUTER JOIN Etat ON etat_id_asset=asset_id WHERE asset_id_proj='''+proj+''' AND asset_id_type='''+t.type_id+''' ORDER BY asset_name, asset_description) UNION (SELECT asset_name, asset_description, asset_id, 'NULL', 'NULL' FROM Asset WHERE asset_id_proj='''+proj+''' AND asset_id_type='''+t.type_id+''' AND asset_id IN (SELECT etat_id_asset FROM Etat)); ''') What can be wrong here ? A: I know you figured out a better way to accomplish, but to answer the original question, in case you get that error again somewhere else in the project: t.type_id appears to be a long integer. You cannot mix integers in strings unless you convert to string, this is really simple: myString = 'some string with type id ' + str(t.type_id) + ', and whatever else you want in the string.'
{ "language": "en", "url": "https://stackoverflow.com/questions/7599769", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Upgrading Team Foundation Services (TFS) Currently our company is using Team Foundation Server 2010, and we have quite a bit of source code in our repositories. Although I am not a big fan of TFS, we are still continuing to use it. I do have hope for TFS 11, but I wanted to know: * *what needs to be done to make the move from our current setup to the new TFS 11. *Does it require us to reestablish our source code repository, or can we simply point the new TFS at our legacy repository. *What are, if any, the best practices on migrating source code repositories. A: 3) What are, if any, the best practices on migrating source code repositories. * *Wait for the new version to reach a beta state (if you are an early adopter) or (for everyone else) it is released. TFS11 is currently a "developer preview", only in the most extreme of cases (eg. you are the TFS team and "dog-fooding") would you adopt software as such an early state for a production system. A: unless you have found different information or posts on this, there is no reason, IMHO, to assume that anything will be different from usual migration/upgrade of TFS 2008 setup into a TFS 2010. see this one: Upgrading from TFS 2005/2008 to TFS 2010 and this step by step guide: Rules To Better TFS 2010 Migration A: There will be an in-place upgrade wizard going from TFS 2010 to TFS 2012 & TFS 2013. It is also an upgrade going from 2012 RTM to Update 1 and Update 2, and beyond. More below** Here's how it will work: * *Go into Add/Remove programs *Uninstall TFS 2010 - not required in 2012 RTM and beyond *Run the install for TFS 2012 *When the wizard launcher comes up, choose upgrade. *Select your database (Tfs_Configuration) in the db picker, accept all the defaults, next, next. *You're done. //Build conference CTP is out there so you can play with it. Since you're looking at 2012 TFS product, make sure you checkout the new TFS in the cloud. You can try it out @ http://tfs.visualstudio.com/ for free without deploying your own. EDIT: The team is working on a blog with step by step walkthrough here: http://elhajj.wordpress.com/ It's also included here: https://www.smashwords.com/books/view/181289 Note that when you go from 2012 RC to RTM (and beyond), the uninstall step will not be required. You just run the setup of the new version. EDIT: give it a shot. http://www.microsoft.com/visualstudio/11/en-us/downloads#tfs-group Also note the addition of the TFS Express sku which is a free version of TFS which uses SQL Express. 2013 preview is available. Same story. Here: http://www.microsoft.com/visualstudio/eng/2013-downloads ** TFS has gone to a cloud cadence where the service (tfs.visualstudio.com) is updated every 3 weeks. Those rollup into CTPs for shipping quarterly updates. So going to a quarterly update on-premise is an upgrade. Remember that it contains rolled up features from months of product development so you are doing a forward only upgrade of the DBs (backup and restore is going back). So, it's not a trivial patch - it's an event but you get the value and are closer to the cloud feature set.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599771", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Singletons, Enums and anonymous inner classes As you may know, some people are declaring singletons with an Enum of 1 instance, because the JVM guarantees that there will always be a single instance with no concurrency problems to handle... Thus what about an Enum with multiple instances? Can we say something like an Enum is a kind of ordered set of singletons sharing a common interface? Why? public enum EnumPriceType { WITH_TAXES { @Override public float getPrice(float input) { return input*1.20f; } public String getFormattedPrice(float input) { return input*1.20f + " €"; } }, WITHOUT_TAXES { @Override public float getPrice(float input) { return input; } }, ; public abstract float getPrice(float input); public static void main(String[] args) { WITH_TAXES.getFormattedPrice(33f); } } In this code why this doesn't work: WITH_TAXES.getFormattedPrice(33f); What is the interest of declaring a public method if it can't be called without passing through the common interface? I guess this is why i don't see any syntax to be able to declare an interface just for one of the instances of an Enum. Edit: It seems that enum instances are a special kind of anonymous classes. Thus i understand why you can't call that method. My question is kinda related to: why can't an anonymous class implement an interface (in addition to the interface it may already implement!) I totally understand why we CANT do that: Vehicle veh = new Vehicle() { public String getName() { return "toto"; } }; veh.getName(); (getName here is not an override) Why i don't understand is why we can't do that with anonymous classes: Runnable veh = new Vehicle() implements Runnable { @Override public void run() { System.out.println("i run!"); } }; veh.run(); Or something that would result in the same thing. Think about it: if you do not use anonymous classes you can absolutely extend the Vehicle class and then make that subclass implement any other interfaces you want... I'm pretty sure that if it was possible we would be able to call WITH_TAXES.getFormattedPrice(33f) in a typesafe way, since WITH_TAXES would not be a real EnumPriceType but it would but a subclass of EnumPriceType, with its own interface, and by calling WITH_TAXES.getFormattedPrice(33f) with a hardcoded WITH_TAXES, you know at compile that which EnumPriceType child you are calling. So my question is: are there any reasons why this is not possible? Or it just haven't be done yet? A: Add public String getFormattedPrice(float input) { return input + " €"; } outside the overrides as the default implementation. (Next to the declaration of getPrice.) And you are good to go. You can also have enums implement interfaces, to define what everybody needs to implement. A: Your enum is equivalent to the following normal class (in fact, that's pretty much what the compiler turns it into): public abstract class EnumPriceType { public static final EnumPriceType WITH_TAXES = new EnumPriceType() { //getPrice() {...} //getFormattedPrice() {...} }; public static final EnumPriceType WITHOUT_TAXES = new EnumPriceType() { //getPrice() {...} }; public abstract float getPrice(float input); public static void main(String[] args) { WITH_TAXES.getFormattedPrice(33f); } } The getFormattedPrice() method is unavailable on the abstract type, and therefore can't be called from the main method. Consider what would happen if the main method is rewritten to use a local variable: public static void main(String[] args) { EnumPriceType foo = EnumPriceType.WITH_TAXES; foo.getFormattedPrice(33f); } This doesn't compile because getFormattedPrice() is not available on the base class. Since the WITH_TAXES instance is an anonymous subclass of EnumPriceType, there's no way you can define the local variable to a type where the getFormattedPrice() method is visible. As a meta observation, this is a key difference between strongly typed languages such as Java and "duck typed" languages such as Ruby. Ruby will happily invoke the getFormattedPrice() method if happens to be there, regardless of what type of object is held in the foo variable. As another meta observation, it doesn't make much sense for different constants of the same enum to have different sets methods. If you can't put everything you need as abstract (or concrete) methods on the base enum type, you're probably using the wrong tool to solve the problem. A: Thus what about an Enum with multiple instances? There is no such thing, and your example doesn't demonstrate it. You have an Enum with multiple values. They are all singletons.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599776", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: How to select every n-th element from a list Possible Duplicate: How to get every Nth element of an infinite list in Haskell? Simple task - we have a list and want to leave only each nth element in that list. What is the most idiomatic way to do it in haskell? off the top of my head it is something like: dr n [] = [] dr n (x : xs) = x : (dr n $ drop n xs) but I have a strong feeling that I'm overcomplicating the problem. A: Lots of ways to shave this yak! Here's yet another: import Data.List.Split -- from the "split" package on Hackage dr n = map head . chunk n A: My variant would be: each :: Int -> [a] -> [a] each n = map head . takeWhile (not . null) . iterate (drop n) Fast and plays well with laziness. A: Your solution is fine, but here are three other solutions using functions from Haskell's base library. dr1 m = concatMap (take 1) . iterate (drop m) Of coarse, this will never terminate (because iterate never terminates). So perhaps a better solution would be to use unfoldr: {-# LANGUAGE TupleSections #-} import Data.Maybe dr2 m = unfoldr ((\x-> fmap (,drop m x) (listToMaybe x))) The function you pass to an unfold can get a bit ugly if you don't know GHC extensions and concepts such as functors, here's that solution again without the fancy foot-work (untested): dr2 m = unfoldr ((\x -> case listToMaybe x of Nothing -> Nothing Just i -> Just (i,drop m x))) If you don't like unfolds then consider a zip and a filter: dr3 m = map snd . filter ((== 1) . fst) . zip (cycle [1..m]) Review Understand all these solutions are slightly different. Learning why will make you a better Haskell progammer. dr1 uses iterate and will thus never terminate (perhaps this is ok for infinite lists, but probably not a good overall solution): > dr1 99 [1..400] [1,100,199,298,397^CInterrupted. The dr2 solution will show every mth value by skipping values in the unfold. The unfold passes both the value to be used for the next unfolding and the result of the current unfolding in a single tuple. > dr2 99 [1..400] [1,100,199,298,397] The dr3 solution is slightly longer but probably easier for a beginner to understand. First you tag every element in the list with a cycle of [1..n, 1..n, 1..n ...]. Second, you select only the numbers tagged with a 1, effectively skipping n-1 of the elements. Third you remove the tags. > dr3 99 [1..400] [1,100,199,298,397] A: Try this: getEach :: Int -> [a] -> [a] getEach _ [] = [] getEach n list | n < 1 = [] | otherwise = foldr (\i acc -> list !! (i - 1):acc) [] [n, (2 * n)..(length list)] Then in GHC: *Main> getEach 2 [1..10] [10,8,6,4,2]
{ "language": "en", "url": "https://stackoverflow.com/questions/7599777", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Understanding functions hooks This is my first post in stackoverflow, eventhough I'v been reading here for more than a year. I would like to ask some questions about function hooking, and would be really glad to have some answers. Say I created an executable and I would like to hide it in the list of the task manager so it would be invisible. I could hook the function in the task manager that is in charge of displaying all the running processes. I know that in order to do such a thing I would need to start by injecting my own DLL to taskmgr.exe, and taking over the required function using one of many techniques. My question are the following: 1.How could I get the name of my requested function ? Would I disassemble taskmgr.exe and search there ? I would like to hear a little more about techniques from this kind. 2.Say I know my function name, how could I get its run time address in order to invoke my hook ? Is the address I will find while disassembling the exe the same as the run time address ? If not, how would I find it ? 3.A general question about hooking functions, Say I hook windows messagebox function, and would override it so that each message that should be printed would print "ABCDEF", Would that affect each process that uses the messagebox function or only my process ? Would love to get an explanation about this issue. Thanks alot in advance :) Michael.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599782", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Cucumber: web_steps.rb I'm wasting my time here and I can't seem to figure this out.. I have used Cucumber in Rails applications before, and if I'm not mistaken, it generates the features/step_definitions/web_steps.rb file when you run rails g cucumber:install. Right? I looked this up in a book I was using a while ago to learn Rails and it says so there aswell: It nevertheless passes because of the features/step_definitions/web_steps.rb file, which was generated when you ran the rails generate cucumber:install command. However, when I run it in this application I'm trying to start working on, it does not generate it.. $ rails g cucumber:install create config/cucumber.yml create script/cucumber chmod script/cucumber create features/step_definitions create features/support create features/support/env.rb exist lib/tasks create lib/tasks/cucumber.rake force config/database.yml No web_steps.rb to be found. Am I losing my mind here? Thanks. A: Which version of cucumber are you using? if it is a recent version, see https://github.com/cucumber/cucumber-rails/blob/f027440965b96b780e84e50dd47203a2838e8d7d/History.md
{ "language": "en", "url": "https://stackoverflow.com/questions/7599788", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: BlackBerry screen shot utility - from a desktop computer I am looking for a screen shot tool that I can use to capture screens from my BlackBerry Tourch 9850. I have tried using the included JavaLoader utility with my SDK but I receive "Retrieving screen <active> data ... Error: buffer too small" errors. I have also tried using the BBScreenShooter v1.67 (I think this is the latest version) but it fails to capture the screen, then crashes. I need the tool to create a user manual for some software we're developing for BlackBerrys and, as they say, "a picture is worth a thousand words." If nothing else, perhaps someone knows how to address the small buffer problem with JavaLoader? A: With the help of Mark Sohm (thanks Mark ... your help is very much appreicated) the solution was discovered: You have to use the JavaLoader from the v7.0 SDK on devices that have the higher screen resolutions ... the Tourch 9850 is 800 x 480. Versions 6 and lower do not have an implementation that will support the larger buffer required to grab the addition bytes - makes sense. Although I have not tested it yet it's certainly possible that the BBScreenShooter would work also knowing this .... BBScreenShooter uses JavaLoader to handle the "heavy lifting" with the handset. A: Try this way: * *Create an application that runs on device startup and listens for GlobalEvents (via GlobalEventListener implementation) *Run this application in JDE or Eclipse and monitor what global events are fired when you press convenience keys on your blackberry device. Write event guids down and find out a guid that corresponds to a convenience key, when it is pressed. *Modify the application created at step 1 to use Display class and invoke screenshot() method of this class when a convenience key is pressed. *As screenshot has been created save it to the device filesystem via BlackBerry FileConnections API. After that you can copy these pictures to your desktop computer when device is connected via usb-cable. That's it. This application will allow you to solve your task. And may become an additional product for your company, if you add some settings to setup convenience key(s) and path to save created screenshots on device memory/media card. A: I'm not sure how to actually fix your problem but alternatively you could just run the application in the device simulator and get the screenshots from there. Run the simulator and go to "Edit" > "Save LCD Snapshot".
{ "language": "en", "url": "https://stackoverflow.com/questions/7599797", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Number of parallel instances of my process (app) Is there some portable way to check the number of parallel instances of my app? I have a c++ app (win32) where I need to know how often it was started. The problem is that several user can start it parallel (terminal server), so i cannot search the "running process" list because I'm not able to access the the list of other users. I tried it with Semaphore (boost & win32 CreateSemaphore) It worked, but now I have the problem if the app crashes (Assertion or just kill the process) the counter is not changed. (rebooting helps) Also manually removing/resetting the semaphore counter in my code is not possible because I don't know if somebody else is running my application. A: Edited to add: Suppose you have a license that lets you run 20 full-functionality copies of your program. Then you could have 20 mutexes, named MyProgMutex1 through MyProgMutex20. At startup, your program can loop through the mutexes. If it finds a spare mutex that it can take, it stops looping and enters full-functionality mode. If it loops through all the mutexes without being able to take any of them, then it enters reduced-functionality mode. Original answer: I assume you want to make sure that only one copy of your process runs at once. (Or, for Terminal Server, one copy of your process per login session). Your named semaphore solution is close. The right way to do this is a named mutex. Use CreateMutex to make the mutex, then call WaitForSingleObject with a timeout of zero. If WaitForSingleObject returns WAIT_TIMEOUT, another copy of the process is running. If it returns WAIT_OBJECT_0 or WAIT_ABANDONED, then you are the only copy of the process. You need to keep the mutex handle open while your program runs - either call CloseHandle when your process is about to exit, or just deliberately leak the handle and rely on Window's built-in cleanup to release the handle for you when your process exits. Windows will automatically increment the mutex's counter when your process exits. A: The only thing I can think of that mitigates the problem of crashed processes is a kind of “dead man’s switch”: each process needs to update its status in regular intervals. If a process fails to do this, it’s automatically discarded from the list of active processes. This technique requires that one of the processes acts as a server which keeps tab of whether other processes have updated recently. If the server dies, then another process can take over. This, in turn, requires that each process tests whether there still is a server alive. Alternatively, each process can be its own server and keep track locally. This may be easier to implement than server-switching. A: You can broadcast message and other instances of your application should send some response. You count responses - you get number of instances.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599801", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: PHP If folder exists do a loop for each subfolder I am trying to get my code to work. I basically check that if a folder exists, and any sub folder exists within that directory called 3 or more (3,4,5) then do a loop, otherwise nothing. // the folder path $folderPath="".cdnurl."assets/".pid.""; // looks like site.com/assets/342/ // is there a sub folder called 3 or more, 3,4,5 and loop from 3 // site.com/assets/342/3 // site.com/assets/342/4 // etc, we only loop if 3 exists other wise nothing $folderSubNumber =>3; while(file_exists($folderPath.$folderSubNumber)) { echo '<li><img src="assets/pid/'.folderSubNumber.''; } else { // nothing echo ""; } A: It looks like what you have should do it. Just change that => to a simple =, and don't forget to increment: while (file_exists($folderPath.$folderSubNumber)) { echo '...'; $folderSubNumber += 1; } (Also, the else part isn't allowed. But you don't need it here, so nothing lost.) A: A simple method: $subdirs = glob(cdnurl . "assets/" . pid . "/*", GLOB_ONLYDIR); that'll return all subdirectories in the specified directory. Ref: http://php.net/glob A: Prepare for some constructive criticism, please. There's a lot wrong with this code. First I'll add comments to explain some of the mistakes as well as some of the pointless things that do nothing. $folderPath="".cdnurl."assets/".pid.""; // 1. Single-quotes will perform slightly better. // 2. There is no need for the first "". or the final ."" - they do nothing. // 3. Ideal: $folderPath = cdnurl.'assets/'.pid; // 4. This assumes that cdnurl and pid are constants declared with the define() command. If they are not constants, you need dollar-signs, which would make it: // $folderPath = $cdnurl.'assets/'.$pid; $folderSubNumber => 3; // You cannot put a "more than X" or "less than X" in a variable. The => is used in foreach() loops for a completely different purpose, and when declaring values in an array only when the array is originally declared. (In other words; in this case, this does nothing.) // Indentation really does matter. This should be indented the same as the code above. while(file_exists($folderPath.$folderSubNumber)) { // 1. $folderSubNumber never changes and so this while-loop always asks the exact same question. // 2. You don't have a directory separator "/", so this will append $folderSubNumber straight to pid, above. echo '<li><img src="assets/pid/'.folderSubNumber.''; // 1. folderSubNumber needs a dollar-sign because it's a variable. If it is not defined as a constant, it will simply be the literal string "folderSubNumber". // 2. The appended .'' does nothing and shouldn't be there. // 3. You are neither closing the <img> tag, nor the <li> tag, nor in fact the src-attribute. // 4. Ideal: echo '<li><img src="assets/pid/'.$folderSubNumber.'" /></li>'; } else { // 1. There is no "else" in while. // 2. You don't need an "else" if the intention is to do nothing. echo ""; // This is 100% pointless, it does nothing. } What you then need, is to increment $foldeSubNumber after you've tried it in the while-loop (see the answer by 'sdleihssirhc'). But also note that you probably need the directory separator between $folderPath and $folderSubNumber. That would be: $folderPath.'/'.$folderSubNumber Good luck! A: // Build folder path $folder_path = cdnurl . 'assets/' . $pid . '/'; // Loop from 3 to 5 for ($i = 3; i <= 5; $i++) { // Checking for a valid sub-directory // Will check sub-directory e.g.: site.com/assets/342/3/ if ( is_dir($folder_path . $i . '/') ) { // Sub-directory exists echo $folder_path . $i; } else { // No Sub-directory, break out of for loop // This is will stop PHP for looking for sub-directory 4 or 5 break; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7599802", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: BigInteger to String according to ASCII Is there a way to convert a series of integers to a String according to the ASCII table. I want to take the ASCII value of a String and convert it back to a String. For example, 97098097=> "aba" I really need an effective way of taking an integer and converting it to a String according to its ASCII value. This method must also take into account the fact that there is no zero in front of the '9' when the String "aba" has an ASCII value of 97098097 as 'a' has an ASCII value of 097 and a String "dee" has one of 100101101. This means that not every number will have an ASCII value that has a number of digits that is a multiple of three. If you have any misunderstandings of what I'm trying to do please let me know. A: No lookup table required. while (string.length() % 3 != 0) { string = '0' + string; } String result = ""; for (int i = 0; i < string.length(); i += 3) { result += (char)(Integer.parseInt(string.substring(i, i + 3))); } A: First, I would create some sort of lookup table in your code with all the ascii values and their String equivalent. Then take the big int and convert it to a String. Then do the mod of 3 with the length of your bigint string to determine if you need to add 1, 2, or no 0's to the front of it. Then just grab every 3 integers from the front of the number, compare it to the lookup table, and append the corresponding value to your result string. Example: Given 97098097 You would convert it to: "97098097" Then you do a mod with 3 resulting in a value of 1, so 1 zero needs to be added. Append 1 zero: "097098097" Then grab every 3 from the front and compare to look up table: 097 -> a, so result += "a" 098 -> b, so result += "b" 097 -> a, so result += "a" You end with result being "aba"
{ "language": "en", "url": "https://stackoverflow.com/questions/7599806", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why aren't recursive calls automagically replaced by recur? In the following (Clojure) SO question: my own interpose function as an exercise The accepted answers says this: Replace your recursive call with a call to recur because as written it will hit a stack overflow (defn foo [stuff] (dostuff ... ) (foo (rest stuff))) becomes: (defn foo [stuff] (dostuff ...) (recur (rest stuff))) to avoid blowing the stack. It may be a silly question but I'm wondering why the recursive call to foo isn't automatically replaced by recur? Also, I took another SO example and wrote this ( without using cond on purpose, just to try things out): (defn is-member [elem ilist] (if (empty? ilist) false (if (= elem (first ilist)) true (is-member elem (rest ilist))))) And I was wondering if I should replace the call to is-member with recur (which also seems to work) or not. Are there cases where you do recurse and specifically should not use recur? A: There's pretty much never a reason not to use recur if you have a tail-recursive method, although unless you're in a performance-sensitive area of code it just won't make any difference. I think the basic argument is that having recur be explicit makes it very clear whether a function is tail-recursive or not; all tail-recursive functions use recur, and all functions that recur are tail-recursive (the compiler will complain if you try to use recur from a non-tail-position.) So it's a bit of an aesthetic decision. recur also helps distinguish Clojure from languages which will do TCO on all tail calls, like Scheme; Clojure can't do that effectively because its functions are compiled as Java functions and the JVM doesn't support it. By making recur a special case, there's hopefully no inflated expectations. I don't think there would be any technical reason why the compiler couldn't insert recur for you, if it were designed that way, but maybe someone will correct me. A: I asked Rich Hickey that and his reasoning was basically (and I paraphrase) "make the special cases look special" he did not see the value in papering over a special case most of the time and leaving people to wonder why if blows the stack later when something changes and the compiler can't guarantee the optimization. Untimely it was just one of the design decisions made to try and keep the language simple A: I was wondering if I should replace the call to is-member with recur In general, as mquander says, there is no reason to not use recur whenever you can. With small inputs (a few dozen to a few hundred elements) they are the same, but the version without recur will blow up on large inputs (a few thousand elements). Explicit recursion (i.e. without 'recur') is good for many things, but iterating through long sequences is not one of them. Are there cases where you specifically should not use recur? Only when you can't use it, which is when * *it is not tail recursive - i.e. it wants to do something with the return value. *the recursion is to a different function. Some examples: (defn foo [coll] (when coll (println (first coll)) (recur (next coll))) ;; OK: Tail recursive (defn fie [coll] (when coll (cons (first coll) (fie (next coll))))) ;; Can't use recur: Not tail recursive. (defn fum ([coll] (fum coll [])) ;; Can't use recur: Different function. ([coll acc] (if (empty? coll) acc (recur (next coll) ;; OK: Tail recursive (conj acc (first coll)))))) As to why recur isn't inserted automatically when appropriate: I don't know, but at least one positive side-effect is to make actual function calls visually distinct from the non-calls (i.e. recur). Since this can be the difference between "works" and "blows up with StackOverflowError", I think it's a fair design choice to make it explicit - visible in the code - rather than implicit, where you would have to start second-guessing the compiler when it doesn't work as expected.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599810", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to use a case statement to determine which field to left join on I have a query that needs to be able to left join a field at the right place given the condition that the field is equal to a variable. Something like: CASE WHEN challenges.userID = $var LEFT JOIN challengesRead ON challenges.userID = challengesRead.userID CASE WHEN challenges.opponentID = $var LEFT JOIN challengesRead ON challenges.opponentID = challengesRead.userID I think I am on the right track but I'm not sure how to put the query together. Thanks A: Something like this may work LEFT JOIN challengesRead ON challenges.userID = CASE WHEN challenges.userID = $var THEN challengesRead.userID WHEN challenges.opponentID = $var THEN challenges.opponen END A: It seems you want this: LEFT JOIN challengesRead ON CASE WHEN challenges.userID = $var THEN challenges.userID WHEN challenges.opponentID = $var THEN challenges.opponentID END = challengesRead.userID which can be simplified to: LEFT JOIN challengesRead ON $var = challengesRead.userID AND ( challenges.userID = $var OR challenges.opponentID = $var )
{ "language": "en", "url": "https://stackoverflow.com/questions/7599811", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Rails Nested Forms With Images So I'm building a nested form with an Campaigns model and a Sites model where Campaigns has_many Sites. In my Campaigns form I have: <%= f.fields_for :sites do |builder| %> <%= render "site_fields", :f => builder %> <% end %> And then in the _site_fields.html.erb I have: <div class="field"> <%= f.label :title %><br /> <%= f.text_field :title %> </div> <%= f.label "Image"%><br> <%= f.file_field :image %> <div class="field"> <%= f.label :url %><br> <%= f.text_field :url %> </div> This all seems to work (shockingly) but I would like to have a preview of the image already uploaded for a particular site in the form. So where I have f.file_field :image I would also like to be able to show a preview of that image. The problem is that I don't seem to be able to access the current site being rendered because I'm using f.fields_for. Any suggestions? I'm sure I'm missing something relatively simple. Thanks in advance! A: From the form helper object (in your case builder and f) you should be able to access the model object and the url your looking for like this: <%= image_tag f.object.image_url(:thumb) %> The image in image_url depends on how you named the attribute, but for your sample this should be correct. A: You may want to investigate the paperclip gem: https://github.com/thoughtbot/paperclip It lets you do this to show a thumbnail of the existing picture. <div class="field"> <% if @thing.logo? %> <%= image_tag @thing.logo(:thumb) %><br/> Change <% end %> <%= f.label :logo %> <%= f.file_field :logo %> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/7599812", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Creating tabs using Fragments now that TabActivity is deprecated I am creating an application which has five tabs at the bottom of the screen, each of which opens a different Activity. My Tab Activity extends TabActivity which I have just read is deprecated and I should use Fragments instead. How do I change my app to use Fragments instead? I have read the information on android.developer.com but I still have no idea how to do this. A: You will need to use the android compatibility library to use fragments. It can be found as a jar file in your android sdk folder. There are many tutorials out there for fragments. There is a project named ActionBarSherlock which demos all the capability of the compatibility library. Source code is also available on github. The link is on there site. This is another tutorial http://mobile.tutsplus.com/tutorials/android/android-compatibility-working-with-fragments/
{ "language": "en", "url": "https://stackoverflow.com/questions/7599816", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: Two divs: one fixed, other stretched I am trying to accomplish this: But I am having trouble getting the two middle divs to play nice. If I set them both to a relative number (30% and 70%) it "works" but the left div changes size as the user changes the browser-windows width. #floatitleft{width:30%; float:left;} #floatitright{width:70%; float:left;} What I want is, as the picture illustrates #floatitleft{width:300px; float:left;} #floatitright{width:100%; float:left;} But this causes "floatitright" to end up beneath floatitleft. And if I set it to 70% it does end up to the right of "floatitleft" but as I change the browser size a little it ends up underneath yet again. What to do? UPDATE: Eventually I ended up with: #topper{ height:100px; width:100%; background-color:blue; } #wrapperz{ height:inherit; width:100%; } #wrapperz p{margin:0 0 0 0px; padding:10px 10px 0px 10px; color:#0F0F0F;} #wrapperz #floatitleft{ width:300px; float:left; } #wrapperz #floatitright{ margin-left: 300px; min-width:300px; } #bottommer{ height:100px; width:100%; background-color:red; } Which would be used as: <div id="topper"> test </div> <div id="wrapperz"> <div id="floatitleft"> <p> Stuff </p> </div> <div id="floatitright"> <p> Stuff </p> </div> <div style="clear: both;"/> </div> <!-- Close Wrapper --> <div id="bottommer"> test </div> Note that this isn't proper HTML but it just serves as the solution to my example. Also, the "div style="clear: both" is escpecially important if you try this because not using that cuases the footer to mess up as the wrapper doesn't properly stretch vertically. But Mark has provided a what I believe to be better/cleaner alternative below. A: Here, I made a duplicate of your picture: jsbin.com/ipexep/3 (click "edit in jsbin" at the top-right to view and edit the source) I for the height of the top and bottom sections, I took the height for them that you put in the picture. Note: I did it by making every section absolutely positioned and setting their top, bottom, left, or right attributes accordingly. Also, notice that my method will match every screen size. I have streched it in every area you didn't specify a dimension. (except the header and footer needed a height dimension so I guessed since you didn't specify) A: Wouldn't this work as intended? #floatitleft{ width:300px; float:left; } #floatitright{ margin-left: 300px; } A: You can accomplish that very easy using grid system. http://960.gs/ Take a look, you can choose a 12 or 16 , 24 or even more columns. You just use classes like "grid_4", "grid_8" depending on the width you need.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599821", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Redirecting back to my custom tab page's iframe app after auth I've got an app embedded in an iframe in a 520px wide custom tab page of my fanpage. When it auths a user, it always takes them to the full-width canvas page for the app rather than the custom tab page. How can I resolve this please? It's driving me nuts! Pete A: Try setting your redirect_uri to your Page Tab url.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599823", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery autocomplete 'length' is null or not an object I'm building an ASP.NET MVC 3 application and I'm trying to properly incorporate the jQuery autocompletex into one of my pages so a user can type in an ingredient name or choose one from the dropdown. I get this error: Microsoft JScript runtime error: 'length' is null or not an object and my view code looks like this: $("#ingredientid").autocomplete({ source: function (request, response) { $.ajax({ url: '@Url.Action("AvailableIngredients", "Recipe")', type: "POST", dataType: "json", data: { query: request.term }, success: function (data) { response($.map(data, function (item) { return { label: item, value: item }; })) } }) }, minLength: 1 }); Things seem to work fine in Firefox, but IE 8 is the standard browser used in-house. Additional: I'm returning the data - List<string> like so: public JsonResult AvailableIngredients() { ... return Json(allIngredients, JsonRequestBehavior.AllowGet); } Ideas? A: make sure to declare your meta tag for content type before your javascript include files. looks like that was a problem for someone else in this question.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599824", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Web Site version control with Team Foundation System We have a Web Site Project, (not a Web Application), and we need a way to track version changes on web pages. The .dlls are no problem, the problem is keeping track of the current version of a web page in the production server. Is there a way to do this with TFS? I was thinking maybe a plugin the automatically placed some commented code physically on each modified web page indicating a version number and last modified date, for example. But I am really at a lost here. I know one alternative would be to change the project type to Web Application, however, it's a big app and that would be a big project involving a lot of testing. EDIT: What I ultimately need: I need a way to identify the version of a web page on the production server. Like I said this is simple with dlls because they carry their version, but web pages don't have any versioning on the file itself. So that we can check the production server, look at a file and know which version it is. A: I have a blog post explaining how this can be done (with a link to a TFS 2010 version). At the core it involves creating a version.txt file with the build number in it and making this information visible on the site. If you want to hardcode this into every page, you could tweak the process to embed that version.txt in the HTML of each and every page isntead. A: One of my co-workers solved this problem by building a Visual Studio Addin which shows all the changed web page files and gives you the option to set the next version or define one yourself and write it to the file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599825", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Issue with asp.net validation control with IE? I do have a strange problem here with asp.net required field validation controls.To my understanding validator controls render client-side script for IE users so no postback occurs in case there's a problem with data entry. So when i was running my web app on my local machine which has IE8 its working fine which has windows XP on it.But when i deploy it on IIS 6 in WS2003 it some how bypasses the validators and makes a post back to the server.Does it have some thing to do with the IE or IIS or ASP.net version ???? A: Go into IIS, and under the ASP.NET tab select the latest ASP.NET version available in the list.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599829", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: showing part of xml response in different DIV tags I have a AJAX response which looks like this <XML> <request> <!-- some xml data related to request --> </request> <response> <!-- some xml data related to response --> </response> </XML> My requirement is to display whole xml under node in a DIV with id=requestDIV and display xml under response in another DIV say id=responseDIV. I am able to get the XML and display XML as it is using this code success: function(xml, status, xhr){ alert(xhr.responseText); My question is how do you select part of the xml using JQUERY? This is the HTML code <div id="requestDIV"> <textarea id="requestArea" rows="10" cols="50"></textarea> </div> <div id="responseDIV"> <textarea id="responseArea" rows="10" cols="50"></textarea> </div> A: Well, since a simple google search answers your question, let me hit you up with a link :) http://think2loud.com/224-reading-xml-with-jquery/ All you need is in that tutorial, better explained than i could. A: You would want to do something like ... $("#requestArea").val($(xml).find("request").text()); $("#responseArea").val($(xml).find("response").text()); For your reading pleasure http://think2loud.com/224-reading-xml-with-jquery/ A: As per Sam's idea I resolved the issue by using the responseText and searching for the tag and retrieving the innerHTML like this success: function(xml, status, xhr){ $("#requestArea").val($(xhr.responseText).find("request").html()); $("#responseArea").val($(xhr.responseText).find("response").html()); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7599831", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Strange results using android PHP API Library Using a PHP implementation of the java android market API I'm attempting to display the top 10 most popular applications. Using the code below: <?php include("local.php"); include("../proto/protocolbuffers.inc.php"); include("../proto/market.proto.php"); include("../Market/MarketSession.php"); $session = new MarketSession(); $session->login(GOOGLE_EMAIL, GOOGLE_PASSWD); $session->setAndroidId(ANDROID_DEVICEID); $ar = new AppsRequest(); $ar->setOrderType(AppsRequest_OrderType::POPULAR); $ar->setStartIndex(0); $ar->setEntriesCount(10); //free or paid //$ar->setViewType(AppsRequest_ViewType::ALL); //arcade etc //$ar->setCategoryId("ARCADE"); $reqGroup = new Request_RequestGroup(); $reqGroup->setAppsRequest($ar); $response = $session->execute($reqGroup); $groups = $response->getResponsegroupArray(); foreach ($groups as $rg) { $appsResponse = $rg->getAppsResponse(); $apps = $appsResponse->getAppArray(); foreach ($apps as $app) { echo $app->getTitle()."<br/>"; } } But the results I'm getting aren't exactly what I expected: Brightest Flashlight Freeâ„¢ LauncherPro Seesmic (Facebook, Twitter) Android Assistant(18 features) Pho.to Lab US Yellow Pages Sudoku Free Color Flashlight ElectroDroid Scanner Radio I expected the list of top 10 apps to contain Gmail, Facebook, Youtube etc Anyone know why this could be happening? Any alternative APIs we could use? Any other way we can acheive this?
{ "language": "en", "url": "https://stackoverflow.com/questions/7599841", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Connect to remote MySQL DB (Linux) from Windows using MySQL Workbench. Remote DB Connection requires local Socket The Linux Server only allows connection over it's local socket. --socket=/tmp/mysql5.sock I want to connect to the Database using MySQL Workbench, but don't know how to specify the socket path there. Using the Standard TCP/IP over SSH connection I'm providing the SSH connection parameters, Databasename, username, etc. Any help is greatly appreciated. A: Try setting up an SSH tunnel to the machine: http://realprogrammers.com/how_to/set_up_an_ssh_tunnel_with_putty.html PuTTY is what I use on Windows when I need to SSH anywhere. The instructions are fairly thorough.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599849", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: mozilla border gradient equivalent I made this idea of mine to work in Chrome but still failed to do so in Firefox. Here is the concept that works in Chrome: <ul> <li>test</li> <li>test</li> <li>test</li> <li>test</li> <li>test</li> </ul> ul{-webkit-border-image: -webkit-gradient(linear, left top, left bottom, from(#FF9999), color-stop(100%, #4AC0F2)) 0 100% 0 0/0 5px 0 0 stretch;} JSFIDDLE I tried to do as it follows to make it cool with Firefox but I get horizontal instead of vertical gradient. border-right: 5px solid; -moz-border-right-colors: #71637D #FF9999; Thank you A: -moz-border-bottom-colors: #555 #666 #777 #888 #999 #aaa #bbb #ccc; -moz-border-top-colors: #555 #666 #777 #888 #999 #aaa #bbb #ccc; -moz-border-left-colors: #555 #666 #777 #888 #999 #aaa #bbb #ccc; -moz-border-right-colors: #555 #666 #777 #888 #999 #aaa #bbb #ccc; Change the colours to suit your needs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599850", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there a name for this concurrency pattern? The problem: we have critical path code that should never block. In many places it relies on configuration data, or similar, infrequently updated data from an external source. When we need to reload configuration data, or refresh data from an external source, we don't want to lock access to that data and potentially block the critical path threads. The solution: move the data in question to its own class. Use a background thread to fully perform the reload and validate the data. Then, when its ready, overwrite the old data reference with the new one. This reference must be volatile to ensure visibility to all threads. As long as its not imperative that the critical path code always have the most recent data available, this works great, with the absolute minimum performance impact (all data goes through a volatile ref). The real question is, is there a name for this concurrency design pattern? The language in question is Java, but I think this applies to most that support a shared-memory concurrency style of programming. A: For me, it looks like a atomic reference to a Value Object Value Object is a persistent object. It just represents a value, i.e. it represent a value from the moment you call the constructor to the end of it's life (no state change). Being a Value Object it is automatically Thread-safe. The atomic reference to it is just a central point to get access to the last version of the Value Object. The Clojure language call it a "ref". I've found a blog post about a design pattern, in GoF form, that looks like what you want: http://tobega.blogspot.com/2008/03/java-thread-safe-state-design-pattern.html EDIT: Rich Hickey (creator of Clojure) define it as Identity: "A putative entity we associate with a series of causally related values (states) over time". Source: http://www.infoq.com/presentations/Are-We-There-Yet-Rich-Hickey A: Could double buffering be the term you're looking for? A: You can still do high-performance locking. This just sounds dangerous. Anyway, you'll want to take a copy of the data -- while locked -- unlock it, then work on that data. A: I'm going to conclude that there is no well-known name for this pattern. The concepts from clojure map cleanly to what I've described here, but Ref and Identity aren't sufficiently descriptive for a design pattern name in Java. Thanks to @Thiago for pointing these out though. Thanks also to @Ed for pointing out that double buffering graphics and hardware is a very similar concept, but again it doesn't work as a design pattern name in Java. For my purposes, I'm going to use something along the lines of Atomic Build and Swap with coworkers so that we can have a handle for this frequently occurring design.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599851", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Converting Bitmap to Binary Array performance I do have a Bitmap Array that contains more than 500 Bitmaps object. I need to convert each single Bitmap object within the Array into a binary Array. I'm using the MemoryStream class to achieve this: using (MemoryStream ms = new MemoryStream()) { images[0].Save(ms, System.Drawing.Imaging.ImageFormat.Gif); byte[] byteData = ms.ToArray(); } I would like to know if there is other way to achieve this. I'm not sure how expensive is this process. Thanks A: I've done some speed tests and converting to ImageFormat.Bmp is the fastest. It doesn't need to do any compression. Though the best format will also depend on what you plan to do with the data after that. It's also worth considering where the Bitmaps came from in the first place. If you're loading them in from a file it may be worth it to switch things around and read the file data in first, then create your Bitmap objects from it after that. A: By choosing Gif you are making a CPU/memory trade off which you most likely don't want. Specifically the Gif is going to be smaller but is going to take some time to compress (unless the images are already in the format) relative to using a BMP. If you are copying these around enough that you have memory bandwidth issues (and can't fix that) this is a good idea, but otherwise you should stick with BMP. Really though, for 500 images I would expect this to take 1-2 seconds at the most so you probably don't need to worry about this sort of micro optimization. If its taking to long you can move to unmanaged code which will likely perform better because you will have finer control over memory allocations and copies.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599853", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: why does my jquery animation not function properly in chrome when using browser confirms and alerts? I'm seeing an issue regarding some jquery animation in chrome. I'm wondering if anyone else has seen this. I'm just trying to do some simple slide up to hide a div, or hide and then fade a div in. The slide up animation on the div is not happening in chrome and the hide is lagging before the fade in kicks in; whereas in firefox the animation is immediate and smooth. The thing is that I have a browser confirm wrapped around this stuff to only do this animation if the user confirms. If I remove the confirms, the animation works fine in chrome. Is that weird? Here's an example. With the confirm I get no slide up. Without the confirm I get one. That is, simply removing the if(confirm){} code block. if (confirm('Are you sure you want to remove the item?')) { dragbox.slideUp('fast', function () { dragbox.remove(); WebService.RemoveItem(itemId, //on success function () { if ($('.dragbox').length == 0) { //remove columns $('.column').remove(); } }, //on fail function () { alert('Failed to remove the "' + itemName + '" item.'); } ); }); } In this example, with the confirm there's a lag after the div is hidden and before the fade in start so that the div is hidden longer than I would like. Without the confirm, ti behaves as I would expect. if (confirm('Are you sure?')) { $('#' + itemId).spin(); WebService.AddItem(itemId, //onsuccess function (r) { var item = $('#' + itemId); //this is a div item.unspin(); item .hide() .toggleClass('item-added') .fadeIn('fast', function () { // Create the DOM elements $('<p><img class="item-added" src="images/item-added.png" />') // Sets the style of the elements to "display:none" .hide() // Appends the hidden elements to the "posts" element .appendTo($('.contentInfo', item)) // Fades the new content into view .fadeIn('fast'); }); }, //onfail function () { $('#' + itemId).unspin(); alert('Failed'); } ); } Can anyone confirm or disprove this notion based on my speculation and example? What are some alternatives to the browser confirm? EDIT: Yeah I'm not sure what's going on. A: Are you using the newest version of jQuery UI? Have you got the jQuery UI stylesheet also? It all looks fine. If you can't find an answer here, open up a bug report. A: Updating Chrome fixes this. I'm now running version 15.0.874.120 and all is well. My word. A: I was just experiencing the same thing with some code that worked when it was written a couple of years ago. Now it has an issues in webkit-based browsers. I had several animations that were paused by using confirm() calls and the subsequent animations failed to display properly. I finally figured out that if I put a short delay before the animation, it started working properly. if (confirm('Are you sure?')) { dragbox.delay(10).slideUp('fast', function () { ... I'm not quite sure why this works but my animations are now working again in Safari 6.0.3 and Chrome 26.0.1410.43
{ "language": "en", "url": "https://stackoverflow.com/questions/7599861", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Facebook JavaScript SDK for FQL with additional parameter Facebook deprecated FB.Data.waitOn and FB.Data.query and they recommend we use FB.api instead. More info: http://developers.facebook.com/blog/post/561/ This sounds easy enough, but I can't seem to pass additional parameters with my FQL request without getting an error from Facebook. For example, I can successfully do this: FB.api({ method: 'fql.query', query: 'select page_id, name, pic, page_url from page where page_id=' + some_page_id }, function(response){ console.log(response); }); But I'd also like to pass the 'return_ssl_resources=1' additional parameter so that Facebook returns secure resources instead of non-secure ones. However, if I try the following, Facebook returns a "Parser error: unexpected '&' at position 71" error: FB.api({ method: 'fql.query', query: 'select page_id, name, pic, page_url from page where page_id=' + some_page_id + '&return_ssl_resources=1' }, function(response){ console.log(response); }); Does anyone know how to pass additional parameters when making FQL requests using the JavaScript SDK? A: It turns out that we can pass additional parameters as properties in the first argument to FB.api(): FB.api({ method: 'fql.query', query: 'select page_id, name, pic, page_url from page where page_id=' + some_page_id, return_ssl_resources: 1 }, function(response){ console.log(response); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7599865", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: sending nested struct over UDP api that accept string I am using a UDP api that basically accept string parameter to be send only. send_udp(str data, ip_address dest); so the thing is that I have a struct below typedef struct { int bmw_red; }vm_car_type; typedef struct { int numberofbuying; vm_car_type bmw; } msg_type; The problem is that I can basically want to send the msg_type struct (that contains another struct inside it), serialize the whole struct to string, and send it using send_udp message. I do not know how to serialize this msg_type into string, so that it can be send. Does anyone have a suggestion what to do, as I can not use any other library to serialize this, so just xml parser. I have the receiver parser, but I can not get the idea of how to serialize the above struct to xml, so I am trying to find any ways to convert the struct to string Thank you for any suggestions. A: Here's some serialization information from Beej's C networking programming guide.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599866", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Set button state programmatically I define my button's states with <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true" > <shape> <gradient android:endColor="@color/orange_light" android:startColor="@color/orange" android:angle="270" /> <corners android:radius="6dp" /> <padding android:left="10dp" android:right="10dp" /> </shape> </item> <item android:state_focused="true" > <shape> <gradient android:endColor="@color/orange_light" android:startColor="@color/orange" android:angle="270" /> <corners android:radius="6dp" /> <padding android:left="10dp" android:right="10dp" /> </shape> </item> <item> <shape> <gradient android:endColor="@color/grey_light" android:startColor="@color/grey" android:angle="270" /> <corners android:radius="6dp" /> <padding android:left="10dp" android:right="10dp" /> </shape> </item> </selector> and set this as my button's background. When I press it it change colors properly, but I'd like it to keep the 'pressed' color once released (to show which button is active). How can I do this? requestFocus() does not work... Thanks A: well in your setOnClickListener you can implement some logic. For example ones the button is pressed it get one color and keeps that color until other button is pressed and when the second one i pressed than the first button's background gets reset to default.... you can implement what ever you want you just need to add some logic and that it is. If you want your button to have some color just for the time is in pressed state than override the on touch listener you can do like this addButtonLayout.setOnTouchListener(new OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_UP) { imageAddSign.setImageResource(R.drawable.a); }else{ imageAddSign.setImageResource(R.drawable.b); } return false; } }); A: I think, what you need is a checkbox and not a button. Try to set the background there or subclass it if you need more features.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599867", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Akka Cluster Java API sample I am pretty interested in testing out the 2.0-SNAPSHOT Akka cluster features, but for my purposes would like to do this in Java. I have read through the example here: http://letitcrash.posterous.com/clustered-actors-with-cloudy-akka But the API seems to have changed enough (Cluster.startLocalCluster() doesn't exist anymore?), and the documentation is sparse enough (to be expected), that my tinkering is going very slow. Is anybody aware of a small small sample application that stands up a couple of local nodes via Akka clustering in Java? Thanks very much. A: At the moment I would not recommend playing around with cluster functionality, too much can change until release. See also where-can-i-find-akka-cloud-package.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599870", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Which indices should be added to speed up queries on massive InnoDB table? Here is my table: CREATE TABLE `letters` ( `a` bigint(20) unsigned NOT NULL, `b` bigint(20) unsigned NOT NULL, `c` bigint(20) unsigned NOT NULL, `d` bigint(20) unsigned NOT NULL, `e` bigint(20) unsigned NOT NULL, PRIMARY KEY (`a`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8$$ * *The table will have about 1+ billion rows. *Each column can be queried; each column can be referenced. e.g.: * *SELECT [any column] FROM letters WHERE [any / any other column] IN ([subquery or list]); My question: what indices should I add to speed up any query in the format above? (Also, if possible, please try to describe 'why' it/they should be added so that I can learn from your answer). Thanks! -- Extra info: inserts will happen on a fairly regular basis (a few/handful every second) but select queries will happen more frequently. A: Since any column can appear in the WHERE clause, you've to add an index for each of the column, except for the field a since is already the PRIMARY KEY and as such is already indexed. UPDATE: as for the subsequent discussion, Poodlehat pointed out that the column e has a low index selectivity, i.e. "The ratio of the number of distinct values in the indexed column / columns to the number of records in the table". For this reason, it's not clear whether adding an index on column e will help or slow down queries. So Lucas will try experimentally and hopefully share the results to us. A: I think you need to have a unique index on a (or it should be a primary key), definitely indexes on b,c,d (on each). No need for index on e (it won't be used anyway since as you say it has just 15 different values)
{ "language": "en", "url": "https://stackoverflow.com/questions/7599873", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Fb.ui() popup works but dialog loads forever I want to ask a user to grant the "publish_stream" permission to my app with the facebook javascript sdk. I initialize it like this: FB.init({ appId : '203702512703', status : true, // check login status cookie : true, // enable cookies to allow the server to access the session xfbml : true, // parse XFBML channelURL : 'http://mydomain.com/channel.php', // channel.html file oauth : true // enable OAuth 2.0 }); And my FB.ui call looks like this: FB.ui({ client_id: '203702512703', method: 'oauth', scope: 'publish_stream', redirect_uri: 'http://mydomain.com/', response_type: 'token', display: 'dialog' }); If i change 'dialog' to 'popup' it works perfectly. But if i specify 'dialog' or leave the option out it shows me the fb-div but with a loading animation (like this: http://p.iqs.me/t1c4j ) and the content never loads. What am i doing wrong? UPDATE: I found this page http://developers.facebook.com/docs/reference/dialogs/#display that says the following about using "iframe" as display: "Because of the risk of clickjacking, this is only allowed for some certain dialogs, and requires you to pass a valid access_token" Doesn't say anything like that about "dialog" thought but both iframe and dialog gives the same bad result. How would i pass in the access_token? A: 'popup' is mandatory for method: 'oauth' or FB.login for javascript SDK because of security (clickjacking and phishing). I'd suggest to use FB.login anyway to get permissions or to authenticate because it is more convenient. hope this helps A: There is also a discrepancy in the way you can use display: iframe for FB.login depending on whether you're in a tab or on a canvas. On a tab you don't need an access_token and on a canvas you do. So on a canvas, you're stuck with either pop-ups being blocked or a good percentage of users refusing to provide basic permissions for something as simple as a post to their own wall that they initiated. IMVHO FB need to rectify this asap but I've had a bug logged against it for months and there's been no sign of a change.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599891", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHPUnit test case aware of symfony2 dependency injection container I'm actually testing a bundle that I created. All the code is fully unit tested but now, I want to test if my symfony2 services can be request without any trouble. For that, I need the symfony2 dependency injection container in my test case. How can I do that ? A: I recently asked a question similar to this in that I needed just the validator, however the person who replied to my question first had a solution which gave access to the whole container. Basically you can pick apart WebTestCase in order to see how it builds the Symfony2 environment and make your own base class which is Symfony aware as it were. Here is the answer, I hope it helps: Symfony2: Testing entity validation constraints
{ "language": "en", "url": "https://stackoverflow.com/questions/7599894", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Django Template does not exist in production server but is working in :8000 Hi guys im having a problem with my own django server (at home), django can't find templates, my error code django is looking in the correct place (/var/www/project/templates) but nothing happen Template does not exist but all path are fine. but using test server :8000 all is fine, i dont know how ill fix this edit this is perfect for get the template: /var/www/agricultura/templates/forms/registro_form.html Template path import os TEMPLATE_DIRS = ( os.path.join(os.path.abspath(os.path.dirname(__file__)),'templates'), ) Template Loader Error: Django tried loading these templates, in this order: Using loader django.template.loaders.filesystem.Loader: /var/www/agricultura/templates/forms/registro_form.html (File does not exist) Using loader django.template.loaders.app_directories.Loader: /usr/local/lib/python2.6/dist-packages/admin_tools/theming/templates/forms/registro_form.html (File does not exist) /usr/local/lib/python2.6/dist-packages/admin_tools/menu/templates/forms/registro_form.html (File does not exist) /usr/local/lib/python2.6/dist-packages/admin_tools/dashboard/templates/forms/registro_form.html (File does not exist) /usr/local/lib/python2.6/dist-packages/django/contrib/admin/templates/forms/registro_form.html (File does not exist) Using loader django.template.loaders.eggs.Loader: Traceback: File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py" in get_response 111. response = callback(request, *callback_args, **callback_kwargs) File "/var/www/agricultura/registro/views.py" in registro_view 71. context_instance=RequestContext(request)) File "/usr/local/lib/python2.6/dist-packages/django/shortcuts/__init__.py" in render_to_response 20. return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs) File "/usr/local/lib/python2.6/dist-packages/django/template/loader.py" in render_to_string 181. t = get_template(template_name) File "/usr/local/lib/python2.6/dist-packages/django/template/loader.py" in get_template 157. template, origin = find_template(template_name) File "/usr/local/lib/python2.6/dist-packages/django/template/loader.py" in find_template 138. raise TemplateDoesNotExist(name) Exception Type: TemplateDoesNotExist at /registro/ Exception Value: forms/registro_form.html Any idea? thanks A: Trivial, but I have seen instances where people forget to add the concerned application in the installed apps and get the template not found error. A: there might be an error in the template. Have you got TEMPLATE_DEBUG = True in the settings? And you've set TEMPLATE_DIRS as well? Try loading the template via the python shell on your server: https://docs.djangoproject.com/en/dev/ref/templates/api/#the-render-to-string-shortcut ./manage.py shell from django.template.loader import render_to_string rendered = render_to_string('my_template.html', { 'foo': 'bar' }) It might throw an error and give you a further clue. A: Add this to your settings file: def findMyWay(*relativeComponents): return os.path.join(os.path.dirname(__file__), *relativeComponents).replace("\\","/") TEMPLATE_LOADERS = ( "django.template.loaders.filesystem.Loader", "django.template.loaders.app_directories.Loader", ) TEMPLATE_DIRS = ( findMyWay("templates"), ) Working perfectly fine for me.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599908", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: In Cygwin emacs C-c is read as C-g I recently installed cygwin and emacs, and when I try to exit the program (by pressing C-x C-c) the minibuffer reads "C-x C-g is undefined". When I type C-c the minibuffer reads "Quit" just like if I had typed C-g. To the best of my knowledge, it's just reading the c key as a g in the minibuffer. However, if I type c into a scratch buffer it correctly displays c. Or if I type M-x c, it correctly reads as c in the minibuffer. Is this a common problem? How do I fix this? Thanks so much for any help! It's driving me crazy. Right now, I have to exit out of Cygwin when I want to quit emacs because C-x C-c won't close the program! A: This is a problem with the default Cygwin console, but it doesn't happen with other Cygwin terminals such as mintty, rxvt, or xterm, so you might want to try one of those. Also, I believe the issue with the console is fixed in recent Cygwin snapshots.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599912", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ACTION_SEND and Google+ App in Android is there any way to share text from my android app by using ACTION_SEND and google+ app. Has anyone try that, which mimeType should i write? Thanks for your answers A: I am pretty sure that Google+ app has intent filters for text/plain and image/*. Here's what they have in the manifest: <activity android:theme="@style/CircleBrowserTheme" android:name=".phone.PostActivity" android:launchMode="singleTop" android:logo="@drawable/ic_menu_stream"> <intent-filter> <action android:name="android.intent.action.SEND" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="text/plain" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.SEND" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="image/*" /> </intent-filter> <intent-filter> <action android:name="android.intent.action.SEND_MULTIPLE" /> <category android:name="android.intent.category.DEFAULT" /> <data android:mimeType="image/*" /> </intent-filter> </activity> So you should be able to putExtra a String onto your intent and setType("text/plain") and that will most likely work just fine. Looks like you won't be able to send both a text and a picture at the same time, though, as SEND_MULTIPLE on G+ only takes images.
{ "language": "en", "url": "https://stackoverflow.com/questions/7599923", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: My tab menus exit the page width So I'm editting the CSS and the tab menu has a whitespace: nowrap property, which means it doesn't overlap but it ends up exiting the page. Setting the width of the tab menu itself does nothing even with !important and heirarchy CSS. Looks like this http://i.imgur.com/yxblJ.jpg When I do whitespace: pre, or any of the others they end up overlapping. Here's the code: html > body > div#header > div#header-bottom-left > ul.tabmenu { position: absolute; top: 75px; left: 700px; width: 100px !important; } #header #header-bottom-left .tabmenu li { font-family: "Courier New", Courier, monospace !important; text-transform: uppercase; letter-spacing: 2px; font-variant: small-caps; font-size: 11px; background: url(%%buttons%%) repeat-x; border: 1px solid black; padding: 5px; margin-right: 16px; } A: Remove li { margin-right: 16px; } You may try this too ul,li { border:0px; padding:0px; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7599928", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }