pid
int64 2.28k
41.1M
| label
int64 0
1
| text
stringlengths 1
28.3k
|
---|---|---|
13,222,849 | 0 | NodeJS+Sequelize+Jade; Using the hasMany collection on an object <p>I'm working on a nodejs+sequelize+jade web-app to learn nodejs. Everything basic is quite clear but now I want to up the ante. I have object(table) called brand. The object product has a one-to-many relation with brand. What I like to do is to findAll brands and show them in a Jade-template and also list the products under it.</p> <p>Here is some basic code</p> <pre><code>var Brand = sequelize.import(application_root + "/models/brand.js"); var Product = sequelize.import(application_root + "/models/product.js"); Brand.hasMany(Product, { as: 'Products', foreignKey: 'brand'}); Product.belongsTo(Brand, { foreignKey: 'key'}); </code></pre> <p>In the route for showing the brands and products I do;</p> <pre><code> Brand.findAll().error(errorHandler).success(function(brands) { brands[0].getProducts().success(function(products) { brands[0].products = products; }); res.render('listOfbrands.jade', { title: 'List of brands', items: brands}); }); </code></pre> <p>The strangest thing is that I can see a query being fired when the console.log has been executed but it doesn't create a correct query with the primary key of the brand. The query being select * from products where "brand" is null </p> <p>Also I want to know if I'm assigning the sub collection correct to access it in my Jade template by doing like this</p> <pre><code>ul each item in items li(class='brandItem')= item.name ul each product in item.products li=product.name </code></pre> |
37,761,657 | 0 | How can I make the image smaller width? Masonry <p>Basically not know how to change the width of the image so it looks like in design.</p> <p>I'm new to working with this library and I want to know how I can change my example to be like in design.</p> <p>The middle image is smaller than the other two. Also to be preserved and height as all three</p> <p>I have this <a href="http://codepen.io/anon/pen/mEVoJo" rel="nofollow">sample</a></p> <p><strong>CODE HTML:</strong></p> <pre><code><div class="grid"> <div class="grid-sizer"></div> <div class="grid-item item-1"> <img src="http://bagelhousecafe.ch/wp-content/themes/wp_bagel/assets/img/img-01.png" /> </div> <div class="grid-item item-2"> <img src="http://bagelhousecafe.ch/wp-content/themes/wp_bagel/assets/img/img-02.png" /> </div> <div class="grid-item item-3"> <img src="http://bagelhousecafe.ch/wp-content/themes/wp_bagel/assets/img/img-03.png" /> </div> </div> </code></pre> <p><strong>CODE CSS:</strong></p> <pre><code>* { box-sizing: border-box; } /* force scrollbar */ html { overflow-y: scroll; } body { font-family: sans-serif; } /* ---- grid ---- */ .item-1,.item-3{ width:40%; } .grid { background: #DDD; } /* clear fix */ .grid:after { content: ''; display: block; clear: both; } /* ---- .grid-item ---- */ .grid-sizer, .grid-item { width: 33.333%; } .grid-item { float: left; } .grid-item img { display: block; width: 100%; } </code></pre> <p><strong>CODE JS:</strong></p> <pre><code>// external js: masonry.pkgd.js, imagesloaded.pkgd.js // init Masonry after all images have loaded var $grid = $('.grid').imagesLoaded( function() { $grid.masonry({ itemSelector: '.grid-item', percentPosition: true, columnWidth: '.grid-sizer' }); }); </code></pre> <p><a href="http://i.stack.imgur.com/KlhCd.jpg" rel="nofollow">And here is the image</a></p> <p>Thanks in advance!</p> |
230,082 | 0 | <p>Silverlight can do this (as can Flash, I'm sure). CSS3 will support it. But graphic text is the way to go right now.</p> <p>You can use any of several text-hiding techniques in CSS to show the text for accessible browsers, yet display the graphic (with text arranged vertically) for sighted users.</p> |
32,798,639 | 0 | <p>You need to use encodeURIComponent to do this.</p> <pre><code>encodeURIComponent('http://example.com/feed.xml&0.1234') </code></pre> <p>will result in</p> <pre><code>http%3A%2F%2Fexample.com%2Ffeed.xml%260.1234 </code></pre> <p>and when appended to the end result you'll get</p> <pre><code>https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=5&q=http%3A%2F%2Fexample.com%2Ffeed.xml%260.1234 </code></pre> |
27,635,845 | 0 | Hbase connection problems and failed to create table <p>I'm running a multi-node cluster; I'm using hadoop-1.0.3(on both), Hbase-0.94.2(on both) and zookeeper-3.4.6(only master) </p> <p>master:192.168.0.1 slave:192.168.0.2</p> <p>Hbase is not running perfectly and I faced problems while trying to create a table on hbase and of course I can't access HBase status UI on <code>http://master:60010</code> please Help!!</p> <p>Here is all my configuration files :</p> <p>(hadoop conf) core-site.xml: (same configuration on both master and slave)</p> <pre><code> <configuration> <property> <name>fs.default.name</name> <value>hdfs://localhost:54310</value> </property> </configuration> </code></pre> <p>(hbase conf) hbase-site.xml:</p> <pre><code><configuration> <property> <name>hbase.rootdir</name> <value>hdfs://master:54310/hbase</value> </property> <property> <name>hbase.cluster.distributed</name> <value>true</value> </property> <property> <name>hbase.zookeeper.quorum</name> <value>master,slave</value> </property> <property> <name>hbase.zookeeper.property.clientPort</name> <value>2222</value> </property> <property> <name>hbase.zookeeper.property.dataDir</name> <value>/usr/local/hadoop/zookeeper</value> </property> </configuration> </code></pre> <p>/etc/hosts and :</p> <pre><code>192.168.0.1 master 192.168.0.2 slave </code></pre> <p>regionservers:</p> <pre><code>master slave </code></pre> <p>here is the log file : hbase-hduser-regionserver-master.log</p> <pre><code>2014-12-24 02:12:13,190 WARN org.apache.zookeeper.ClientCnxn: Session 0x0 for server null, unexpected error, closing socket connection and attempting reconnect java.net.NoRouteToHostException: No route to host at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method) at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:739) at org.apache.zookeeper.ClientCnxnSocketNIO.doTransport(ClientCnxnSocketNIO.java:286) at org.apache.zookeeper.ClientCnxn$SendThread.run(ClientCnxn.java:1035) 2014-12-24 02:12:14,002 INFO org.apache.zookeeper.ClientCnxn: Opening socket connection to server master/192.168.0.1:2181 2014-12-24 02:12:14,003 INFO org.apache.zookeeper.client.ZooKeeperSaslClient: Client will not SASL-authenticate because the default JAAS configuration section 'Client' could not be found. If you are not using SASL, you may ignore this. On the other hand, if you expected SASL to work, please fix your JAAS configuration. 2014-12-24 02:12:14,004 INFO org.apache.zookeeper.ClientCnxn: Socket connection established to master/192.168.0.1:2181, initiating session 2014-12-24 02:12:14,005 INFO org.apache.zookeeper.ClientCnxn: Unable to read additional data from server sessionid 0x0, likely server has closed socket, closing socket connection and attempting reconnect 2014-12-24 02:12:14,675 INFO org.apache.hadoop.ipc.HBaseServer: Stopping server on 60020 2014-12-24 02:12:14,676 FATAL org.apache.hadoop.hbase.regionserver.HRegionServer: ABORTING region server master,60020,1419415915643: Initialization of RS failed. Hence aborting RS. java.io.IOException: Received the shutdown message while waiting. at org.apache.hadoop.hbase.regionserver.HRegionServer.blockAndCheckIfStopped(HRegionServer.java:623) at org.apache.hadoop.hbase.regionserver.HRegionServer.initializeZooKeeper(HRegionServer.java:598) at org.apache.hadoop.hbase.regionserver.HRegionServer.preRegistrationInitialization(HRegionServer.java:560) at org.apache.hadoop.hbase.regionserver.HRegionServer.run(HRegionServer.java:669) at java.lang.Thread.run(Thread.java:745) 2014-12-24 02:12:14,676 FATAL org.apache.hadoop.hbase.regionserver.HRegionServer: RegionServer abort: loaded coprocessors are: [] 2014-12-24 02:12:14,676 INFO org.apache.hadoop.hbase.regionserver.HRegionServer: STOPPED: Initialization of RS failed. Hence aborting RS. 2014-12-24 02:12:14,683 INFO org.apache.hadoop.hbase.regionserver.HRegionServer: Registered RegionServer MXBean 2014-12-24 02:12:14,689 INFO org.apache.hadoop.hbase.regionserver.ShutdownHook: Shutdown hook starting; hbase.shutdown.hook=true; fsShutdownHook=Thread[Thread-5,5,main] 2014-12-24 02:12:14,689 INFO org.apache.hadoop.hbase.regionserver.HRegionServer: STOPPED: Shutdown hook 2014-12-24 02:12:14,690 INFO org.apache.hadoop.hbase.regionserver.ShutdownHook: Starting fs shutdown hook thread. 2014-12-24 02:12:14,691 INFO org.apache.hadoop.hbase.regionserver.ShutdownHook: Shutdown hook finished. </code></pre> |
27,985,064 | 0 | <p>In pure Python you can do this using a dictionary in <code>O(N)</code> time, the only time penalty is going to be the Python loop involved:</p> <pre><code>>>> arr1 = np.array([7.2, 2.5, 3.9]) >>> arr2 = np.array([[7.2, 2.5], [3.9, 7.2]]) >>> indices = dict(np.hstack((arr1[:, None], np.arange(3)[:, None]))) >>> np.fromiter((indices[item] for item in arr2.ravel()), dtype=arr2.dtype).reshape(arr2.shape) array([[ 0., 1.], [ 2., 0.]]) </code></pre> |
16,220,490 | 0 | If there a way I can inner join a MS Sql table to a MySql Table in one query using MySql? <p>I have 2 servers one servers runs Microsoft SQL Server and the other one is using MySql. </p> <p>I need to be able to inner join a table from MS SQL name it "A" to a table "B" located on a different server that uses MySql</p> <p>So I want to be able to do something like this</p> <p><code>SELECT A.*, B.* FROM A INNER JOIN B ON A.id=B.id LIMIT 100</code></p> <p>How can I do this? note that both servers are on the same network. </p> |
18,921,377 | 0 | <p>Another alternative: RedGate has recently updated pricing on their Deployment manager tool: <a href="http://www.red-gate.com/delivery/deployment-manager/" rel="nofollow">http://www.red-gate.com/delivery/deployment-manager/</a></p> <p>If you have 5 projects or less, the tool appears to be free. </p> |
22,302,102 | 0 | <p>Try using regex as a lightweight solution.</p> <p>Try this regex (tested on <a href="http://regexpal.com/" rel="nofollow">http://regexpal.com/</a>):</p> <pre><code>src=\"([^\"]*)\" </code></pre> <p>And you could extract the string using captured group</p> <p>Sample code:</p> <pre><code>string input = "<img alt=\"Desert.jpg\" src=\"/PublishingImages/Lists/Images/NewForm/Desert.jpg\" width=\"174\" style=\"BORDER: 0px solid; \">"; string pattern = "src=\"([^\"]*)\""; string extractedString = Regex.Match(input, pattern).Groups[1].Value; </code></pre> |
14,584,006 | 0 | <p>In dynamically loaded files using autoloaders, the file containing the function or class might not have loaded, so you need to check if it exists</p> |
2,800,943 | 0 | javascript form submission usng window.onload on background window <p>I have a form which submits certain values to third party... I am using windows.onload(); to submit that form, but as soon as the page is loaded the focus goes to new window... Is there a way to retain focus on my window only...</p> |
8,276,845 | 1 | python's scrapy doesn't seem to get data from all available URLs <p>I'm trying to scrape <a href="http://thesession.org" rel="nofollow noreferrer">thesession.org</a> to create a table of how many times each tune has been added to memeber's tunebooks so I can find some popular pieces to learn. I've started with the scrapy tutorial <a href="http://doc.scrapy.org/en/0.7/intro/tutorial.html" rel="nofollow noreferrer">here</a> and am trying to modify it to suit my purposes. The problem is that although the thesession.org website appears to have some 10,390 tunes, my scraper only returns data on 10 of them (only the ones on <a href="http://www.thesession.org/tunes/index.php" rel="nofollow noreferrer">http://www.thesession.org/tunes/index.php</a>). How can I get data on all the tunes (or the top-ranked hundred tunes)? Any advice would be greatly appreciated.</p> <p>Here's what I've got so far: </p> <p>items.py</p> <pre><code>from scrapy.item import Item, Field class tuneItem(Item): url = Field() name1 = Field() name2 = Field() key = Field() count = Field() pass </code></pre> <p>tune_spider.py</p> <pre><code>from scrapy.spider import BaseSpider from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import HtmlXPathSelector from scrapy.item import Item from tutorial.items import tuneItem from scrapy.conf import settings class tunesSpider(CrawlSpider): name = "irishtunes" allowed_domains = ["thesession.org"] start_urls = ["http://www.thesession.org/tunes"] rules = [Rule(SgmlLinkExtractor(allow=['/display/\d+'], deny=['/members/','/recordings/','/index/','/display/\d+/.']), 'parse_tune')] def parse_tune(self, response): x = HtmlXPathSelector(response) tune = tuneItem() tune['url'] = response.url tune['name1'] = x.select("//div[@id='details']//div[@class='box']/h1/text()").extract() tune['name2'] = x.select("//div[@id='details']//div[@class='box']/h2/text()").extract() tune['key'] = x.select("//div[@id='details']//div[@class='box']/p[1]/text()").extract() tune['count'] = x.select("//div[@id='details']//div[@class='box']/p[3]/text()").re('\d+') return tune </code></pre> <p>I run the scraper by opening my console, going to directory containing tutorial's cfg file, and running <code>scrapy crawl irishtunes --set FEED_URI=scraped_data.csv --set FEED_FORMAT=csv</code></p> <p>Here is what I get:</p> <pre><code>C:\Users\BM\Desktop\scrape\tutorial>scrapy crawl irishtunes --set FEED_URI=scrap ed_data.csv --set FEED_FORMAT=csv 2011-11-25 22:45:47-0800 [scrapy] INFO: Scrapy 0.14.0.2841 started (bot: tutoria l) 2011-11-25 22:45:47-0800 [scrapy] DEBUG: Enabled extensions: FeedExporter, LogSt ats, TelnetConsole, CloseSpider, WebService, CoreStats, SpiderState 2011-11-25 22:45:48-0800 [scrapy] DEBUG: Enabled downloader middlewares: HttpAut hMiddleware, DownloadTimeoutMiddleware, UserAgentMiddleware, RetryMiddleware, De faultHeadersMiddleware, RedirectMiddleware, CookiesMiddleware, HttpCompressionMi ddleware, ChunkedTransferMiddleware, DownloaderStats 2011-11-25 22:45:48-0800 [scrapy] DEBUG: Enabled spider middlewares: HttpErrorMi ddleware, OffsiteMiddleware, RefererMiddleware, UrlLengthMiddleware, DepthMiddle ware 2011-11-25 22:45:48-0800 [scrapy] DEBUG: Enabled item pipelines: 2011-11-25 22:45:48-0800 [irishtunes] INFO: Spider opened 2011-11-25 22:45:48-0800 [irishtunes] INFO: Crawled 0 pages (at 0 pages/min), sc raped 0 items (at 0 items/min) 2011-11-25 22:45:48-0800 [scrapy] DEBUG: Telnet console listening on 0.0.0.0:602 3 2011-11-25 22:45:48-0800 [scrapy] DEBUG: Web service listening on 0.0.0.0:6080 2011-11-25 22:45:48-0800 [irishtunes] DEBUG: Redirecting (301) to <GET http://ww w.thesession.org/tunes/> from <GET http://www.thesession.org/tunes> 2011-11-25 22:45:48-0800 [irishtunes] DEBUG: Crawled (200) <GET http://www.these ssion.org/tunes/> (referer: None) 2011-11-25 22:45:49-0800 [irishtunes] DEBUG: Crawled (200) <GET http://www.these ssion.org/tunes/display/11602> (referer: http://www.thesession.org/tunes/) 2011-11-25 22:45:49-0800 [irishtunes] DEBUG: Scraped from <200 http://www.theses sion.org/tunes/display/11602> {'count': [u'1'], 'key': [u'Key signature: Dmajor'], 'name1': [u"Brendan Begley's"], 'name2': [u'polka'], 'url': 'http://www.thesession.org/tunes/display/11602'} 2011-11-25 22:45:49-0800 [irishtunes] DEBUG: Crawled (200) <GET http://www.these ssion.org/tunes/display/11593> (referer: http://www.thesession.org/tunes/) 2011-11-25 22:45:49-0800 [irishtunes] DEBUG: Scraped from <200 http://www.theses sion.org/tunes/display/11593> {'count': [u'3'], 'key': [u'Key signature: Amajor'], 'name1': [u'Carleton County Breakdown'], 'name2': [u'reel'], 'url': 'http://www.thesession.org/tunes/display/11593'} 2011-11-25 22:45:49-0800 [irishtunes] DEBUG: Crawled (200) <GET http://www.these ssion.org/tunes/display/11597> (referer: http://www.thesession.org/tunes/) 2011-11-25 22:45:49-0800 [irishtunes] DEBUG: Scraped from <200 http://www.theses sion.org/tunes/display/11597> {'count': [u'3'], 'key': [u'Key signature: Dmajor'], 'name1': [u"Kasper's Rant"], 'name2': [u'hornpipe'], 'url': 'http://www.thesession.org/tunes/display/11597'} 2011-11-25 22:45:49-0800 [irishtunes] DEBUG: Crawled (200) <GET http://www.these ssion.org/tunes/display/11594> (referer: http://www.thesession.org/tunes/) 2011-11-25 22:45:49-0800 [irishtunes] DEBUG: Scraped from <200 http://www.theses sion.org/tunes/display/11594> {'count': [u'5'], 'key': [u'Key signature: Gmajor'], 'name1': [u'The Full Of The Bag'], 'name2': [u'hornpipe'], 'url': 'http://www.thesession.org/tunes/display/11594'} 2011-11-25 22:45:49-0800 [irishtunes] DEBUG: Crawled (200) <GET http://www.these ssion.org/tunes/display/11599> (referer: http://www.thesession.org/tunes/) 2011-11-25 22:45:49-0800 [irishtunes] DEBUG: Scraped from <200 http://www.theses sion.org/tunes/display/11599> {'count': [u'1'], 'key': [u'Key signature: Adorian'], 'name1': [u'The New Steamboat'], 'name2': [u'reel'], 'url': 'http://www.thesession.org/tunes/display/11599'} 2011-11-25 22:45:49-0800 [irishtunes] DEBUG: Crawled (200) <GET http://www.these ssion.org/tunes/display/11598> (referer: http://www.thesession.org/tunes/) 2011-11-25 22:45:49-0800 [irishtunes] DEBUG: Scraped from <200 http://www.theses sion.org/tunes/display/11598> {'count': [u'4'], 'key': [u'Key signature: Gmajor'], 'name1': [u"Galen's Arrival"], 'name2': [u'reel'], 'url': 'http://www.thesession.org/tunes/display/11598'} 2011-11-25 22:45:49-0800 [irishtunes] DEBUG: Crawled (200) <GET http://www.these ssion.org/tunes/display/11596> (referer: http://www.thesession.org/tunes/) 2011-11-25 22:45:49-0800 [irishtunes] DEBUG: Scraped from <200 http://www.theses sion.org/tunes/display/11596> {'count': [u'2'], 'key': [u'Key signature: Amixolydian'], 'name1': [u'Culloden Day'], 'name2': [u'strathspey'], 'url': 'http://www.thesession.org/tunes/display/11596'} 2011-11-25 22:45:49-0800 [irishtunes] DEBUG: Crawled (200) <GET http://www.these ssion.org/tunes/display/11595> (referer: http://www.thesession.org/tunes/) 2011-11-25 22:45:49-0800 [irishtunes] DEBUG: Scraped from <200 http://www.theses sion.org/tunes/display/11595> {'count': [u'2'], 'key': [u'Key signature: Aminor'], 'name1': [u'Miss Sine Flemington'], 'name2': [u'barndance'], 'url': 'http://www.thesession.org/tunes/display/11595'} 2011-11-25 22:45:49-0800 [irishtunes] DEBUG: Crawled (200) <GET http://www.these ssion.org/tunes/display/11600> (referer: http://www.thesession.org/tunes/) 2011-11-25 22:45:49-0800 [irishtunes] DEBUG: Scraped from <200 http://www.theses sion.org/tunes/display/11600> {'count': [u'2'], 'key': [u'Key signature: Dmajor'], 'name1': [u"Joan Martin's"], 'name2': [u'polka'], 'url': 'http://www.thesession.org/tunes/display/11600'} 2011-11-25 22:45:49-0800 [irishtunes] DEBUG: Crawled (200) <GET http://www.these ssion.org/tunes/display/11601> (referer: http://www.thesession.org/tunes/) 2011-11-25 22:45:49-0800 [irishtunes] DEBUG: Scraped from <200 http://www.theses sion.org/tunes/display/11601> {'count': [u'2'], 'key': [u'Key signature: Gmajor'], 'name1': [u'My Time Inside 2005'], 'name2': [u'waltz'], 'url': 'http://www.thesession.org/tunes/display/11601'} 2011-11-25 22:45:49-0800 [irishtunes] INFO: Closing spider (finished) 2011-11-25 22:45:49-0800 [irishtunes] INFO: Stored csv feed (10 items) in: scrap ed_data.csv 2011-11-25 22:45:49-0800 [irishtunes] INFO: Dumping spider stats: {'downloader/request_bytes': 3655, 'downloader/request_count': 12, 'downloader/request_method_count/GET': 12, 'downloader/response_bytes': 31620, 'downloader/response_count': 12, 'downloader/response_status_count/200': 11, 'downloader/response_status_count/301': 1, 'finish_reason': 'finished', 'finish_time': datetime.datetime(2011, 11, 26, 6, 45, 49, 500000), 'item_scraped_count': 10, 'request_depth_max': 1, 'scheduler/memory_enqueued': 12, 'start_time': datetime.datetime(2011, 11, 26, 6, 45, 48, 10000)} 2011-11-25 22:45:49-0800 [irishtunes] INFO: Spider closed (finished) 2011-11-25 22:45:49-0800 [scrapy] INFO: Dumping global stats: {} </code></pre> <p><strong>EDIT:</strong> The answer from @reclosedev got me on the way. For anyone wondering about the outcome, here's a snapshot... </p> <p>(1) The vast majority of tunes are less than 10 members' tunebooks</p> <p><img src="https://i.stack.imgur.com/bOJvl.png" alt="enter image description here"></p> <p>(2) The popularity of all 10,379 tunes that I could scrape from the site (as measured by how many tunebooks they are in) follows a power-law distribution</p> <p><img src="https://i.stack.imgur.com/8hozW.png" alt="enter image description here"></p> <p>(3) And here are the tunes that are in >1000 tunebooks on the site, showing the names of the top-ranked tunes and how many tunebooks they are in</p> <p><img src="https://i.stack.imgur.com/WgAik.png" alt="enter image description here"></p> |
23,188,463 | 0 | <p>try this:</p> <pre><code> $name = $_POST['name']; $email = $_POST['email']; $custom_field1 = $_POST['custom_field1']; $custom_field2 = $_POST['custom_field2']; $error = array(); if($name=='') { $error[] = 'Name are mandatory'; } if($email == '') { $error[] = 'Email are mandatory'; } if($custom_field1 == '') { $error[] = 'Custom field 1 is mandatory'; } if($custom_field2 == '') { $error[] = 'Custom field 2 is mandatory'; } if (!empty($error)) { $custom_field3 = $_POST['custom_field3']; $boolean = 'true'; $postdata = http_build_query( array( 'name' => $name, 'email' => $email, 'custom_field1' => $custom_field1, 'custom_field2' => $custom_field2, 'custom_field3' => $custom_field3, 'list' => $list, 'boolean' => 'true' ) ); $opts = array('http' => array('method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata)); $context = stream_context_create($opts); $result = file_get_contents($app_url.'/signin', false, $context); if ($result != 1) $error[] = $result; } } </code></pre> <p>When you displaying the error messages, make a loop in <code>$error</code> array</p> <pre><code>foreach ($error as $errstr) { echo "<p>{$errstr}</p>"; } </code></pre> <p>or <code>implode</code> to string and echoes like</p> <pre><code>echo "<p>" . implode("</p><p>", $error) . "</p>"; </code></pre> |
21,918,427 | 0 | <p>It means if you try to serialize/deserialize more than 20 different types you will require a paid license. See the test in the source code <a href="https://github.com/ServiceStack/ServiceStack/blob/master/tests/ServiceStack.WebHost.Endpoints.Tests/LicenseUsageTests.cs#L55" rel="nofollow">here</a>. In this case 20 different types are trying to be deserialized, causing a <code>License Exception</code>.</p> <p>From you description, you should be well within the limit of the free license and not have to worry about hitting any limitations.</p> |
32,968,242 | 0 | <p>We have a project like this one before. You need an sdk (software development kit) to go to your device. Add that to your project references so you can communicate with it. And I believe there is a sample code in the SDK site that you could find in the case of your finger print reader which you could modify. <br/><br/>Anyway here is our sample code for saving fingerprint directly in the database.</p> <pre><code>private void SaveButton_Click(object sender, EventArgs e) { MemoryStream fingerprintData = new MemoryStream(); Template.Serialize(fingerprintData); fingerprintData.Position = 0; BinaryReader br = new BinaryReader(fingerprintData); Byte[] bytes = br.ReadBytes((Int32)fingerprintData.Length); //Insert the file into database SqlConnection cn = new SqlConnection("Data Source=10.115.5.3; Initial Catalog=EnrollmentSampledb;Integrated Security=SSPI;"); SqlCommand cmd = new SqlCommand("INSERT INTO tblUser VALUES(@ID_NUMBER, @FIRSTNAME, @LASTNAME, @FINGERPRINT, @DATE_ADDED, @DATE_MODIFIED)", cn); cmd.Parameters.Add("ID_NUMBER", SqlDbType.NVarChar).Value = tboxIdNum.Text; cmd.Parameters.Add("FIRSTNAME", SqlDbType.NVarChar).Value = tboxFname.Text; cmd.Parameters.Add("LASTNAME", SqlDbType.NVarChar).Value = tboxLname.Text; cmd.Parameters.Add("FINGERPRINT", SqlDbType.Image).Value = bytes; cmd.Parameters.Add("DATE_ADDED", SqlDbType.DateTime).Value = DateTime.Now; cmd.Parameters.Add("DATE_MODIFIED", SqlDbType.DateTime).Value = DateTime.Now; cn.Open(); cmd.ExecuteNonQuery(); cn.Close(); tboxIdNum.Text = ""; tboxFname.Text = ""; tboxLname.Text = ""; } </code></pre> <p>see also my similar question <a href="http://stackoverflow.com/questions/17335769/how-to-save-a-fingerprint-directly-in-the-database-using-digitalpersona-sdk">here</a> for saving fingerprint directly in the database.</p> |
26,324,565 | 0 | <p>Yes, it is safe. From [6.5.9] of the C99 standard (emphasis mine):</p> <blockquote> <p><strong>Two pointers compare equal if and only if</strong> both are null pointers, <strong>both are pointers to the same</strong> object (including a pointer to an object and a subobject at its beginning) or <strong>function</strong>, both are pointers to one past the last element of the same array object, or one is a pointer to one past the end of one array object and the other is a pointer to the start of a different array object that happens to immediately follow the first array object in the address space.</p> </blockquote> |
21,984,294 | 0 | <p>I'm no expert in ActiveMQ, but I'm one of the developers of the HiveMQ MQTT broker, which is also written in Java. We have an OpenSource Plugin SDK, which allows to customize the authentication of clients and the authorization of clients to publish/subscribe to the broker. You can use a relational database or any other kind of service that is accessable from within Java to determine if a certain client is allowed to publish or subscribe to a topic. Clients can be restricted by topic, activity (publish/subscribe) and QoS.</p> <p>More information how it works can be found in the HiveMQ Plugin developers guide [1] [2].</p> <p>Cheers, Chris</p> <p>[1] <a href="http://www.hivemq.com/docs/plugins/1.4.0/#auth-permission-chapter" rel="nofollow">http://www.hivemq.com/docs/plugins/1.4.0/#auth-permission-chapter</a></p> <p>[2] <a href="http://www.hivemq.com/docs/plugins/1.4.0/#client-authorization-chapter" rel="nofollow">http://www.hivemq.com/docs/plugins/1.4.0/#client-authorization-chapter</a></p> |
25,845,536 | 0 | Trait to check if some specialization of template class is base class of specific class <p>There is <code>std::is_base_of</code> in modern STL. It allow us to determine whether the second parameter is derived from first parameter or if they are the same classes both or, otherwise, to determine is there no such relation between them.</p> <p>Is it possible to determine whether the one class is derived from some concrete template class without distinction of which concrete actual parameters involved to its specialization?</p> <p>Say, we have;</p> <pre><code>template< typename ...types > struct B {}; </code></pre> <p>And</p> <pre><code>template< typename ...types > struct D : B< types... > {}; </code></pre> <p>Is it possible to define a type trait:</p> <pre><code>template< typename T > is_derived_from_B; </code></pre> <p>Such that it is derived from <code>std::true_type</code> when <code>T</code> is any specialization of <code>D</code> and derived from <code>std::false_type</code> if <code>T</code> is not derived from any specialization of <code>B</code>?</p> |
32,172,238 | 0 | <p>You already got it, you just needed to create the container for the output (the <code>numnights</code> element). </p> <p>Anyway the code is a little bit cleaner in this way:</p> <hr> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function(){ $(".daypicker").on('change', function(){calculateNights();}); }); function calculateNights() { var arrivalday = $("#arrivalday").val(); var departureday = $('#departureday').val(); var numberNights = departureday - arrivalday; numberNights = (numberNights < 1) ? numberNights + 7 : numberNights; $("#numNights").html(numberNights); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select required="required" class="daypicker" id="arrivalday" name="arrivalday"> <option></option> <option value="1">Monday</option> <option value="2">Tuesday</option> <option value="3">Wednesday</option> <option value="4">Thursday</option> <option value="5">Friday</option> <option value="6">Saturday</option> <option value="7">Sunday</option> </select> <select required="required" class="daypicker" id="departureday" name="departureday"> <option></option> <option value="1">Monday</option> <option value="2">Tuesday</option> <option value="3">Wednesday</option> <option value="4">Thursday</option> <option value="5">Friday</option> <option value="6">Saturday</option> <option value="7">Sunday</option> </select> <hr> <div id="numNights"></div></code></pre> </div> </div> </p> <p>Hope it helps!</p> |
23,627,627 | 0 | C++ copy constructor, assignment 'operator=' <p>I'm trying to make a copy constructor or = operator. If I define a matrix named A, another as B and C and use the '=' operator as:</p> <p>A=B</p> <p>it performs well, However if i use like: </p> <p>A=B+C i get this error: no matching function for '='. </p> <p>The point is when I change the symbol(=) to (==) it works well,even in the case of A == B+C, however by using only the equality sign(=) it doesn't work! any ideas?</p> <p>In the header file:</p> <pre><code>Simple2DMatrixD (const Simple2DMatrixD& matrixA) { numRows = matrixA.numRows; numCols = matrixA.numCols; dataArray = new double[numRows * numCols]; for (int iX = 0; iX < numRows; iX++) { for (int iY = 0; iY < numCols; iY++) { dataArray[(iX * numRows) + iY] = matrixA.getElement(iX,iY) ; } } } Simple2DMatrixD & assign (const Simple2DMatrixD & matrixB); Simple2DMatrixD & sum (const Simple2DMatrixD & matrixA, const Simple2DMatrixD & matrixB); </code></pre> <p>// ADDITION OPERATOR</p> <pre><code>friend Simple2DMatrixD operator+ (Simple2DMatrixD & matrixA, Simple2DMatrixD & matrixB) { Simple2DMatrixD matrixTemp(matrixA.numRows, matrixA.numCols); matrixTemp.sum(matrixA, matrixB); return (matrixTemp); } </code></pre> <p>// ASSIGNMENT OPERATOR</p> <pre><code>Simple2DMatrixD & operator= (const Simple2DMatrixD & matrixB) { this->assign(matrixB); return (*this); } </code></pre> <p>// and in the source file:</p> <pre><code>Simple2DMatrixD & Simple2DMatrixD::assign (const Simple2DMatrixD & matrixB) { for (int r = 0; r < numRows; r++) { for (int c = 0; c < numCols; c++) { this->setElement(r, c, matrixB.getElement(r, c)); } } return (*this); } </code></pre> <p>// MATRICES ADDITION</p> <pre><code>Simple2DMatrixD & Simple2DMatrixD::sum (const Simple2DMatrixD & matrixA, const Simple2DMatrixD & matrixB) { // TODO REPLACE WITH COMPAREDIMENSION FUNCTION if ((this->numRows == matrixB.numRows) && (this->numCols == matrixB.numCols) ) { for (int r = 0; r < matrixA.numRows; r++) { for (int c = 0; c < matrixA.numCols; c++) { this->setElement(r, c, matrixA.getElement(r, c) + matrixB.getElement(r, c)); } } return (*this); } else { throw " Dimensions does not match!"; } } </code></pre> |
40,264,523 | 0 | Why does 5/2 results in '2' even when I use a float? <p>I entered the following code (and had no compiling problems or anything):</p> <pre><code>float y = 5/2; printf("%f\n", y); </code></pre> <p>The output was simply: <code>2.00000</code></p> <p>My math isn't wrong is it? Or am I wrong on the / operator? It means divide doesn't it? And 5/2 should equal 2.5?</p> <p>Any help is greatly appreciated!</p> |
11,829,740 | 0 | <p>You can use one of the libraries which allow you to create and manipulate Excel files, like <a href="http://epplus.codeplex.com/" rel="nofollow">EPPlus</a> (open source) or <a href="http://www.aspose.com/" rel="nofollow">Aspose</a> (commercial). I have a positive experience with the latter.</p> |
30,921,360 | 1 | Creating graph vertices from numpy array <p>I have a numpy array full of values that I would like to create vertices from for every point in the array. I am using networkx as my graphing support method(documentation here: <a href="http://networkx.github.io/documentation/latest/tutorial/" rel="nofollow">http://networkx.github.io/documentation/latest/tutorial/</a> )</p> <p>I would like to treat each element within the array as a pixel location and create a vertex instance at each location. This is easy using a simple for loop:</p> <pre><code>new=np.arange(16) gnew=nx.Graph() for x in new: if new[x]>0: gnew.add_node(x) h=gnew.number_of_nodes() print h </code></pre> <p>And as expected, 15 nodes will be printed. However, this becomes more tricky when you have identical values. For example:</p> <pre><code>new=np.ones(16) gnew=nx.Graph() for x in new: if new[x]>0: gnew.add_node(x) h=gnew.number_of_nodes() print h </code></pre> <p>Now, because all values are identical-(1), only one node will be added to the graph. Is there a way to circumnavigate this?</p> |
9,421,462 | 0 | <p>Spring 3 introduced the Converter SPI which makes this quite easy. Have a look at 6.5 in the <a href="http://static.springsource.org/spring/docs/current/spring-framework-reference/html/validation.html#beans-beans-conversion" rel="nofollow">documentation</a> </p> <p>Taking source from the docs and putting in your country, you would do something like </p> <pre><code>package my.converter; final class StringToCountry implements Converter<String, Country> { public Country convert(String source) { return // whatever you do to get a country from your string } } </code></pre> <p>Then in the xml config you would configure the converter</p> <pre><code><bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"> <property name="converters"> <list> <bean class="my.converter.StringToCountry"/> </list> </property> </bean> </code></pre> <p>As GriffeyDog pointed out, you may want to put the country id in for the select path so you can get the Country by ID or something instead of whatever is returned by toString() of your Country object.</p> |
35,065,421 | 0 | Evaluate all formulas in a Workbook object <p>I want to evaluate all formulas in a Workbook object. I know there are XSSFFormulaEvaluator and HSSFFormulaEvaluator for evaluating formulas in XSSFWorkbook and HSSFWorkbook. But the workbook object I have belongs to Workbook class.</p> <p>I can use something like this,</p> <pre><code>XSSFFormulaEvaluator.evaluateAllFormulaCells((XSSFWorkbook) workbook); </code></pre> <p>Is it ok to use this evaluator? Does it have any side effects to type-casting Workbook to XSSFWorkbook?</p> |
35,686,500 | 0 | How to define member class operator based on the class parameters <p>Is it possible to define different = operators for different template arguments. Let's assume that I want to use different methods for converting arguments of different types:</p> <pre><code>template <class T,class U> class cTest { private: public: T x; U y; //typical case cTest<T,U>& operator =(const cTest<T,U> &that) { return *this; } //operator = based on the LHS type 1 cTest<uint16_t,U>& operator =(const cTest<int,U> &that) { cout<<"cTest<uint16_t,U>& operator =(const cTest<int,U> &that)"<<endl; return cTest<uint16_t,U>(); } //operator = based on the LHS type 2 cTest<uint8_t,U>& operator =(const cTest<int,U> &that) { cout<<"cTest<uint8_t,U>& operator =(const cTest<int,U> &that)"<<endl; return cTest<uint16_t,U>(); } }; </code></pre> |
7,289,721 | 0 | Using resources across classes? <p>I have a GameLoop class with a ParticleSystem object defined in it.</p> <p>The ParticleSystem contains an array of Particle objects - I don't want to have to load an image for each individual particle, id like to just be able to draw from a source image in the GameLoop class - how can I do this in an efficient manner?</p> <p><strong>SOLUTION:</strong></p> <p>Here is what Dan S helped me come up with:</p> <pre><code>public class ResourceManager { Context mContext; public final HashMap<String, Bitmap> Texture = new HashMap<String, Bitmap>(); //Constructor public ResourceManager(Context context) { mContext = context; Texture.put("particle1", loadBitmap(R.drawable.particle1)); } public Bitmap getBitmap(String key) { return Texture.get(key); } /** Load an image */ protected Bitmap loadBitmap(int id) { return BitmapFactory.decodeResource(mContext.getResources(), id); } } //End ResourceManager </code></pre> <p>then define it in a class:</p> <pre><code>rm = new ResourceManager(mContext); </code></pre> <p>And then pass the rm variable down the way:</p> <pre><code> ParticleSystem.Draw(rm, canvas); { Particle.Draw(rm, canvas); } </code></pre> <p>and in Particle class, there is a String assetKey I set in constructor - so that I can refer to the Bitmap by a name:</p> <pre><code>public void doDraw(ResourceManager rm, Canvas canvas) { canvas.drawBitmap(rm.getBitmap(AssetKey), xpos, ypos, null); } </code></pre> <p>I hope this is helpful to someone else also.</p> |
20,021,366 | 0 | Regex - matching a multiline block by noting the absence of a string and then inserting it <p>What a mouthful of a subject. </p> <p>So in essence I have a pattern I need to find in a file based on that pattern missing something.</p> <p>For example what I HAVE is:</p> <pre><code>Huge amounts of preceding code... someHeader { someInfo = "blah blah blah"; } Huge amounts of ending code... </code></pre> <p>What I need to do is make it look like this:</p> <pre><code>someHeader { someDescription = "Excellent information found here!"; someInfo = "blah blah blah"; } Huge amounts of ending code... </code></pre> <p><strong>The bottom line:</strong> I need to find all instances of the "someHeader" block that do not have a "someDescription" and insert it. "someInfo" will not always be there either so I really need to find every instance of <code>"someheader\r\t\t{\r\t\t\t!someDescription"</code> and replace it with <code>"someheader\r\t\t{\r\t\t\tsomeDescription = "Excellent information found here!";\r"</code></p> <p>I really am at a loss and have been banging on this for about a day. I have attempted <a href="/questions/tagged/sed" class="post-tag" title="show questions tagged 'sed'" rel="tag">sed</a>, <a href="/questions/tagged/awk" class="post-tag" title="show questions tagged 'awk'" rel="tag">awk</a>, <a href="/questions/tagged/perl" class="post-tag" title="show questions tagged 'perl'" rel="tag">perl</a> and am dorking around with <a href="/questions/tagged/c%23" class="post-tag" title="show questions tagged 'c#'" rel="tag">c#</a> right now.</p> |
26,771,465 | 0 | <p>It turned out to be a CORS issue. Opera 12.17 seems to be very restrictive when it comes to CORS. I moved the app and all the necessary resources into one domain and it works as it should. Note * this issue only happens with Opera 12.17 , later versions seem to work.</p> |
3,796,740 | 0 | <p>In this <a href="http://mindprod.com/jgloss/hashcode.html" rel="nofollow">link</a> it says that indeed the default hash code is the JVM address of the object, but if it is moved - the address stays consistent. I don't know how reliable this source is, but I am sure that the implementors of this method thought of this scenario (which is not rare or corner case), and ensured correct functionality of this method.</p> |
6,522,747 | 0 | <p>A minor shuffle to trigger the <code>hide()</code> on the last callback for the <code>each()</code> you've got going should do the trick.</p> <pre><code>elsCheck = $(".treeclick", "#treegrid"); $("#expandAll").click(function(e){ $('#collapseExpandProgress').show(); elsCheck.each(function(i){ if ($(this).hasClass("tree-plus")) { $(this).trigger("click"); } if (i==(elsCheck.length-1)){ $('#collapseExpandProgress').hide(); } }); }); </code></pre> |
21,871,726 | 0 | Accessing a jobjectarray in C++ <pre><code>JNIEXPORT void JNICALL Java_com_beantowngameshop_bingoshoot_api_ApslarHandler_sendEvent (JNIEnv *, jobject, jobjectArray); </code></pre> <p>The jobjectArray is object array of my java class that has two attributes </p> <p>1) A String 2) A Integer</p> <p>I want to iterate and read the values of this array ? Can anyone please show me how ? </p> |
31,578,621 | 0 | <p>The plain <code>for loop</code> way:</p> <pre><code>T max_e = std::numeric_limits<T>::min(); for(const auto& v: vv) { for(const auto& e: v) { max_e = std::max(max_e, e); } } </code></pre> |
2,667,088 | 0 | <p>Hmm its a good question.</p> <p>Anything that can be displayed can be rendered using an instance of <code>WriteableBitmap</code> and its <code>Render</code> method. You can access the output using the <code>Pixels</code> byte array property. </p> <p>However (assuming GPU acceleration is turned on and the content is appropriately marked to make use of the GPU) whether such a render will actually make use of the GPU when going to a <code>WriteableBitmap</code> instead of the display I don't know. </p> |
19,308,956 | 0 | <p>Thank you for your assistance. After many hours, I figured I had to use setTitle().</p> |
4,894,964 | 0 | Flash mp3 player throws Error 2032 - Thinking URLRequest is the culprit? <p>I am trying to set up an audio player for a website I am working on, and I keep running into this Error 2032. The .swf is located in my main folder along with my songlist file. The song files themselves are located in a subfolder called songs/</p> <p>I am not sure what could be causing this, and any input would be helpful.</p> <p> </p> <pre><code><fx:Script> <![CDATA[ import mx.collections.ArrayCollection; import mx.collections.ArrayList; import mx.collections.XMLListCollection; import mx.controls.Alert; import mx.rpc.events.FaultEvent; import mx.rpc.events.ResultEvent; import mx.utils.ArrayUtil; private var sound:Sound; // Mp3 File private var soundChannel:SoundChannel; // Reference to playing channel private var pausePosition:Number; // Current play position (time) private var percent:Number; // Current played percentage private var isPlaying:Boolean = false; // Is the mp3 playing? private var isLoaded:Boolean = false; // Is the mp3 loaded? //private var updateSeek:Timer = new Timer(500); // Timer for updating the seek bar private var currentSong:String; private var index:int; private var start:Boolean = true; private var songs:Array; private function init():void { grabSongs(); } private function grabSongs():void{ var theLoader:URLLoader = new URLLoader(); var theRequest:URLRequest = new URLRequest("songlist.txt"); theLoader.load(theRequest); theLoader.addEventListener(Event.COMPLETE, loadComplete); } private function loadComplete(theEvent:Event):void{ songs = theEvent.target.data.split("\n"); currentSong = songs[0]; index = 0; } private function playPause(e:Event = null):void { // Song playing? if(isPlaying) { // Save the current position in the track, stop playback, change button icon pausePosition = soundChannel.position; soundChannel.stop(); this.btnPlay.label = "Play"; // If the URL has been changed but not loaded, hide seekbar // Song is not playing? } else { if(!isLoaded) { // If the song isn't loaded yet, set up a new sound load request if(start == true){ start = false; } sound = new Sound(); sound.load(new URLRequest("songs/" + currentSong)); // Add an event listener to check for song load complete event sound.addEventListener(Event.COMPLETE, songLoaded); this.btnPlay.label ="Pause"; } else { // The song IS loaded, so play it soundChannel = sound.play(pausePosition); this.btnPlay.label = "Pause"; } } // Regardless of playing state, change it now to the opposite isPlaying = !isPlaying; } private function songLoaded(e:Event):void { // Remove load event listener sound.removeEventListener(Event.COMPLETE, songLoaded); // Play the song soundChannel = sound.play(0); // Song is loaded isLoaded = true; } private function prev(e:Event = null):void { if(start == false){ if(index == 0){ index = songs.length - 1; }else{ index--; } currentSong = songs[index]; isPlaying = true; isLoaded = false; playNew(e); } } private function next(e:Event = null):void { if(start == false){ if(index == songs.length - 1){ index = 0; }else{ index++; } currentSong = songs[index]; isPlaying = true; isLoaded = false; playNew(e); } } private function playNew(e:Event = null):void { soundChannel.stop(); sound = new Sound(); sound.load(new URLRequest("songs/" + currentSong)); // Add an event listener to check for song load complete event sound.addEventListener(Event.COMPLETE, songLoaded); this.btnPlay.label = "Pause"; } ]]> </fx:Script> <s:Button id="btnPrev" label="Previous" chromeColor="#000000" focusColor="#000000" color="#8D1111" enabled="true" click="{prev(event)}" height="20" width="80" x="0" y="0"/> <s:Button id="btnPlay" label="Play" chromeColor="#000000" focusColor="#000000" color="#8D1111" enabled="true" click="{playPause(event)}" height="20" width="80" x="81" y="0"/> <s:Button id="btnNext" label="Next" chromeColor="#000000" focusColor="#000000" color="#8D1111" enabled="true" click="{next(event)}" height="20" width="80" x="162" y="0"/> </code></pre> <p></p> <p>This works locally on my laptop, but when I upload the swf it throws error 2032.</p> <p>Thanks</p> <p><strong>Update</strong></p> <p>So the setup is exactly as FlexFiend answered, along with <a href="http://localhost/FlexStuff/songs/" rel="nofollow">http://localhost/FlexStuff/songs/</a> I tried checking the log file of the flash debugger and this was my message:</p> <p>Error #2032: Stream Error. URL: <a href="http://www.mywebsite.com/framework_4.0.0.14159.swf" rel="nofollow">http://www.mywebsite.com/framework_4.0.0.14159.swf</a></p> <p>I am very unfamiliar with what this means, but maybe its causing my problems?</p> |
6,127,528 | 0 | Converting from Windows 1252 to UTF8 in Java: null characters with CharsetDecoder/Encoder <p>I know it's a very general question but I'm becoming mad. </p> <p>I used this code:</p> <pre><code>String ucs2Content = new String(bufferToConvert, inputEncoding); byte[] outputBuf = ucs2Content.getBytes(outputEncoding); return outputBuf; </code></pre> <p>But I read that is better to use CharsetDecoder and CharsetEncoder (I have contents with some character probably outside the destination encoding). I've just written this code but that has some problems:</p> <pre><code>// Create the encoder and decoder for Win1252 Charset charsetInput = Charset.forName(inputEncoding); CharsetDecoder decoder = charsetInput.newDecoder(); Charset charsetOutput = Charset.forName(outputEncoding); CharsetEncoder encoder = charsetOutput.newEncoder(); // Convert the byte array from starting inputEncoding into UCS2 CharBuffer cbuf = decoder.decode(ByteBuffer.wrap(bufferToConvert)); // Convert the internal UCS2 representation into outputEncoding ByteBuffer bbuf = encoder.encode(CharBuffer.wrap(cbuf)); return bbuf.array(); </code></pre> <p>Indeed this code <strong>appends to the buffer a sequence of null character</strong>!!!!!</p> <p>Could someone tell me where is the problem? I'm not so skilled with encoding conversion in Java. </p> <p>Is there a better way to convert encoding in Java?</p> |
20,852,884 | 0 | PHP passing model as a function argument <p>I'm using the Laravel Framework and I've got <code>MyModel</code>.</p> <pre><code>namespace App\Models; use Illuminate\Support\Facades\DB; class MyModel extends \Eloquent { //Some stuff goes here } </code></pre> <p>I have made this function that group the data of an array. <strong>This is working well.</strong></p> <pre><code>public static function GroupBy($array, $key){ $grouped = array(); foreach($array as $arr){ if(!array_key_exists($arr->MyModel['id'], $grouped)){$grouped[$arr->MyModel['id']] = array();} array_push($grouped[$arr->MyModel['id']], $arr[$key]); } return $grouped; } </code></pre> <p><strong>Now I wish to make this function more generic by passing the model by which my grouping is made. In order word I'd like to be able to pass <code>MyModel['id']</code> as another argument.</strong> Something like:</p> <pre><code>$by = "MyModel['id']"; public static function GroupBy($by, $array, $key){ $grouped = array(); foreach($array as $arr){ if(!array_key_exists($arr->$by, $grouped)){$grouped[$arr->$by] = array();} array_push($grouped[$arr->$by], $arr[$key]); } return $grouped; } </code></pre> <p>This last solution doesn't work. It returns me an array with an array containing all the <code>id</code>.</p> |
20,918,211 | 0 | <pre><code>function mom_get_first_image() { global $post; if(preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches)) $first_img = $matches[1][0]; else $first_img = "images/logo.png"; return $first_img; } </code></pre> |
12,456,714 | 0 | google distance Matrix api v3 showing error <p>I am trying to calculate the rates of the taxi fare from the distance of two locations using google distance matrix app.</p> <p>I created a new project, enabled the Google Maps Api V2 & V3 from the services, copied the api key from Simple API Access</p> <pre><code><script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=MY_AppS_KeY&sensor=false"> </script> </code></pre> <p>But I am getting errors like</p> <pre><code>Google has disabled use of the Maps API for this application. The provided key is not a valid Google API Key, or it is not authorized for the Google Maps Javascript API v2 on this site. If you are the owner of this application, you can learn about obtaining a valid key here: http://code.google.com/apis/maps/documentation/javascript /v2/introduction.html#Obtaining_Key </code></pre> <p>If i go back to my old apps key, i get following error:</p> <pre><code>This web site needs a different Google Maps API key. A new key can be generated at http://code.google.com/apis/maps/documentation/javascript /v2/introduction.html#Obtaining_Key. </code></pre> <p>Can any one Please Help</p> <p>The script i used is as follows:</p> <pre><code><?php $rate=20; $extra=0; ?> <head> <script type="text/javascript"src="http://maps.googleapis.com/maps/api /js?key=AIzaSyD0TzSohrtPSgWRQx8BhKryZKsjqQQH65Q&sensor=true"></script> <script type="text/javascript"> var geocoder, location1, location2, gDir; var map; var gdir; var geocoder = null; var addressMarker; var directionsPanel; var directions; function initialize() { geocoder = new GClientGeocoder(); gDir = new GDirections(); GEvent.addListener(gDir, "load", function() { var drivingDistanceMiles = gDir.getDistance().meters / 1609.344; var drivingDistanceround = Math.round(drivingDistanceMiles*100)/100; //if (40>drivingDistanceMiles) //{ var cost = ((drivingDistanceMiles * <?php echo $rate; ?>) + (<?php echo $extra; ?>)) //} /*else { var cost = ((drivingDistanceMiles * <?php echo $rate; ?>) + (<?php echo $extra; ?>)) }; */ //var cost2 = cost + (cost * .0675); //var fare = Math.round(cost2*100)/100; var fare=cost; var fare = Math.round(fare*100)/100; document.getElementById('results').innerHTML = '<table width="100%" style="border-collapse:collapse; padding-top:3px;"><tr><td rowspan="2" width="35"><img src="images/rates.png"></td><td><strong>Distance: </strong>' + drivingDistanceround + ' miles</td></tr><tr><td><strong>Estimated Cost: </strong>$ ' + fare + '</td></tr></table>'; }); if (GBrowserIsCompatible()) { map = new GMap2(document.getElementById("map_canvas")); map.setCenter(new GLatLng(-33.722626, 150.810585), 10); gdir = new GDirections(map, document.getElementById("directions")); //directionsPanel = document.getElementById("route"); //directions = new GDirections(map, directionsPanel); //directions.load("from: "+ document.forms[0].from.value +" to: "+ document.forms[0].to.value+""); //directions.load("from: 500 Memorial Drive, Cambridge, MA to: 4 Yawkey Way, Boston, MA 02215 (Fenway Park)"); //directions.load("from: "+document.locations.to.value+" to: "+document.locations.to.value+""); GEvent.addListener(gdir, "load", onGDimrectionsLoad); GEvent.addListener(gdir, "error", handleErrors); } } function setDirections(fromAddress, toAddress, locale) { gdir.load("from: " + fromAddress + " to: " + toAddress); } function showLocation() { geocoder.getLocations(document.forms[0].from.value, function (response) { if (!response || response.Status.code != 200) { alert("Sorry, we were unable to geocode the first address"); } else { location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address}; geocoder.getLocations(document.forms[0].to.value, function (response) { if (!response || response.Status.code != 200) { alert("Sorry, we were unable to geocode the second address"); } else { location2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address}; gDir.load('from: ' + location1.address + ' to: ' + location2.address); } }); } }); /////////////////////////////////////////////////////////// var directionsPanel; var directions; directionsPanel = document.getElementById("route"); directions = new GDirections(map, directionsPanel); directions.load("from: "+document.forms[0].from.value+" to: "+document.forms[0].to.value); } </script> </head> <body onload="initialize()" onunload="GUnload()"> <table width="380px" border="2" cellpadding="0" cellspacing="0" bordercolor="#FF9F0F" style="border-collapse:collapse"> <tr> <td bgcolor="#FFFF99" style="padding:5px;"><table width="375px" border="0" cellspacing="0" cellpadding="0"> <tr> <td><div id="map_canvas" style="width: 374px; height: 255px; border: solid 1px #336699"></div></td> </tr> <tr> <td><div id="form" style="width:374px; text-align:center; border: solid 1px #336699; background:#d1e1e4;"> <form action="#" onsubmit="document.getElementById('route').innerHTML=''; showLocation(); setDirections(this.from.value, this.to.value); return false;"> <p style="font-family:Tahoma; font-size:8pt;">From: <input id="fromAddress" type="text" onblur="if(this.value=='') this.value=this.defaultValue;" onfocus="if(this.value==this.defaultValue) this.value='';" value="Street Name City, State" maxlength="50" size="26" name="from" style="font- family:Tahoma; font-size:8pt;" /> To: <input id="toAddress" type="text" onblur="if(this.value=='') this.value=this.defaultValue;" onfocus="if(this.value==this.defaultValue) this.value='';" value="Street Name City, State" maxlength="50" size="26" name="to" style="font- family:Tahoma; font-size:8pt;"/> <input class="submit" name="submit" type="submit" value="Calculate" style="font-family:Tahoma; font-size:8pt;" /> </p> <div id="results" style="font-family:Tahoma; font-size:8pt; text-align:left; padding-left:5px; padding-bottom:5px;"></div> <div id="route" style="font-family:Tahoma; display:none; font-size:8pt; text-align:left; padding-left:5px; padding-bottom:5px;"></div><a href="../large.php" target="_top" style="font-size:13px;">click here view large map with routes</a> </form> </div></td> </tr> </table></td> </tr> </table> </body> </code></pre> |
22,447,369 | 0 | Navigation Controller to View Controller Programmatically Not Working IOS7 <p>Hi in my application i have navigation controller with registration and I'm doing the validation for my registration form if user enter a invalid data in the registration form it should not move to the next view controller and if user give the right data it should move to the next view controller but its not working.</p> <pre><code> - (IBAction)reg:(id)sender { if ([self validateEmail:[email text]]== 1 && [self phonevalidate:[phone text]]== 1 && [name.text length] <= 25 && [city.text length] <= 25 ) { pollpoliticalViewController *pollVC = [[UIStoryboard storyboardWithName:@"Main.storyboard" bundle:nil] instantiateViewControllerWithIdentifier:@"PollPoliticalVCID"]; [self.navigationController pushViewController:pollVC animated:YES]; UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"Thanks For The Registration" delegate:self cancelButtonTitle:@"ok" otherButtonTitles: nil]; [alert show]; [alert release]; }else{ UIAlertView *alert1 = [[UIAlertView alloc]initWithTitle:@"Message" message:@"you entered worng correct" delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil, nil]; [alert1 show]; [alert1 release]; } } </code></pre> <p>I used this above code for the navigating to view controller form the navigation controller programmatically but its giving error like.</p> <blockquote> <p>Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Could not find a storyboard named 'Main.storyboard'</p> </blockquote> <p>But my storyboard name is main.storyboard i don't know why its giving error like this i have tried to by chaining the storyboard name but what ever i change the its giving the same error for all please tell me how to resolve this one.</p> <p>Thanks. </p> |
32,368,447 | 1 | Default the root view in cherrypy <p>In <a href="https://github.com/metaperl/metaperl-proxy">some source code</a> I am writing, I am able to make a request such as:</p> <pre><code>http://proxy.metaperl.org/index/bitgold-rw1 </code></pre> <p>And have it redirect successfully.</p> <p>However, I want to remove <code>index</code> from the URL and have it still redirect by using the <code>index()</code> method. I tried renaming <code>index()</code> to <code>default()</code> after reading about <a href="https://cherrypy.readthedocs.org/en/3.2.6/concepts/dispatching.html">Dispatching</a>, but it still does not allow me to have a URL like this:</p> <pre><code>http://proxy.metaperl.org/bitgold-rw1 </code></pre> <p>It tries to find a method named <code>bitgold-rw1</code> instead of using the default method to resolve the request, gving me the error:</p> <pre><code>NotFound: (404, "The path '/bitgold-rw1' was not found.") </code></pre> <p>The WSGI startup file looks like this:</p> <pre><code># -*- python -*- # core import os import sys # 3rd party import cherrypy # local def full_path(*extra): return os.path.join(os.path.dirname(__file__), *extra) sys.path.insert(0, full_path()) import config import myapp application = cherrypy.Application( myapp.Root(), "/", config.config) </code></pre> |
40,997,035 | 0 | <p>@Joshua Blevins its nice to see you come to symfony and try its first ever beginners code.</p> <p>Here you have to change your <code>app.php</code> located in <strong>web</strong> folder of your project. Open and turn the false option to true, it will enable your project to run in production environment.</p> <p>Moreover every controller of symfony extended from the base controller.</p> <p>Try this:</p> <pre><code>// src/AppBundle/Controller/LuckyController.php // ... // --> add this new use statement use Symfony\Bundle\FrameworkBundle\Controller\Controller; class LuckyController extends Controller { // ... } </code></pre> <p>you can also test your rout by just <code>echo "hello world!</code>" in the controller.</p> <p>reference <a href="http://symfony.com/doc/current/page_creation.html" rel="nofollow noreferrer">Create your First Page in Symfony</a></p> |
8,662,221 | 0 | Collecting and identifying functions within an array in actionscript <p>So, I want to do something where I collect functions to be invoked later when a certain condition is met. E.g.</p> <pre><code>function doSomething(someArg:Object):void { if (conditionIsFalse){ operationsToDoWhenConditionIsTrue.push(function(){ doSomething(someArg); }); } } function onConditionBecomingTrue():void { while (operationsToDoWhenConditionIsTrue.length > 0){ operationsToDoWhenConditionIsTrue.shift()(); } } </code></pre> <p>So far so good. However at some point I want to iterate over the operationsToDoWhenConditionIsTrue and identify and replace a function. In pseudo code inside the doSomething method it would be:</p> <pre><code>function doSomething(someArg:Object):void { if (conditionIsFalse){ for (var i:int = 0; i<operationsToDoWhenConditionIsTrue; i++){ // pseudo code here if (typeof operationsToDoWhenConditionIsTrue[i] == doSomething){ operationsToDoWhenConditionIsTrue[i] = doSomething(someArg); } } } } </code></pre> <p>Basically if doSomething is called twice, I only want operationsToDoWhenConditionIsTrue to hold the most recent invocation. Obviously since the invocations are wrapped in function(){} all the functions are the same. Is there any way I can accomplish what I want?</p> |
19,766,668 | 0 | How to make a URL link to another state of the page? <p>I'd like to share a page in a state when the second link is active (e.g. "http:/ /mypage#green-color"). </p> <p>I tried to add to the second link <code>onClick="window.location='#green-color';"</code> attribute. It changes the URL in the browser's address window, but I can't share it with others.</p> <p><a href="http://jsfiddle.net/Rk3Xz/1/" rel="nofollow">code in JS Fiddle</a> </p> <pre><code><a href="#" id="all">All Colors</a> <a href="#green" id="green-color">Green Color</a> <div id="red"></div> <div id="green"></div> </code></pre> <p>Two states of the page:</p> <pre><code>$( "#all" ).click(function() { $( "#red" ).show(200); }); $( "#green-color" ).click(function() { $( "#red" ).hide(200); }); </code></pre> |
37,698,170 | 0 | What is the actual pricing for AWS ECS? <p>AWS EC2 Container Service official webpage says:</p> <blockquote> <p>There is no additional charge for Amazon EC2 Container Service. You pay for AWS resources (e.g. EC2 instances or EBS volumes) you create to store and run your application.</p> </blockquote> <p>What does that mean if I host my application that would run on the micro EC2 instance and it would have been scheduled to run only once a day. The execution would take 1 hour.</p> <p>Does it mean I pay for 1 hour or do I also pay for the EC2 instance while it's idle? Is in this case AWS Beanstalk better?</p> |
33,350,116 | 0 | <p>I thank you all for the input. I was able to fix my errors. I re-iterate through each character and strip the punctuation and i kept creating new lists to add repeated words then keep a single occurrence. The response that I have seem to work but I was not introduced to the higher order programming as yet.</p> <p>Here is the modified code:</p> <pre><code>def repeatWords(filename_1, filename_2): infile_1=open(filename_1,'r') content_1=infile_1.read() infile_1.close() import string new_content="" for char in content_1: new_content+=char.strip(string.punctuation) new_content=new_content.lower() new_content=new_content.split() repeated_list=[] for word in new_content: if new_content.count(word)>1: repeated_list.append(word) new_repeat_list=[] for item in repeated_list: while item not in new_repeat_list: new_repeat_list.append(item) outfile=open(filename_2,'w') for repeat in new_repeat_list: outfile.write(repeat) outfile.write('\n') outfile.close() infile_2=open(filename_2,'r') content_2=infile_2.read() infile_2.close() return content_2 inF = 'catInTheHat.txt' outF = 'catRepWords.txt' print(repeatWords(inF, outF)) </code></pre> |
38,368,878 | 0 | neo4j refresh pagination in cyper query <p>I have a news feed in my application and im using neo4j as database. I also use pagination with <code>SKIP</code> and <code>LIMIT</code> to pull more and more item from the database.</p> <p>Im looking for a way to "refresh" the pagination (pull to refresh. like facebook have when there are new stories for in the news feed)</p> <p>Assuming I have the Id of the first element that was returned by the query with the <code>SKIP=0</code> how can I do that?</p> |
2,432,257 | 0 | <p>Visual SourceSafe 2005 includes support for access over HTTP:</p> <blockquote> <p><strong>Remote Internet Access.</strong> This release of Visual SourceSafe introduces a new SourceSafe Internet plug-in for Visual Studio source control. The plug-in and its associated Web service enable remote Internet access to Visual SourceSafe databases over HTTP or HTTPS. The SourceSafe Internet plug-in supports the basic operations of database open, database add, check-in, checkout, and get, but does not provide rename, delete, get by time or by label, history, labeling, or share/branch functions. This plug-in is particularly helpful when you need to access your Visual SourceSafe databases when you are on the road.</p> </blockquote> <p>Articles on setting it up seem to be scarce: <a href="http://www.yafla.com/dennisforbes/Visual-SourceSafe-2005-Internet-Provider/Visual-SourceSafe-2005-Internet-Provider.html" rel="nofollow noreferrer">Visual SourceSafe 2005 Internet Provider</a>.</p> <p>Also see:</p> <ul> <li><p><a href="http://msdn.microsoft.com/en-us/library/ms181052(VS.80).aspx" rel="nofollow noreferrer">How to: Enable Internet Information Services (IIS)</a></p></li> <li><p><a href="http://msdn.microsoft.com/en-us/library/ms181053(VS.80).aspx" rel="nofollow noreferrer">How to: Set Up Secure Sockets Layer (SSL)</a></p></li> </ul> <p>But given that Visual SourceSafe 2005 will be retired from mainstream support on 12 April 2011 (with extended support ending on 12 April 2016), you might be better off going with Subversion (or similiar).</p> |
25,894,194 | 0 | <p>smallImageUrls, is inside matches that is inside the root, so you have to retrieve matches and, through it, smallImageUrls</p> <pre><code>JSONObject obj = new JSONObject(...); JSONArray matches = obj.optJSONArray("matches"); if (matches != null) { for (int i = 0; i < matchesLenght; i++) { JSONObject objAtIndex = matches.optJSONObject(i); if (objAtIndex != null) { JSONArray smallImageUrls = objAtIndex.optJSONArray("smallImageUrls"); for (int j = 0; j < smallImageUrlsSize; j++) { String urlAtIndex = smallImageUrls.optString(j); } } } } </code></pre> |
25,342,573 | 0 | RESTful API to safeguard server and client from large datasets <p>I am working on designing a RESTful API and need second opinion on the design. I will be abstracting away the problem statement for better understanding.</p> <p>Consider a URI <code>/search?key1=value1&key2=value2</code>, which can potentially return a huge result set for a given search criteria for key1 and key2. </p> <p>My mandate is to make sure that the server and client are bounded by limits to prevent performance degradation. If that limit is reached and the intended data is not found in result set, user will be asked to refine the search query to narrow down. (I am not thinking of pagination, that is for a different problem set)</p> <p>Approach is to allow client specify a limit to server that it(client) can comfortably handle, and to help server set a limit for itself to prevent from generating huge result sets affecting performance.</p> <p>Client can do <code>/search?key1=value1&key2=value2&maxresults=xxxx</code> to specify it's limit.</p> <p>Server can set it's own limit as a configuration param for search URI. While serving a request, server will take a min of (client's limit, server's limit) and generate result set satisfying the effective limit.</p> <p>The JSON generated will have a meta data part which will mention if the result was truncated or not, and the effective limit set. The client can inspect this part and ask the user to refine search if "truncated" is "true". The problem domain actually allows the user to refine to a single item.</p> <pre><code>{ "result": { "truncated": "true", "limit": "2000", "data": [ { "id": "1" }, { "id": "2" } ... { "id": "2000" } ] } } </code></pre> <p>The questions I am trying to answer are:</p> <ul> <li>Is this violating any REST principles? </li> <li>Is there a standard convention to do the same that I might follow? </li> <li>Are there good examples on public APIs that you can quote? (Jira RESTful API has a couple of examples) </li> <li>Is there any gotcha in this design which may affect us in the future?</li> </ul> <p>Any view on this will be appreciated ...</p> <p>Thanks!</p> |
35,466,556 | 0 | Filtering an object based on its values using lodash <p>How would I use lodash to get the following output ?</p> <pre><code>input = { 'property1' : true, 'property2' : false, 'property3' : false } // only pick those properties that have a false value output = ['property2', 'property3']; </code></pre> <p>I currently have the following in place:</p> <pre><code>var output = []; _.forEach(input, (value, key) => { if (value === false) { output.push(key); } }); </code></pre> |
31,077,760 | 0 | <p>if you just want a quick implementation i might recommend putting something like {{title}} in your html template, and configuring and using $rootScope.title to update this value from each of your controllers.</p> <p>implementation would be something like this plus the update to your template.</p> <pre class="lang-js prettyprint-override"><code>angular.module('myApp', []) .run(function($rootScope) { $rootScope.title = ""; }) .controller('myCtrl', function($scope, $rootScope) { $rootScope.title = "Navigation Bar Title" }) </code></pre> <p>but i think that a better way to do it would actually be to create a state for your navigation bar and make each of your current states a different child state of your navigation state. Because of scope inheritance you would have access to the navigation states $scope.title in any nested child state.</p> <p>here is a good place to learn how that should work.</p> <p><a href="https://github.com/angular-ui/ui-router/wiki/Nested-States-%26-Nested-Views#inherited-custom-data" rel="nofollow">https://github.com/angular-ui/ui-router/wiki/Nested-States-%26-Nested-Views#inherited-custom-data</a></p> |
11,134,993 | 0 | Sumproduct with Substitute <p>I have a range, containing numeric values & blank cells. Some of the numeric values will have * as suffix.</p> <pre><code>10* 5 7 9 25* 10 </code></pre> <p>When I do a SUM(A1:A8), I get result of 5+7+9+10 = 31, the required output. Now, I also require the total sum irrespective of * suffix. I'm trying to solve by using</p> <pre><code>SUMPRODUCT(SUBSTITUTE(A1:A8,"*","")) </code></pre> <p>It works out to</p> <pre><code>SUMPRODUCT({"10","5","7","","9","","25","10"}) </code></pre> <p>And outputs 0 since all are text values. When I use </p> <pre><code>SUMPRODUCT(value(SUBSTITUTE(A1:A8,"*",""))) </code></pre> <p>It works out to </p> <pre><code>SUMPRODUCT({10,5,7,#VALUE!,9,#VALUE!,25,10}) </code></pre> <p>and finally outputs #Value!. Can someone help me to solve this? Thanks for your time.</p> |
37,844,112 | 0 | <p>You can loop through the latlongs for the user and location off to a function that calculates distance based on the Haversine formula:</p> <p>In your controller, after loading your data:</p> <pre><code>angular.forEach(results, function(s) { store['dist'] = getDistanceInM(user_lat, user_lon, store['store_latitude'], store['store_longitude']); }) </code></pre> <p>These functions can be either in your controller or in a service:</p> <pre><code> var getDistanceInM = function(lat1, lon1, lat2, lon2) { var R = 6371; var dLat = deg2rad(lat2 - lat1); var dLon = deg2rad(lon2 - lon1); var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.sin(dLon / 2) * Math.sin(dLon / 2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); var d = R * c * 1000; return parseInt(d, 10); }; var deg2rad = function(deg) { return deg * (Math.PI / 180); }; </code></pre> <p>In your view:</p> <pre><code><ion-item ng-repeat="item in data.stores | orderBy:'dist'"> </code></pre> |
27,542,562 | 0 | <p>This replaces the last character of a url if it is a '/'</p> <pre><code>concat(LEFT(url, LENGTH(url)-1),replace(right(url, 1),'/','')) </code></pre> |
28,439,200 | 0 | Developing a testing tool <p>I am developing a testing tool. Is it possible to add JUnit functionality to a java application so that the application (itself) can run test cases against a specified java code. In a more specific way, the application takes a folder of test cases, and the code to be tested, it then runs the test cases against that code.</p> <p>if it is possible, what is the required libraries to include in the application?</p> <p>Thanks.</p> |
36,156,921 | 0 | <p>Adding a space to the end of a string is as simple as just using <code>+</code>:</p> <pre><code>string = 'a' new_string = string + ' ' </code></pre> <p>So you just need to iterate each item in your list and append the space:</p> <pre><code>for string in sliced: print string + ' ' </code></pre> <p>So could just create a new list with a simple list comprehension</p> <pre><code>new_sliced = [slice + ' ' for slice in sliced] </code></pre> <p>Or alternatively, if you want to change the <code>sliced</code> list in place you could use the enumerate builtin to get the index of each element of your list</p> <pre><code>for i, slice in enumerate(sliced): sliced[i] = slice + ' ' </code></pre> |
2,846,471 | 0 | <p>Look at the Unicode <a href="http://www.fileformat.info/info/unicode/category/index.htm" rel="nofollow noreferrer">character categories</a>. You can match these in C# regular expressions with the character class syntax <code>\p{catname}</code>. So to match a lower-case letter, you would use <code>\p{Ll}</code>. You can combine these. <code>[\p{Ll}\p{Lu}]</code> matches characters in either the Ll or Lu class.</p> |
16,341,128 | 0 | <p>I think I basically did what prodigitalson suggested...</p> <p>I <code>include()</code> a call to a php file that inserts a new shot(same query as in my question)</p> <p>Then I <code>include()</code> another call to another php file that selects this new row I just inserted and assigns each column of the result row into variables and then into session variables</p> <p>Then the session variables are used in my script that uploads the image to my server with the <code>image filename</code> and also creates a thumbnail image based on my <code>shrunk image filename</code>.</p> |
5,634,487 | 0 | If A extends B extends C, why can I cast to A but get a ClassCastException casting to C? <p>I am trying to read an ASN1 object using Bouncycastle on Android. I expect it to be a DERSequence, which in Bouncycastle is a subclass of ASN1Sequence, which is a subclass of ASN1Object.</p> <pre><code>import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.DERSequence; ... ASN1InputStream ais = ...; Object o = ais.readObject(); // Eclipse's debugger now says o is a DERSequence, as expected. DERSequence o2 = (DERSequence)o; ASN1Sequence o3 = o2; ASN1Object o4 = o3; // And o4 is now exactly what I want. ASN1Object o5 = (ASN1Object)o; // But this throws: /// java.lang.ClassCastException: org.bouncycastle.asn1.DERSequence </code></pre> <p>Based on feedback from the answers, I have constructed another, shorter example:</p> <pre><code>Object o = new DERSequence(); ASN1Object o1 = new DERSequence(); // This behaves fine. ASN1Object o2 = (ASN1Object)o; // Throws ClassCastException. </code></pre> <p>What causes this cast to fail?</p> |
19,554,136 | 0 | <p>Because the code you have posted is not the same that the code you are trying to compile.</p> <p>The following line</p> <pre><code>void function1(std::ostream&, const std::string&, double function2(const infocontainer&, const std::string&), const infocontainer, const infocontainer); </code></pre> <p>is missing a <code>const</code> before <code>std::string &</code> in the third parameter in the code you are trying to compile.</p> |
20,814,433 | 0 | <pre><code>strtr($str, ['<' => '', '.' => '']); </code></pre> <p>This will probably outperform anything else, because it doesn't require you to iterate over anything in PHP.</p> |
18,130,746 | 0 | <p>Read each line one by one with <a href="http://en.cppreference.com/w/c/io/fgets" rel="nofollow"><code>fgets</code></a> then split them with <a href="http://en.cppreference.com/w/c/string/byte/strtok" rel="nofollow"><code>strtok</code></a> and parse with <a href="http://en.cppreference.com/w/c/string/byte/strtol" rel="nofollow"><code>strtol</code></a>.</p> <p>Something like this:</p> <pre><code>char line[256]; int l = 0; while (fgets(line, sizeof(line), input_file)) { int n = 0; for (char *ptr = strtok(line, " "); ptr != NULL; ptr = strtok(NULL, " ")) { key1[l][n++] = strtol(ptr, NULL, 10); } l++; } </code></pre> |
4,497,541 | 0 | <p>As far as operator <code>as</code> returns <code>null</code> in failure case, variable should be a class or nullable struct:</p> <p>Meanwhile <code>cast</code> requires nothing like that and you can cast struct on struct.</p> |
12,237,281 | 0 | <p>All the bottlenecks you posted seem to be from setting the BorderWidth property on your shapes. I'm guessing you do repainting or updating the layout of the shapes in BorderWidth. If you set BorderWidth on a container there will a lot of unnecessary repaints and layout changes which are kind of slow in WinForms (specially for layouts, if your shapes inherit from Control).</p> <p>Might I suggest a <em>BeginUpdate</em> *EndUpdate* mechanism like some other WinForms controls?</p> |
38,932,505 | 0 | <p>Try this ;)</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function() { $('.bg-primary').on('click', function() { $('.' + $(this).attr('id')).slideToggle(); }).css('cursor', 'pointer'); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.hide { display: none; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table border="1"> <thead> <tr class="btn-info"> <th>header</th> <th>header</th> </tr> </thead> <tr id="main1" class="bg-primary"> <td>maintext1</td> <td>maintext1</td> </tr> <tr class="bg-info main1 hide"> <td>subtext1</td> <td>subtext1</td> </tr> <tr class="bg-info main1 hide"> <td>subtext1</td> <td>subtext1</td> </tr> <tr id="main2" class="bg-primary"> <td>maintext2</td> <td>maintext2</td> </tr> <tr name="toggletext2" class="bg-info main2 hide"> <td>subtext2</td> <td>subtext2</td> </tr> <tr name="" class="bg-info main2 hide"> <td>subtext2</td> <td>subtext2</td> </tr> </table></code></pre> </div> </div> </p> |
20,135,079 | 0 | Fence plot (or Wall plot?) density plots in R or GNUPLOT <p>Hi I have some ensembles for stochastic simulations of a system. I would like to represent these data as histograms in a fence plot in a similar way to what is shown here:</p> <p><a href="http://stackoverflow.com/questions/9009154/3d-parametric-graph-in-gnuplot">3D parametric graph in Gnuplot</a></p> <p><a href="http://lee-phillips.org/qdf/" rel="nofollow">http://lee-phillips.org/qdf/</a></p> <p><a href="http://gnuplot-tricks.blogspot.mx/2009/08/return-of-wall-chart-entirely-in.html" rel="nofollow">http://gnuplot-tricks.blogspot.mx/2009/08/return-of-wall-chart-entirely-in.html</a></p> <p>However, I am not sure about how to do it with histograms (in principle, it is quite confusing for me to make histograms in GNUPLOT, I've already checked <a href="http://stackoverflow.com/questions/2471884/histogram-using-gnuplot">Histogram using gnuplot?</a> and some other posts). I know how to make histograms in R and I've successfully tried things like this:<a href="http://rgraphgallery.blogspot.mx/2013/04/rg10-plotting-multiple-suprimposed.html" rel="nofollow">http://rgraphgallery.blogspot.mx/2013/04/rg10-plotting-multiple-suprimposed.html</a> <a href="http://learnr.wordpress.com/2009/06/28/ggplot2-version-of-figures-in-lattice-multivariate-data-visualization-with-r-part-1/" rel="nofollow">http://learnr.wordpress.com/2009/06/28/ggplot2-version-of-figures-in-lattice-multivariate-data-visualization-with-r-part-1/</a></p> <p>My data looks like this:</p> <pre><code> # time Aa As 0.000000000000e+00 0.000000000000e+00 0.000000000000e+00 5.000000000000e-01 0.000000000000e+00 0.000000000000e+00 1.000000000000e+00 0.000000000000e+00 0.000000000000e+00 1.500000000000e+00 0.000000000000e+00 0.000000000000e+00 2.000000000000e+00 2.000000000000e+00 0.000000000000e+00 2.500000000000e+00 2.000000000000e+00 0.000000000000e+00 3.000000000000e+00 2.000000000000e+00 0.000000000000e+00 3.500000000000e+00 2.000000000000e+00 0.000000000000e+00 4.000000000000e+00 2.000000000000e+00 0.000000000000e+00 4.500000000000e+00 3.000000000000e+00 0.000000000000e+00 . . 0.000000000000e+00 0.000000000000e+00 0.000000000000e+00 5.000000000000e-01 0.000000000000e+00 0.000000000000e+00 1.000000000000e+00 0.000000000000e+00 0.000000000000e+00 1.500000000000e+00 0.000000000000e+00 0.000000000000e+00 2.000000000000e+00 0.000000000000e+00 0.000000000000e+00 2.500000000000e+00 0.000000000000e+00 0.000000000000e+00 3.000000000000e+00 2.000000000000e+00 0.000000000000e+00 3.500000000000e+00 3.000000000000e+00 0.000000000000e+00 4.000000000000e+00 3.000000000000e+00 0.000000000000e+00 . . . </code></pre> <p>I have around 1000 different stochastic simulations and I want to plot together density plots for the Aa column in different times, for example time zero, 100 and 1000. And make it look like the firsts posts I included here. I hope this post is enoughly clear. Please let me know I you need any further information.</p> |
18,735,164 | 0 | <p>After enabling Java 1.5 mode with Trex's answer, you can access the generic types of <code>fieldType</code> using </p> <pre><code>Type[] typeArguments = fieldType.asParameterizedType().typeArguments() </code></pre> |
40,048,763 | 0 | <p>You just had your logic wrong. This should work for you.</p> <pre><code>Do While E1 < 4 OrElse E1 Mod 2 <> 0 E1 = CInt(Int((11 * Rnd()) + 1)) Loop Do While E1 Mod E2 <> 0 OrElse _ E2 = 1 OrElse _ E2 = 0 OrElse _ E1 = E2 E2 = CInt(Int((11 * Rnd()) + 1)) Loop </code></pre> |
10,566,312 | 0 | <p>Given that <code>$index</code> is an integer you could just break out of the loop:</p> <pre><code>foreach ($images as $index => $image) { echo '<li><a href="'.$image['XLargeURL'].'"><img src="'.$image['TinyURL'].'" alt="thumbnail"/></li>'; if ($index >= 5) { break; } } </code></pre> |
21,757,417 | 0 | <p>There's no way that Exception <em>originated</em> from the code you posted. If <code>OnInit</code> is aprt of the stack trace, then the exception <em>has</em> to have been thrown from (or passed through) <code>InitializeComponent</code> or <code>base.OnInit(e)</code></p> <p>Run it in the debugger and see where the exception <em>actually</em> originates. You can also turn on "break on handled exception" if you want, but you'll likely get some false positives.</p> |
8,072,716 | 0 | How to fix "function not allowed" when using row_number() over a view? <pre><code>select * from ( select a.*,row_number() over() as rk from table1 tba ) as foo where rk between 11 and 20 </code></pre> <p>This works for database table. I am using a view which is a join of 2 tables. When i try to do rownum it is saying: "<strong>Function not allowed</strong>"</p> <pre><code>select * from ( select a.*,row_number() over() as rk from view1 v1 ) as foo where rk between 11 and 20 </code></pre> <p>Any suggestion or alternative for rownum in DB2?</p> |
8,864,576 | 0 | <p>I'm assuming you're using ajax to pull in your data from the php file. You'll need to call this function in the success callback of your ajax request.</p> |
23,252,455 | 1 | how to put data(id) in form (wtforms) and get it back on submit <p>I am new to wtforms, so I`ll really appreciate any help. </p> <p>I need to display books names and near each put "Delete" button. I`ve read <a href="http://wtforms.readthedocs.org/en/1.0.4/crash_course.html" rel="nofollow">wtforms crash course</a> but I have no idea how to solve my problem with it.</p> <p>So I decided to do it other way - my best idea is to render to template a dict with id and name and on submit return id, but I still can`t do it. Code examples are below.</p> <p>It`s view.py</p> <pre><code>@application.route('/delete', methods=['GET', 'POST']) def delete(): books_lib = mydatabase.get_all_books() form = DeleteForm(request.form) if request.method == 'POST': delete_id = form.id.data mydatabase.del_book(delete_id) return render_template('delete.html', form = form, books_lib = books_lib) return render_template('delete.html', form = form, books_lib = books_lib) </code></pre> <p>It`s template</p> <pre><code><!DOCTYPE html> <html> <body> <h2>book to delete</h2> <form action="/delete" name="delete" method="POST"> {% if books_lib %} {% for id, book in books_lib.items() %} <p>{{book}}:<input type="submit" value="Delete" id="{{id}}"> {% endfor%} {% endif %} </form> </body> </html> </code></pre> <p>It`s form</p> <pre><code>class DeleteForm(Form): book = TextField("Book name", [validators.Length(min=2, max=25)]) id = HiddenField("id") </code></pre> |
39,931,184 | 0 | <p>Change your last rule to this,</p> <pre><code># If the request is not for a valid directory RewriteCond %{REQUEST_FILENAME} !-d # If the request is not for a valid file RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^([a-z]+)/$ home/index.php?nLang=$1 [L,QSA,NC] </code></pre> <p>That way it will only handle language parameter e.g. <code>/it/</code> or <code>/en/</code> but will let other URLs e.g. <code>/it/dummy/</code> go to 404 handler. </p> |
36,054,503 | 0 | <p>You have to add it at the end and beginning also because <code>Join</code> will only <em>combine</em> two strings. Having said this when combining <code>"1"</code> and <code>"2"</code> with a speaterator of <code>','</code> you get <code>"1','2"</code> where the seperator is just added <em>between</em> the two elements.</p> <p>As of <a href="https://msdn.microsoft.com/library/57a79xd0%28v=vs.110%29.aspx" rel="nofollow">MSDN</a>:</p> <blockquote> <p>Concatenates all the elements of a string array, using the specified separator <strong>between each element</strong>.</p> </blockquote> <p>In the end the following solution seems to be best in terms of memory and speed because you have least number of string-concatenations (two for start and end and one for every element --> 2 + n). </p> <pre><code>var daysConverted = "'" + string.Join("','", days) + "'"; </code></pre> |
40,658,544 | 0 | <p>The compiler attempts to resolve implicits before eta-expansion of <code>from</code> into a function, so the type parameters of <code>from</code> are not yet inferred when you call it like this:</p> <pre><code>future.map(from) </code></pre> <p><code>compiles2</code> obviously works because you supply the type parameters on your own. When you call <code>future.map(from[C1, C2])</code>, the compiler knows it will need an implicit <code>C1 => C2</code>, because that's what you've told it.</p> <p>With <code>compiles1</code>, the difference is a little more subtle, but it stems from the fact that <code>future.map(from)</code> and <code>future.map(x => from(x))</code> are actually very different things. The former uses eta-expansion, which fails for the aforementioned reasons. With <code>future.map(x => from(x))</code>, there is no eta-expansion happening. Instead, you have an anonymous function that simply <em>calls</em> <code>from</code> instead of eta-expanding it. Therefore, the compiler can infer the type of <code>x</code>, which tells us that <code>x</code> is a <code>C1</code> (in this case), and it can find the implicit conversion <code>c1ToC2</code> that satisfies the type parameters of <code>from</code> while resolving the implicit and the final return type of the method, <code>Future[C2]</code>.</p> |
584,287 | 0 | <p>If you have a large pool of proxies you can use, then I suppose you could switch between them, but otherwise no, you generally can't just renew your IP address whenever you feel like it.</p> <p>You might want to look into <a href="http://www.torproject.org/" rel="nofollow noreferrer">Tor</a>, an anonymizing network which does something like what you're asking about.</p> |
19,113,717 | 1 | playing midi sounds through pygame on raspberrypi <p>I'm trying to play midi sounds using pygame on my raspberrypi (without external midi devices), however I can't get anything to work.</p> <p>I have tried many examples: The following gives.</p> <pre><code>import pygame import time import pygame.midi pygame.midi.init() player= pygame.midi.Output(0) player.set_instrument(48,1) major=[0,4,7,12] def go(note): player.note_on(note, 127,1) time.sleep(1) player.note_off(note,127,1) def arp(base,ints): for n in ints: go(base+n) def chord(base, ints): player.note_on(base,127,1) player.note_on(base+ints[1],127,1) player.note_on(base+ints[2],127,1) player.note_on(base+ints[3],127,1) time.sleep(1) player.note_off(base,127,1) player.note_off(base+ints[1],127,1) player.note_off(base+ints[2],127,1) player.note_off(base+ints[3],127,1) def end(): pygame.quit() </code></pre> <p>Gives the following error</p> <pre><code>PortMidi call failed... PortMidi: 'Bad pointer' type ENTER... </code></pre> <p>The next example (like most of the others) gives a 'Device id invalid, out of range.' error:</p> <pre><code>import pygame import pygame.midi from time import sleep instrument = 0 note = 74 volume = 127 pygame.init() pygame.midi.init() for id in range(pygame.midi.get_count()): print pygame.midi.get_device_info(id) port = 2 midiOutput = pygame.midi.Output(port, 1) midiOutput.set_instrument(instrument) for note in range(0,127): midiOutput.note_on(note,volume) sleep(.25) midiOutput.note_off(note,volume) del midiOutput pygame.midi.quit() </code></pre> <p>Gives this error</p> <pre><code>('ALSA', 'Midi Through Port-0', 0, 1, 0) ('ALSA', 'Midi Through Port-0', 1, 0, 0) Traceback (most recent call last): File "midi-test2.py", line 16, in <module> midiOutput = pygame.midi.Output(port, 1) File "/usr/lib/python2.7/dist-packages/pygame/midi.py", line 414, in __init__ raise MidiException("Device id invalid, out of range.") pygame.midi.MidiException: 'Device id invalid, out of range.' </code></pre> <p>I haven't found any guides to setting up a RaspberryPi to play midi sounds, any suggestions?</p> |
33,554,871 | 0 | How to use/declare an unsigned Integer value in VHDL? <p>I'm trying to design a basic Vending machine on a Altera DE1-SoC Board. My question comes from trying to code the State Machine that will control the vending process. How do you track the $ value being added jumping between states? I think the code I'm trying to implement is written in a higher level language format and is not being able to be compiled in VHDL. Any ideas?</p> <p>I'm getting this error (right after the Architecture declaration):</p> <blockquote> <p>Error (10482): VHDL error at State.vhd(21): object "unsignedInteger" is used but not declared</p> </blockquote> <pre><code>library ieee; use ieee.std_logic_1164.all; use IEEE.numeric_std.all; use IEEE.std_logic_unsigned.all; entity MessageState is Port( Reset :in std_logic; -- reset to a safe state ----------------------------------------------------------------------------------- MyStateOut :out std_logic_vector( 1 downto 0 ); -- drive the current state to display or LEDs OutputCode :out std_logic_vector( 6 downto 0 ) -- to the display driver ); end; architecture Vending_FSM of MessageState is signal Count: unsignedInteger(8 downto 0); -- we define a data type to represent the states. Use descriptive names -- add more lines for more states. Change the size of MyState as needed subtype MyState is std_logic_vector(2 downto 0); constant Idle :MyState := "000"; constant NickelState :MyState := "001"; constant DimeState :MyState := "010"; constant QuarterState :MyState := "011"; constant Dispense :MyState := "100"; signal state, next_state: MyState; begin MyStateOut <= state; -- make state visible. MyNextState: process(state, next_state) begin -- add all signals read or tested in this process case state is when Idle => if ( KEY(0) = '1') then next_state <= NickelState; elsif ( KEY(1) = '1') then next_state <= DimeState; elsif ( KEY(2) = '1') then next_state <= QuarterState; else next_state <= Idle; -- default action Count <= (others => '0'); end if; </code></pre> |
40,322,536 | 0 | How can I change the border thickness of an Android checkbox? <p>The default size of the android checkboxes were too small for my purposes, so I changed their overall size, however with their new size their borders now are horribly thick. </p> <p>In what way could I change the thickness? I quite like the default behavior of the checkboxes, so the only thing I would like to change is the thickness of the border. </p> <p>Code used to make the checkbox larger: </p> <pre><code><CheckBox android:id="@+id/item_switch" android:layout_width="160dp" android:layout_height="160dp" android:button="@null" android:background="?android:attr/listChoiceIndicatorMultiple"/> </code></pre> <p>From this <a href="http://stackoverflow.com/a/36071778/7089738">SO answer</a>.</p> |
5,109,018 | 0 | <p>The nested lexical scope example that someone gave gives several benefits.</p> <ol> <li>"Safer" globals</li> <li>It is one method to embed DSL's into your program. </li> </ol> <p>I think that is a very good example of the differences between the two languages. Ruby is simply more flexible. Python can be flexible, but you often have to do extreme contortions to get there, which makes it not worth the hassle.</p> <p>Sorry for not posting under the original answer, I guess I don't have privileges to do that.</p> |
30,019,358 | 0 | Android List View Scrolling Items Randomize <p>my ListView works fine except when I scroll fast some of the items are duplicated and in random order. It's kind of hard to explain but here's the beginning of my getView method.</p> <pre><code>@Override public View getView(final int position, View convertView, ViewGroup arg2) { View view; if (convertView == null) { LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = inflater.inflate(R.layout.list_item, null); }else{ view = convertView; }....... </code></pre> <p>In my MainActivity I call notifySetAdapterChanged(). Anyone know how to fix this?</p> <p>Here is what the Logcat says each getView():</p> <p>-Layouts #:1 and position is 0</p> <ul> <li>Layouts #:1 and position is 0 Layouts #:2 and position is 1 Layouts #:3 and position is 2 Layouts #:4 and position is 3 Layouts #:5 and position is 4 Layouts #:6 and position is 5 Layouts #:7 and position is 6 Layouts #:8 and position is 7 Layouts #:9 and position is 8 //click one of the list items Layouts #:10 and position is 0 Layouts #:11 and position is 1 Layouts #:12 and position is 2 Layouts #:13 and position is 3 Layouts #:14 and position is 4 Layouts #:14 and position is 5 Layouts #:14 and position is 6 Layouts #:14 and position is 7 Layouts #:14 and position is 8 Layouts #:14 and position is 0 Layouts #:14 and position is 1 Layouts #:14 and position is 2 Layouts #:14 and position is 3 Layouts #:14 and position is 4 Layouts #:14 and position is 5 Layouts #:14 and position is 6 Layouts #:14 and position is 7</li> </ul> |
10,133,796 | 0 | <p>You can override <code>-[NSView viewWillMoveToSuperview:]</code> in a custom NSView subclass. This is simply a means for your class to be notified when its position in the view hierarchy is about to change. It doesn't have some deeper meaning other than what its name implies, but you can, of course, harness it to serve various purposes. It's not a method on a delegate or on the view controller, but you can implement such delegation yourself if you want.</p> <p>Also, if your code is moving views around the view hierarchy, it can directly do whatever it wants immediately beforehand, which is also roughly when such a method would be called.</p> |
33,740,324 | 0 | GetMethodID for "getName" is returning NULL <p>I have been trying to print out the class name from a jclass object.</p> <p><code>jmethodID mid_getName = env->GetMethodID(point_class, "getName", "()Ljava/lang/String;");</code></p> <p>The <code>point_class</code> object is not NULL.</p> <p>I used this snippet from <a href="http://stackoverflow.com/questions/12719766/can-i-know-the-name-of-the-class-that-calls-a-jni-c-method">Can I know the name of the class that calls a JNI C method?</a> and <a href="http://stackoverflow.com/questions/9265457/class-name-from-jclass-in-jni">Class name from jclass in JNI</a></p> <p>On another note, I am doing JNI programming for android and my <code>FindClass</code> method is returning NULL when I want to create Java object on the native side. No proguard issue or anything else.</p> <p>Code:</p> <pre><code>JNIEXPORT void JNICALL long_JNI_method_name (JNIEnv * env, jobject object, jlong image, jint screenHeight, jint screenWidth) { jclass point_class = env->GetObjectClass(object); jmethodID mid_getName = env->GetMethodID(point_class, "getName", "()Ljava/lang/String;"); ... </code></pre> <p>I changed the JNI method name as it had package name(where I work) in it.</p> |
21,881,417 | 0 | <p>Try this.</p> <pre><code><?php include("connect.php"); if( isset($_GET['del']) ) { $id = (int)$_GET['del']; $sql = "DELETE termekek WHERE id = $id" ; echo "<a href='admin.php'>Back</a>"; } ?> </code></pre> |
17,192,980 | 0 | R submit to CRAN: which R version to build package? <p>I want to submit a package to CRAN. In the <a href="http://cran.r-project.org/web/packages/policies.html" rel="nofollow">CRAN repository policy</a> it states that <strong>"Packages for which R CMD check gives an ‘ERROR’ when a new R x.y.0 version is released will be archived"</strong>.</p> <p>It also says <strong>"Please ensure that R CMD check --as-cran has been run on the tarball to be uploaded before submission"</strong>.</p> <p>Running <code>R CMD check --as cran</code> on my tarball gives me the warning:</p> <pre><code>Warning: unknown option ‘--as-cran’ </code></pre> <p>I am running R version 2.14.1 on Ubuntu 12.04.2 LTS. Can I build a source package using this version or do I have to use R 3.0?</p> <p>And why does <code>R CMD check --as-cran</code> not work for me?</p> |
33,098,343 | 0 | <p>What about <code>set -v</code>?</p> <blockquote> <p><code>-v</code> Print shell input lines as they are read.</p> </blockquote> <p>The output seems to meet your expectation.</p> <pre><code>$ set -v $ ./command1 > output1 ./command1 > output1 sh: ./command1: No such file or directory $ ./command2 arg1 arg2 > output2 ./command2 arg1 arg2 > output2 sh: ./command2: No such file or directory $ ./command3 | tee output3 ./command3 | tee output3 sh: ./command3: No such file or directory </code></pre> |
557,593 | 0 | <p><a href="http://www.gnuplot.info/" rel="nofollow noreferrer">GnuPlot</a> is a the old reliable answer here, easy graphing with lots of options. I believe there are python bindings but it's probably easier to export your data and run it through regular gnuplot. Here's an ancient <a href="http://parand.com/docs/gnuplot.html" rel="nofollow noreferrer">quick start doc</a> for it.</p> <p>I'm also using <a href="http://matplotlib.sourceforge.net/" rel="nofollow noreferrer">matplotlib</a> with great success for larger data sizes.</p> |
18,356,882 | 0 | <p>Call merge(), and use its returned value: it's the attached entity containing the values found in the detached entity passed as argument:</p> <pre><code>Foo modifiedAttachedFoo = session.merge(modifiedDetachedFoo); modifiedAttachedFoo.getLazyCollection().size(); // no problem: the entity is attached </code></pre> |
29,378,657 | 0 | <p>Change this line from your form element:</p> <pre><code>name="payment_amount" </code></pre> <p>to be an array:</p> <pre><code>name="payment_amount[]" </code></pre> <p>Then, modify your <code>foreach</code> to read as:</p> <pre><code>foreach ($_POST['payment_amount'] as $value) { echo $value . "<br>"; } </code></pre> <ul> <li>You were using the wrong POST array => <code>name="payment_id[]"</code></li> </ul> <p>To add them all up, should you want to do that, use:</p> <pre><code>foreach ($_POST['payment_amount'] as $value) { echo $value . "<br>"; $total += $value; } echo $total; </code></pre> <p>or</p> <pre><code>$total = array_sum($_POST['payment_amount']); </code></pre> |
40,258,608 | 1 | python: extract and download an image from the body of the email <p>I am trying to read the content of the email. If an email contains an image in the <strong>BODY</strong> part I need to extract and save it in the local Here is the code for getting the body content</p> <pre><code>def get_body(id): res, mail_data = connection.fetch(id, '(RFC822)') raw_email=mail_data[0][1] email_message_instance = email.message_from_string(raw_email) whole_body = '' for part in email_message_instance.walk(): if part.get_content_type() == "text/plain": # ignore attachments/html body = part.get_payload(decode=True) whole_body += body + ' ' else: continue return whole_body </code></pre> |
27,332,767 | 0 | <p>To quickly answer your question I will first provide solution.</p> <p>Although this is not best practice, and not helping you learn the right approach to design html structure and traverse the DOM in efficient and quick way, it will solve this specific problem.</p> <p>If it was all designed better, this might not require Javascript at all and CSS would be perfect solution.</p> <p>I do not want to explain How my solution work, so you will have the opportunity to learn from this.</p> <p>I replaced the following tow lines:</p> <pre><code>afterSlideLoad:(function(){ $(".active").parent().css("color", "black"); $(".active").parent().parent().css("color", "black"); }) </code></pre> <p>To this. this is broken to lines, for better understanding. [of-course this works in code too.]):</p> <pre><code> afterLoad: function(){ /* Here comes your previous code... */ console.log('afterSlideLoad Changed to afterLoad'); $('.inlinedColor') .css('color','gray') .removeClass('inlinedColor'); $('li.active') .prevAll('span.year') .first() .add( $('li.active') .parents('li') .find('>a span span') ) .addClass('inlinedColor') .css('color','black'); } </code></pre> <p>All the above available here: <a href="http://jsfiddle.net/rwde78ts/10/" rel="nofollow">http://jsfiddle.net/rwde78ts/10/</a></p> <p>If you did not managed to figure it out on your own, do not hesitate to ask, so i could explain line by line.</p> |
1,691,470 | 0 | Edited most errors, Now Compiles, but does not Run, what am I doing wrong? <pre><code>#include <cstdlib> #include <iomanip> #include <iostream> #include <string> using std::cout; using std::cin; using std::endl; using std::string; using std::setprecision; using std::fixed; //function prototypes void getInput(string &, double); void calcFedTaxes(double , double, double &, double &); void calcnetPay(double &, double , double, double); void displayInfo(string, double, double, double); int main() { //declare constants and variables const double FWT_RATE = .2; const double FICA_RATE = .08; string dname = ""; double dsalary = 0.0; double dfwtTax = 0.0; double dficaTax = 0.0; double dnetPay = 0.0; //display output in fixed-point notation with two decimal places cout << fixed << setprecision(2); //call function to get input and calculate salary and taxes void getInput(string dname, double dsalary, double dnetPay); void calcFedTaxes(double Fsalary, double FwtRate, double FicaRate, double & withholdingTax, double & incomeTax); void calcnetPay(double & netPay, double weeklySalary, double fwtTax, double ficaTax); void displayInfo (string dname, double dfwtTax, double dficaTax, double dnetPay); system ("pause"); } //end call function //*****function definitions***** void getInput(string iname, double isalary) { //enter input items cout << "Enter name: "; cin >> iname; cout << "weekly salary: "; cin >> isalary; } void calcFedTaxes (double Fsalary, double FwtRate, double FicaRate, double & withholdingTax, double & incomeTax) { withholdingTax = Fsalary * FwtRate; incomeTax = Fsalary * FicaRate; } void calcnetPay(double & netPay, double weeklySalary, double fwtTax, double ficaTax) { netPay = weeklySalary - fwtTax - ficaTax; } void displayInfo(string dname, double dfwtTax, double dficaTax, double dnetPay) { cout << "name: " << dname; cout << "With holding Tax: " << dfwtTax; cout << "With holding Fica: "<<dficaTax; cout << "Net pay: " <<dnetPay; cin>> dnetPay; //end of displayInfo function return; } </code></pre> |
4,043,455 | 0 | Which costs more while looping; assignment or an if-statement? <p>Consider the following 2 scenarios:</p> <pre><code>boolean b = false; int i = 0; while(i++ < 5) { b = true; } </code></pre> <p>OR</p> <pre><code>boolean b = false; int i = 0; while(i++ < 5) { if(!b) { b = true; } } </code></pre> <p>Which is more "costly" to do? If the answer depends on used language/compiler, please provide. My main programming language is Java.</p> <p>Please do not ask questions like why would I want to do either.. They're just barebone examples that point out the relevant: should a variable be set the same value in a loop over and over again or should it be tested on every loop that it holds a value needed to change?</p> |
33,004,021 | 0 | <p>After reading through parse doc, I figured out that AppDelegate.m file should be updated like this for IOS 9:</p> <blockquote> <p>There's also two code changes you'll need to make. First, add the following to your application:didFinishLaunchingWithOptions: method, after you've initialized the Parse SDK.</p> <pre><code>// AppDelegate.m #import <FBSDKCoreKit/FBSDKCoreKit.h> #import <ParseFacebookUtilsV4/PFFacebookUtils.h> @implementation AppDelegate - (void)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [Parse setApplicationId:@"parseAppId" clientKey:@"parseClientKey"]; [PFFacebookUtils initializeFacebookWithApplicationLaunchOptions:launchOptions]; } Next, add the following handlers in your app delegate. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation { return [[FBSDKApplicationDelegate sharedInstance] application:application openURL:url sourceApplication:sourceApplication annotation:annotation]; } - (void)applicationDidBecomeActive:(UIApplication *)application { [FBSDKAppEvents activateApp]; } </code></pre> <p>There are two main ways to use Facebook with your Parse users: (1) to log in (or sign up) as a Facebook user and creating a PFUser, or (2) linking Facebook to an existing PFUser.</p> </blockquote> |
710,969 | 0 | <p>This may be more than you need, here's the code for the class I use:</p> <pre><code>public class ControlColorAnimator { private const int INTERVAL = 100; private readonly decimal _alphaIncrement; private readonly decimal _blueIncrement; private readonly Color _endColor; private readonly decimal _greenIncrement; private readonly int _iterations; private readonly decimal _redIncrement; private readonly Color _startColor; private decimal _currentAlpha; private decimal _currentBlueValue; private decimal _currentGreenValue; private decimal _currentRedValue; private Timer _timer; public ControlColorAnimator(TimeSpan duration, Color startColor, Color endColor) { _startColor = startColor; _endColor = endColor; resetColor(); _iterations = duration.Milliseconds / INTERVAL; _alphaIncrement = ((decimal) startColor.A - endColor.A) / _iterations; _redIncrement = ((decimal) startColor.R - endColor.R) / _iterations; _greenIncrement = ((decimal) startColor.G - endColor.G) / _iterations; _blueIncrement = ((decimal) startColor.B - endColor.B) / _iterations; } public Color CurrentColor { get { int alpha = Convert.ToInt32(_currentAlpha); int red = Convert.ToInt32(_currentRedValue); int green = Convert.ToInt32(_currentGreenValue); int blue = Convert.ToInt32(_currentBlueValue); return Color.FromArgb(alpha, red, green, blue); } } public event EventHandler<DataEventArgs<Color>> ColorChanged; public void Go() { disposeOfTheTimer(); OnColorChanged(_startColor); resetColor(); int currentIteration = 0; _timer = new Timer(delegate { if (currentIteration++ >= _iterations) { Stop(); return; } _currentAlpha -= _alphaIncrement; _currentRedValue -= _redIncrement; _currentGreenValue -= _greenIncrement; _currentBlueValue -= _blueIncrement; OnColorChanged(CurrentColor); }, null, TimeSpan.FromMilliseconds(INTERVAL), TimeSpan.FromMilliseconds(INTERVAL)); } public void Stop() { disposeOfTheTimer(); OnColorChanged(_endColor); } protected virtual void OnColorChanged(Color color) { if (ColorChanged == null) return; ColorChanged(this, color); } private void disposeOfTheTimer() { Timer timer = _timer; _timer = null; if (timer != null) timer.Dispose(); } private void resetColor() { _currentAlpha = _startColor.A; _currentRedValue = _startColor.R; _currentGreenValue = _startColor.G; _currentBlueValue = _startColor.B; } } </code></pre> <p>This uses <code>DataEventArgs<T></code> (shown below)</p> <pre><code>/// <summary> /// Generic implementation of <see cref="EventArgs"/> that allows for a data element to be passed. /// </summary> /// <typeparam name="T">The type of data to contain.</typeparam> [DebuggerDisplay("{Data}")] public class DataEventArgs<T> : EventArgs { private T _data; /// <summary> /// Constructs a <see cref="DataEventArgs{T}"/>. /// </summary> /// <param name="data">The data to contain in the <see cref="DataEventArgs{T}"/></param> [DebuggerHidden] public DataEventArgs(T data) { _data = data; } /// <summary> /// Gets the data for this <see cref="DataEventArgs{T}"/>. /// </summary> public virtual T Data { [DebuggerHidden] get { return _data; } [DebuggerHidden] protected set { _data = value; } } [DebuggerHidden] public static implicit operator DataEventArgs<T>(T data) { return new DataEventArgs<T>(data); } [DebuggerHidden] public static implicit operator T(DataEventArgs<T> e) { return e.Data; } } </code></pre> <p>Use in your form like this:</p> <pre><code>private ControlColorAnimator _animator; private void runColorLoop() { endCurrentAnimation(); startNewAnimation(); } private void endCurrentAnimation() { ControlColorAnimator animator = _animator; _animator = null; if (animator != null) { animator.ColorChanged -= _animator_ColorChanged; animator.Stop(); } } private void startNewAnimation() { _animator = new ControlColorAnimator(TimeSpan.FromSeconds(.6), Color.Yellow, BackColor); _animator.ColorChanged += _animator_ColorChanged; _animator.Go(); } private void _animator_ColorChanged(object sender, DataEventArgs<Color> e) { invokeOnFormThread(delegate { setColor(e); }); } private void setColor(Color color) { // code to set color of the controls goes here } private void invokeOnFormThread(MethodInvoker method) { if (IsHandleCreated) Invoke(method); else method(); } </code></pre> |
39,151,158 | 0 | Most efficient way to evaluate cards for TexasHoldEm game? <p>So I am in the process of making a texas holdem game. I am stuck on how to evualte the hands to see what type of scoring each player has (Two Pair, Flush etc) </p> <p>EDIT: I only need to deal 5 cards to each player and compare those 5 cards. Its not a complete texas holdem game.</p> <p>Any tips on how to do that? (I know this code is really sloppy, sorry!)</p> <pre><code>public class Main { public static void main(String[] args) { //CDHS run(); } public static void run() { List<Card> deck = new ArrayList(); Card C1 = new Card("1C"); Card C2 = new Card("2C"); Card C3 = new Card("3C"); Card C4 = new Card("4C"); Card C5 = new Card("5C"); Card C6 = new Card("6C"); Card C7 = new Card("7C"); Card C8 = new Card("8C"); Card C9 = new Card("9C"); Card CT = new Card("TC"); Card CJ = new Card("JC"); Card CQ = new Card("QC"); Card CK = new Card("KC"); Card CA = new Card("AC"); Card D1 = new Card("1D"); Card D2 = new Card("2D"); Card D3 = new Card("3D"); Card D4 = new Card("4D"); Card D5 = new Card("5D"); Card D6 = new Card("6D"); Card D7 = new Card("7D"); Card D8 = new Card("8D"); Card D9 = new Card("9D"); Card DT = new Card("TD"); Card DJ = new Card("JD"); Card DQ = new Card("QD"); Card DK = new Card("KD"); Card DA = new Card("AD"); Card H1 = new Card("1H"); Card H2 = new Card("2H"); Card H3 = new Card("3H"); Card H4 = new Card("4H"); Card H5 = new Card("5H"); Card H6 = new Card("6H"); Card H7 = new Card("7H"); Card H8 = new Card("8H"); Card H9 = new Card("9H"); Card HT = new Card("TH"); Card HJ = new Card("JH"); Card HQ = new Card("QH"); Card HK = new Card("KH"); Card HA = new Card("AH"); Card S1 = new Card("1S"); Card S2 = new Card("2S"); Card S3 = new Card("3S"); Card S4 = new Card("4S"); Card S5 = new Card("5S"); Card S6 = new Card("6S"); Card S7 = new Card("7S"); Card S8 = new Card("8S"); Card S9 = new Card("9S"); Card ST = new Card("TS"); Card SJ = new Card("JS"); Card SQ = new Card("QS"); Card SK = new Card("KS"); Card SA = new Card("AS"); deck.add(C1); deck.add(C2); deck.add(C3); deck.add(C4); deck.add(C5); deck.add(C6); deck.add(C7); deck.add(C8); deck.add(C9); deck.add(CT); deck.add(CJ); deck.add(CQ); deck.add(CK); deck.add(CA); deck.add(D1); deck.add(D2); deck.add(D3); deck.add(D4); deck.add(D5); deck.add(D6); deck.add(D6); deck.add(D7); deck.add(D8); deck.add(D9); deck.add(DT); deck.add(DJ); deck.add(DQ); deck.add(DK); deck.add(DA); deck.add(H1); deck.add(H2); deck.add(H3); deck.add(H4); deck.add(H5); deck.add(H6); deck.add(H7); deck.add(H8); deck.add(H9); deck.add(HT); deck.add(HJ); deck.add(HQ); deck.add(HK); deck.add(HA); deck.add(S1); deck.add(S2); deck.add(S3); deck.add(S4); deck.add(S5); deck.add(S6); deck.add(S7); deck.add(S8); deck.add(S9); deck.add(ST); deck.add(SJ); deck.add(SQ); deck.add(SK); deck.add(SA); } Collections.shuffle(deck); Player black = new Player(); Player white = new Player(); Card temp1 = deck.get(0); String temp2 = temp1.getValue(); black.setCard1(temp2); temp1 = deck.get(1); temp2 = temp1.getValue(); white.setCard1(temp2); temp1 = deck.get(2); temp2 = temp1.getValue(); black.setCard2(temp2); temp1 = deck.get(3); temp2 = temp1.getValue(); white.setCard2(temp2); temp1 = deck.get(4); temp2 = temp1.getValue(); black.setCard3(temp2); temp1 = deck.get(5); temp2 = temp1.getValue(); white.setCard3(temp2); temp1 = deck.get(6); temp2 = temp1.getValue(); black.setCard4(temp2); temp1 = deck.get(7); temp2 = temp1.getValue(); white.setCard4(temp2); temp1 = deck.get(8); temp2 = temp1.getValue(); black.setCard5(temp2); temp1 = deck.get(9); temp2 = temp1.getValue(); white.setCard5(temp2); System.out.println("Black: " + black.getCard1() + " " + black.getCard2() + " " + black.getCard3() + " " + black.getCard4() + " " + black.getCard5() + " White: " + white.getCard1() + " " + white.getCard2() + " " + white.getCard3() + " " + white.getCard4() + " " + white.getCard5()); int score; switch(black.getCard1() + black.getCard2() + black.getCard3() + black.getCard4() + black.getCard5()) { } } } </code></pre> <p>And heres the card class</p> <pre><code>public class Card { private String value; public Card(String value) { this.value = value; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } </code></pre> <p>And Player class</p> <pre><code>public class Player { private String name; private String card1; private String card2; private String card3; private String card4; private String card5; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCard1() { return card1; } public String getCard2() { return card2; } public String getCard3() { return card3; } public String getCard4() { return card4; } public String getCard5() { return card5; } public void setCard1(String card1) { this.card1 = card1; } public void setCard2(String card2) { this.card2 = card2; } public void setCard3(String card3) { this.card3 = card3; } public void setCard4(String card4) { this.card4 = card4; } public void setCard5(String card5) { this.card5 = card5; } } </code></pre> |
16,133,289 | 0 | <p>Try updating the components code in your appController to add the authenticate values to the Auth array like this:</p> <pre><code>public $components = array( 'Session', 'DebugKit.Toolbar', 'Auth' => array( 'allow' => array('login','logout'), 'loginAction' => array('controller' => 'users', 'action' => 'login'), 'loginRedirect' => array('controller' => 'dashboard', 'action' => 'index'), 'authorize' => 'Controller', 'authenticate' => array( 'Form' => array( 'fields' => array('username' => 'email') ) ) ) ); </code></pre> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.