diff --git "a/test.tsv" "b/test.tsv" deleted file mode 100644--- "a/test.tsv" +++ /dev/null @@ -1,7465 +0,0 @@ -pid label text -39424767 0 android studio emulator: WARNING: Increasing RAM size to 1024MB
I am trying to build my first android application in Android Studio, following the tutorial https://developer.android.com/training/basics/firstapp/creating-project.html, using AndroidStudio 2.1.2.
Whenever I run the emulator, I get this error message:
Android Emulator could not allocate 1.0 GB of memory for the current AVD configuration. Consider adjusting the RAM size of your AVD in the AVD Manager. Error detail: QEMU 'pc.ram': Cannot allocate memory
Decreasing the size of the memory on the Nexus5x emulator has no effect, so the error message still says "could not allocate 1.0 GB", even when I adjust the memory of the AVD to 256MB. The app needs to run on Android 6.0, with a Nexus5x emulator, so I can't try with a different emulator. Any help would be much appreciated :)
-8991182 0 Difference between different datasourcesHim Please explain what is the difference between different datasources for SQL (shown in the pic.)
I mean difference between Microsoft SQL Server and Microsoft SQL Server Database File
Use a separate query analyzer with the KeywordTokenizerFactory, thus (using your example):
<analyzer type="index"> <tokenizer class="solr.LowerCaseTokenizerFactory"/> <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt" enablePositionIncrements="false" /> <filter class="solr.ShingleFilterFactory" maxShingleSize="5" outputUnigrams="false"/> <filter class="solr.RemoveDuplicatesTokenFilterFactory"/> </analyzer> <analyzer type="query"> <tokenizer class="solr.KeywordTokenizerFactory"/> <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt" enablePositionIncrements="false" /> <filter class="solr.LowerCaseFilterFactory"/> <filter class="solr.RemoveDuplicatesTokenFilterFactory"/> </analyzer>
-29714091 0 how to save and restore an object into a file in matlab? I have a class like this:
classdef my_class properties prop_a prop_b end methods(Static) ... function o = load() ??? end end methods function save(o) ??? end ... end end
Please help me to write save and load methods. name of methods is clear and they should save and restore an object from a text file...
the properties are quite dynamic and have different row/col number.
-25989684 0 How to bind an alert message with the controller?Hi guys I've been experimenting with a simple commenting app with AngularJS and I'm stuck on how to get an alert message popup in the view if a user inputs an empty string into an input field.
The HTML view and ng-show logic as below:
<div ng-show="alert===true" class="alert alert-warning alert-dismissible inner" role="alert"> <button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">× </span><span class="sr-only">Close</span></button> <strong>Warning!</strong> You did not submit a comment. </div>
The controller view and $scope logic as below:
// pushes data back to Firebase Array $scope.addComment = function(){ if ($scope.newComment.text === ''){ $scope.alert = true; } else { $scope.alert = false; } $scope.comments.$add($scope.newComment); $scope.newComment = {text: '', date: ''}; };
The problem is that although I can bind the alert message logic to the HTML view, the alert message only shows up once and cannot be re-used again if the user types in an empty string again.
Should I use a while loop or something for this? Any help would be much appreciated!
EDIT:
Thanks to meriadec's feedback, I have made a fix using a more simple codebase, as follows.
The HTML view and ng-show logic as below:
<div ng-show="alert===true" class="alert alert-warning inner" role="alert"> <button type="button" class="btn" ng-click="alert=false"><span aria-hidden="true">× </span><span class="sr-only">Close</span></button> <strong>Warning!</strong> You did not submit a comment. </div>
The controller view and $scope logic as below:
// pushes data back to Firebase Array $scope.addComment = function(){ if ($scope.newComment.text === ''){ return $scope.alert = true; }; $scope.comments.$add($scope.newComment); $scope.newComment = {text: '', date: ''}; };
-4841203 0 how to create a pam module? Can anyone tell me about this... I want to create a pam module similar to the login module in /etc/pam.d
-20086791 0 How can I send an email with a layoutI am using grails mail plugin. When I submit my form, it will send an email from aaa@example.com to textField name="email successfully but how can I send an email with a layout...not blank like this picture http://www.4shared.com/photo/uT2YUCfo/Capture__2_.html or maybe some CSS..
FORM
<g:form action="send"> <table style="width:500px"> <tbody> <tr> <td>Your Email Address </td> <td><g:textField style="width:250px" name = "email"/></td> </tr> <tr> <td>Your Name</td> <td><g:textField style="width:250px" name = "user"/></td> </tr> <tr> <td><input type="submit"/></td> </tr> </tbody> </table> </g:form>
MAIL CLOSURE
def send = { sendMail { to params.email from "aaa@yahoo.com" subject "Test Reset Password" body(view:"/user/layoutmail",model:[name:params.user]) } render "Email Terkirim" }
-30733824 0 Yes. The code is executed in serial.
-25159920 0You may start with that base : http://jsfiddle.net/8r99k/
I put sample text and only a few css :
html{ margin:0; padding:0; width:calc(100% - 100px); height:calc(100% - 100px); border:solid #eeeeee 50px; overflow:hidden; } body{ margin:0; padding:0; height:100%; overflow:auto; }
Update
Adding width:100%
and padding-right:70px
to body
http://jsfiddle.net/8r99k/2/
Considering the fact that you want to get "select new " shown ... you still need to send something to the view. Take the entity with the most fields that are present in your new entity.
Create a partial class
namespace YourDomain.Model { [MetadataType(typeof(EntityWithinXList))] public partial class EntityWithinXList { [DataMember] public string DesiredFieldFromA{ get; set; } [DataMember] public int DesiredFieldFromB{ get; set; } } public class EntityWithinXList { }
So you need to add 2 new fields from 2 other tables to your entity:
var list = (from x in xList join a in AList on x.commonfield equals a.commonfield join b in BList on x.newCommonField equals b.newCommonField select new { x, a.DesiredFieldFromA, b.DesiredFieldFromB }).ToList(); list.ForEach(el => { el.x.DesiredFieldFromA= el.DesiredFieldFromA; el.x.DesiredFieldFromB= el.DesiredFieldFromB ; }); return list.Select(p=>p.x);
Unless I've misunderstood your question this should do it . And the list that you are sending to the view is List<EntityWithinXList>
I read that there is an option to create a mobile app in symfony2 and I don't really understand how to create it. As much as I do understand the concepct of emulating HTML5 to native app I don't know HOW to do the same thing with symfony.
Lets say that we created the app in html5. We just go through the process with PhoneGap and it creates the native app ( yeah, I know, very simplified ). But how should I do it with Symfony? I mean.. is there any similar emulator for php and...all the files that symfony contains or.. or what? How to make it work on iOS, how on Android, how on Windows Phone and BlackBerry..
Sorry for dumb question but I couldn't find proper answer.
-33034681 0In the Jake Wharton U2020 application it is solved in the next way
Add to you gradle.build file
configurations.all { resolutionStrategy { force 'com.android.support:support-annotations:23.0.1' } }
-40416451 0 Query returing no results codename one Query showing no results and not giving any error .control not entering inside the if block help me out that where is the mistake i am doing ? i have tried many ways to get the result but all in vain. When i tried the following before the if statement
int column=cur.getColumnCount(); Row row=cur.getRow(); row.getString(0);
then i got the resultset closed exception
Database db=null; Cursor cur=null; System.out.print("Printing from accounts class "+Email+Password); String [] param={Email,Password}; System.out.print(param[0]+param[1]); try{ db=Display.getInstance().openOrCreate("UserAccountsDB.db"); cur= db.executeQuery("select * from APPUserInfo WHERE Email=? AND Password=?",(String [])param); int columns=cur.getColumnCount(); if(columns > 0) { boolean next = cur.next(); while(next) { Row currentRow = cur.getRow(); String LoggedUserName=currentRow.getString(0); String LoggedUserPassword=currentRow.getString(1); System.out.println(LoggedUserName); next = cur.next(); } } }catch(IOException ex) { Util.cleanup(db); Util.cleanup(cur); Log.e(ex); } finally{ Util.cleanup(db); Util.cleanup(cur); }
-5745113 0 If I understood your question, you want the duplicated row of selects to reset their values.
In this case you can just remove this:
dropdownclone.find('select').each(function(index, item) { //set new select to value of old select $(item).val( $dropdownSelects.eq(index).val() ); });
and replace it with:
dropdownclone.find('option').attr('selected', false);
-38242048 0 Expect not accepting negative values I am trying to run expect
with negative values. But I'm getting bad flag error.
Test File:
echo "Enter Number:" read num echo $num
Expect File:
spawn sh test.sh expect -- "Enter Number:" {send "-342345"}
I even tried to escape negative values with \
option still it's not working.
Possible Duplicate:
Which files in a Visual C# Studio project don’t need to be versioned?
when creating a repository, what do you include in the repository, should folders like Resharper, Debug and Bin folder be included? if not, is it possible to exclude files/folders from the unstaged changes check?
-12513218 0This will definitely do the task for you.
tTable = {} OldIDX, OldIDX2, bSwitched, bSwitched2 = 0, 0, false, false for str in io.lines("txt.txt") do local _, _, iDx, iDex, sIdx, sVal = str:find( "^%| ([%d|%s]?) %| ([%d|%s]?) %| (%S?) %| (%S?) %|$" ) if not tonumber(iDx) then iDx, bSwitched = OldIDX, true end if not tonumber(iDex) then iDex, bSwitched2 = OldIDX2, true end OldIDX, OldIDX2 = iDx, iDex if not bSwitched then tTable[iDx] = {} end if not bSwitched2 then tTable[iDx][iDex] = {} end bSwitched, bSwitched2 = false, false tTable[iDx][iDex][sIdx] = sVal end
The only thing you can change in the code is the name of the file. :)
Seems like I was wrong, you did need some changes. Made them too.
-20801157 0Normally it can't. It will complain about libc being too old, for one.
If you statically link with libstdc++ and carefully avoid newer glibc features, you may be able to get away with it. The latter is not always possible though. Static linking with libc is not officially supported and may work or not work for you.
-1221935 0I think you can't with the grouped style of the UITableView. You could however use the plain style, and create your own view to show as the cell, just like the grouped view.
-22237682 0You have to declare
the overload in the header and define
it in the cpp file. Ex.:
MyHeader.h:
Fraction& operator+(const Fraction& l, const Fraction& r);
MyFile.cpp:
Fraction& operator+(const Fraction& l, const Fraction& r){ // ...
-40292211 0 Change the add to cart text on product archives by product types Here is a Complete Example
Change this line as per your needed !
case 'variable': return __( 'Select options', 'woocommerce' );
Complete code Add the following to your functions.php
file and edit the buttons text.
add_filter( 'woocommerce_product_add_to_cart_text' , 'custom_woocommerce_product_add_to_cart_text' ); function custom_woocommerce_product_add_to_cart_text() { global $product; $product_type = $product->product_type; switch ( $product_type ) { case 'external': return __( 'Buy product', 'woocommerce' ); break; case 'grouped': return __( 'View products', 'woocommerce' ); break; case 'simple': return __( 'Add to cart', 'woocommerce' ); break; case 'variable': return __( 'Select options', 'woocommerce' ); // Change this line break; default: return __( 'Read more', 'woocommerce' ); } }
-19292671 0 Try this:
textarea { overflow-x: vertical; }
-21975919 0 That error means that Laravel is trying to write data to your storage/view file, but it doesn't have permissions (write access). Storage/view is a folder for caching view files.It is default Laravel behaviour, so change permissions on whole storage folder, becuse there is more files inside, that Laravel will try to use for other purposes. For example, services.json is used when you add new service provider, and if it is locked, Laravel will complain.
-40545851 0 jQuery - Search on text entry - delay until full term enteredI have the following code, which detects any text entered into the #search-box
field and then immediately runs the search (if greater than 2 characters):
$('#search-box').on('input', function() { var term = $(this).val(); if (term.length > 2) { //execute search and display results } });
This doesn't look pretty though, as if you were to type dollar
for example, after 'doll' a load of dolls will appear, which will then be replaced with dollars once dolla
is entered. This can happen in a split second.
What I'd like to do is determine whether the user has finished the search term. Is it possible to wait for a second or 2 before doing the search? And if in that waiting period the user enters another letter, it resets the clock?
-3622549 0 Idiomatic way to write .NET interop functionI'm looking for a more idiomatic way, if possible, to write the following clojure code:
(import '(System.Net HttpWebRequest NetworkCredential) '(System.IO StreamReader)) (defn downloadWebPage "Downloads the webpage at the given url and returns its contents." [^String url ^String user ^String password] (def req (HttpWebRequest/Create url)) (.set_Credentials req (NetworkCredential. user password "")) (.set_UserAgent req ".NET") (def res (.GetResponse req)) (def responsestr (.GetResponseStream res)) (def rdr (StreamReader. responsestr)) (def content (.ReadToEnd rdr)) (.Close rdr) (.Close responsestr) (.Close res) content )
This is on ClojureCLR and works. (the fact that it's the CLR variant doesn't matter much)
I'd like to get rid of the defs (replace by lets? can they refer to each other?)
How about a better way to get to the stream - keeping in mind that .. chaining won't work because I need to Close the streams later on.
EDIT: After the answer, I found a much easier way in .NET to download a web page using the WebClient class. I still used many of Michal's recommended approaches - just wanted to record what I now believe to be the best answer:
(defn download-web-page "Downloads the webpage at the given url and returns its contents." [^String url ^String user ^String password] (with-open [client (doto (WebClient.) (.set_Credentials (NetworkCredential. user password "")))] (.DownloadString client url)))
-6267788 0 Making pre- and post-build event scripts pretty? I have some moderately hefty pre- and post-build event scripts for my Visual Studio 2008 projects (actually it's mainly post-build event scripts). They work OK in that they function correctly and when I exit 0
the build succeeds and when I exit 1
the build fails with an error. However, that error is enormous, and goes something like this:
The command "if Release == Debug goto Foo if Release == Release goto Bar exit 0 :Foo mkdir "abc" copy "$(TargetDir)file.dll" "abc" [...] " exited with code 1.
You get the idea. The entire script is always dumped out as part of the error description. The entire script is also dumped out in the Output window while the build is happening, too. So, why have I seen various references on the web to using echo
in these scripts? For example, here's part of an example on one particular site:
:BuildEventFailed echo POSTBUILDSTEP for $(ProjectName) FAILED exit 1 :BuildEventOK echo POSTBUILDSTEP for $(ProjectName) COMPLETED OK
Is there a way to get Visual Studio to suppress all script output apart from what is echo
ed (and therefore using echo
only to output what you want would make sense), or are these examples just misguided and they don't realize that the whole script is always dumped out?
There are a few ways to do this:
1) PHP: Using PHP, you can simply include an html file into another one
<?php include('fileOne.html'); ?>
2) jQuery: Using jQuery, you can load an HTML page dynamically into another (this is kind of hacky in my opinion):
<html> <head> <script src="jquery.js"></script> <script> $(function(){ $("#includedContent").load("b.html"); }); </script> </head> <body> <div id="includedContent"></div> </body> </html>
Source: Include HTML Page via jQuery
3) Framework: Using a framework like Python/Django, you can use {% include %} blocks to create standalone html files that can be reused like blocks.
<html> {% include 'navbar.html' %} </html>
My honest recommendation is #2 if you have to stay with just raw html, otherwise, if you are using PHP then includes are a no brainer. The last option is the frameworks, and that is really only if you have other heavy-duty functions you would need.
-2430673 0i think you must miss some proper argument which should be a pointer type in your method declaration.
-16607326 0480 * 800 is a mdpi device. You can can put these image resources in drawable-mdpi if you want the device to auto adjust for smaller and larger screen sizes. If you want these images to be of maximum size you can put it in drawable-xhdpi. If not i.e. if you want same image to be used in all the screen sizes then you can simply put in drawable folder in resource.
For more information you can check this :developer link
-30421058 0 How to tell Faraday to preserve hashbang in site URL?I'm working on a fork of a library that implements Faraday to build URLs.
site = "https://example.io/#/" path = "oauth/authorize" connection = Faraday.new(site) resource = Faraday::Utils.URI(path) URL = connection.build_url(resource)
Notice that my site URL ends with a hashbang. But when the above code is executed, Faraday strips out the hashbang entirely:
But my application requires it to build this URL (with the hashbang):
Now before I go ripping out Faraday and monkey-patching something terrible.. can I do this by setting an option on Faraday?
-5373508 0You can simply overload the enqueue class to take both Dates and Integers. In either case, it sounds like you need a method getValue() in CInteger that lets you access the int value.
public class CInteger { //constructors, data public void getValue() { return i; } }
and then you can have two enqueue() methods in your other class:
public void enqueue(Date d) { add(tailIndex, d); } public void enqueue(CInteger i) { add(tailIndex, new Integer(i.getValue()); //access the int value and cast to Integer object }
And Java will know which one you are calling automatically based on the parameters.
-14994030 0To programmatically instantiate the component instead of a declarative implementation, use addElement()
to add components to the display list.
For example, to add a visual element to a Spark Group named container
.
<?xml version="1.0" encoding="utf-8"?> <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" creationComplete="creationCompleteHandler(event)"> <fx:Script> <![CDATA[ import mx.core.UIComponent; import mx.events.FlexEvent; protected function creationCompleteHandler(event:FlexEvent):void { var component:UIComponent = new UIComponent(); component.x = 5; component.y = 5; container.addElement(component); } ]]> </fx:Script> <s:Group id="container" /> </s:Application>
Within script blocks, use package namespaces instead of MXML namespaces.
import com.msns.Component; var component:Component = new Component(); component.x = 5
-29693526 0 Are there any Java APIs for for planning or say creating time table Some time back, while Googling, I found a Java API (as I remember it was an Apache project but I am not sure) for creating timetables. By time table I mean simple timetable used in schools and colleges
Unfortunately I didn't take note of that API and now I cannot find it.
Please tell me if you know any such open source API available in Java.
-40956699 0 Hide attributes out of stock on product page PRESTASHOP 1.6I need help with hiding attributes out of stock on product page when selected some of attributes. Prestashop 1.6.1.9 I did not find ready-made solution. I'm bad at programming in php and java script, I believe I should be the knowledge that would solve this problem.
For example.
Product combinations should disappear if a certain combo is not currently in stock. For example on one product we might have S M L and 5 color variations, so 15 options. But maybe we only have size M in one color. The customer has to click through each color to find what is available as all colors show up if there is even one size M color available. It's only a problem when combos are partially out of stock.
It is necessary to make it work for the block as in the screenshot.
I would be very grateful for any help. Thanks in advance. Best Regards. Aleksandrs
-1502685 0You can open an interactive shell by right-clicking on the project, selecting Scala-> Create interpreter in XYZ.
-9960073 0You can use mktime() or strtotime()
$input_time = mktime(0,0,0,$_POST['m']+1,0,$_POST['y']); if ($input_time < time()){ print '<p class = "error">Date has elapsed</p>'; }
-1769169 0 Toy can try something like this
declare @t table (i int, d datetime) insert into @t (i, d) select 1, '17-Nov-2009 07:22:13' union select 2, '18-Nov-2009 07:22:14' union select 3, '17-Nov-2009 07:23:15' union select 4, '20-Nov-2009 07:22:18' union select 5, '17-Nov-2009 07:22:17' union select 6, '20-Nov-2009 07:22:18' union select 7, '21-Nov-2009 07:22:19' --order that I want select * from @t order by d desc, i declare @currentId int; set @currentId = 4 SELECT TOP 1 t.* FROM @t t INNER JOIN ( SELECT d CurrentDateVal FROM @t WHERE i = @currentId ) currentDate ON t.d <= currentDate.CurrentDateVal AND t.i != @currentId ORDER BY t.d DESC SELECT t.* FROM @t t INNER JOIN ( SELECT d CurrentDateVal FROM @t WHERE i = @currentId ) currentDate ON t.d >= currentDate.CurrentDateVal AND t.i != @currentId ORDER BY t.d
You must be carefull, it can seem that 6 should be both prev and next.
-19205962 0I also get this error sometimes but only on the emulator - seems like an emulator bug to me.
Android - Emulator internet access helped me a lot. :)
-3263295 0This has worked for me
$(window).bind("resize", function(e){ // do something });
You are also missing the closing bracket for the resize function;
-40045543 0 Rearrange and save images in gallery using jQuery,php,MySQLI've a dynamic gallery created with php and MySQL. Images are loaded from database tables and are shown according to auto increment id. However I need to sort the images by drag and drop system. I've implemented drag n drop with jquery. I need to rearrange them and their order should be stored in database table.
I've used the below drag and drop jquery and is working properly.
<script type="text/javascript"> $(function() { $("#dragdiv li,#dropdiv li").draggable({ appendTo: "body", helper: "clone", cursor: "move", revert: "invalid" }); initDroppable($("#dropdiv li,#dragdiv li")); function initDroppable($elements) { $elements.droppable({ activeClass: "ui-state-default", hoverClass: "ui-drop-hover", accept: ":not(.ui-sortable-helper)", over: function(event, ui) { var $this = $(this); }, drop: function(event, ui) { var $this = $(this); var li1 = $('<li>' + ui.draggable.html() + '</li>') var linew1 = $(this).after(li1); var li2 = $('<li>' + $(this).html() + '</li>') var linew2 = $(ui.draggable).after(li2); $(ui.draggable).remove(); $(this).remove(); var result = {}; var items = []; $('#allItems').each(function () { var type = $(this).attr('data-type'); $(this).find('li').each(function (index, elem) { items.push(this.innerHTML); }); result[type] = items; }); // alert(items); alert($('.lb').attr('id')); initDroppable($("#dropdiv li,#dragdiv li")); $("#dragdiv li,#dropdiv li").draggable({ appendTo: "body", helper: "clone", cursor: "move", revert: "invalid" }); } }); } }); </script>
The php n MySQL code for display images in gallery is given below
<div class="box-content" id="maindiv"> <br> <div id="dragdiv"> <?php $sql1=mysql_query("select bnr_img_id,bnr_img_name,img_cap from xhr_bnr_images where bnr_img_par='$id' order by bnr_img_id desc "); $n1=mysql_num_rows($sql1); if($n1>0) { ?> <ul id="allItems" runat="server" class="col-md-12" > <?php while($row1=mysql_fetch_array($sql1)) { ?> <li> <div class="lb" id="<?php echo $row1['bnr_img_id'];?>"> <img src="banner/<?php echo $row1['bnr_img_name'];?>" width="177px" height="150px"> <br/><br/> <div><input id="cap<?php echo $row1['bnr_img_id'];?>" value="<?php echo $row1['img_cap'];?>" onblur="update_caption('<?php echo $row1['bnr_img_id'];?>')" style="font-size:12px;font-weight:normal;width:180px;" type="text"></div> <a href="javascript:void(0);" onclick="del_this('<?php echo $row1['bnr_img_id'];?>','<?php echo $row1['bnr_img_name'];?>')">delete</a> </div> </li> <?php } ?> </ul> <?php } ?> </div> </div>
I need to get the replaced image id and their values should be shuffled when dragged.
Captions of the images updated by onblur function and its id will be send to another php file via ajax
-20977271 0You have to enclose the value of pm in quotation marks too:
result = Evaluate({@DBlookup("":"";"":"";"admin";"} & pm & {";1)})
This way it is recognized as a string.
Example:
If pm has a string value "Domino" then Evaluate string has to look like this:
@DBlookup("":"";"":"";"admin";"Domino";1)
but in your original formula version it would be
@DBlookup("":"";"":"";"admin";Domino;1)
BTW, the code would break if pm would contain a quotation mark. If you are sure that can't happen then the code is fine.
-2778629 0 TLS/SRP in browsers?Is there a plan or existing implementation of RFC 5054 in any of the major browsers yet?
If nobody has an implementation yet, then which major browsers have it on their roadmap? Where?
-22163107 0No it is not equivalent
If you want to support only jQuery 1.8+ then you can use .addBack() - Demo
var foo = $some.find(theCriteria).addBack(theCriteria);
else you can use .add
var foo = $some.find(theCriteria).add($some.filter(theCriteria));
It is not the same because of 2 reasons Demo: Fiddle
Okay this has baffled me. My script works in Mozilla but not IE. I get this error in IE:
Warning: move_uploaded_file(uploads/properties/yh96gapdna8amyhhmgcniskcvk9p0u37/) [function.move-uploaded-file]: failed to open stream: Is a directory in /homepages/19/d375499187/htdocs/sitename/include/session.php on line 602 Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/phpJkiaF3' to 'uploads/properties/yh96gapdna8amyhhmgcniskcvk9p0u37/' in /homepages/19/d375499187/htdocs/sitename/include/session.php on line 602
my code at Session.php is:
function addPhoto($subphotoSize,$subphotoType,$subphotoTmpname,$subphotoDesc,$subfieldID,$subsessionid){ global $database, $form; /* Get random string for directory name */ $randNum = $this->generateRandStr(10); $maxFileSize = 2500000; // bytes (2 MB) $filerootpath = PHOTOS_DIR.$subsessionid."/"; if($subphotoType == "image/png"){ $filename = $randNum.".png"; } else if ($subphotoType == "image/jpeg"){ $filename = $randNum.".jpg"; } $fullURL = $filerootpath.$filename; /* Image error checking */ $field = "photo"; if(!$subphotoTmpname){ $form->setError($field, "* No file selected"); } else { if($subphotoSize > $maxFileSize) { $form->setError($field, "* Your photo is above the maximum of ".$maxFileSize."Kb"); } else if (!is_dir($filerootpath)){ mkdir($filerootpath,0777); chmod($filerootpath,0777); } move_uploaded_file($subphotoTmpname, "$fullURL"); } /* Errors exist, have user correct them */ if($form->num_errors > 0){ return 1; //Errors with form } else { if($subfieldID == "1"){ // If the first field... $is_main_photo = 1; } else { $is_main_photo = 0; } if(!$database->addNewPhoto($ownerID,$subphotoDesc,$fullURL,$userSession,$is_main_photo, $subsessionid)){ return 2; // Failed to add to database } } return 0; // Success }
It creates the folder no problem but doesnt do anything else.
-4437653 0There is no built-in looping for nested structures (given the depth of nesting could be arbitrary). You have several options.
Flatten the 2D vector into a single dimensional vector and iterate over that or, Use something like for_each
, e.g.
template <typename T> struct do_foo { void operator()(T v) { // Use the v } }; template <typename Handler, typename Container> struct handle_nested { void operator()(Container const& internal) { // inner loop, container type has been abstracted away and the handler type for_each(internal.begin(), internal.end(), Handler()); } }; // outer loop for_each(foo.begin(), foo.end(), handle_nested<do_foo<int>, std::vector<int> >());
-28601530 0 Change your menthod to
private void fadingAnimation() { Animation fadeIn = new AlphaAnimation(0, 1); fadeIn.setInterpolator(new DecelerateInterpolator()); //add this fadeIn.setDuration(2000); AnimationSet animation1 = new AnimationSet(false); //change to false final AnimationSet animation2 = new AnimationSet(false); //change to false final AnimationSet animation3 = new AnimationSet(false); //change to false animation1.addAnimation(fadeIn); animation1.setAnimationListener(new Animation.AnimationListener(){ @Override public void onAnimationStart(Animation arg0) { } @Override public void onAnimationRepeat(Animation arg0) { } @Override public void onAnimationEnd(Animation arg0) { text_1.setVisibility(View.VISIBLE); text_2.startAnimation(animation2); } }); animation2.addAnimation(fadeIn); animation2.setAnimationListener(new Animation.AnimationListener(){ @Override public void onAnimationStart(Animation arg0) { } @Override public void onAnimationRepeat(Animation arg0) { } @Override public void onAnimationEnd(Animation arg0) { text_2.setVisibility(View.VISIBLE); text_3.startAnimation(animation3); } }); animation3.addAnimation(fadeIn); animation3.setAnimationListener(new Animation.AnimationListener(){ @Override public void onAnimationStart(Animation arg0) { } @Override public void onAnimationRepeat(Animation arg0) { } @Override public void onAnimationEnd(Animation arg0) { text_3.setVisibility(View.VISIBLE); } }); text_1.startAnimation(animation1); }
-35014427 0 You can use regex for your copy (under "Artifacts to copy")-
dev\downloadAgents\target\dependency\ios***.*
** - all folders under ios
*.* - all file types
You can also specify the target directory, and you also have a flag for "Flatten directories". This will move all the files without the hierarchy of the folders (flat to your target directory)
Feel free to look at the plugin's home page: https://wiki.jenkins-ci.org/display/JENKINS/Copy+Artifact+Plugin
-33586292 0MSIs can be authored per-user or per-machine. Per-user installs won't ask for elevation by default. Per-machine installs will ask for elevation once they hit the InstallExecuteSequence.
-32058029 0 Function returning REF CURSORI have package like this:
CREATE OR REPLACE PACKAGE product_package AS TYPE t_ref_cursor to IS REF CURSOR; FUNCTION get_products_ref_cursor RETURN t_ref_cursor; END product_package; CREATE OR REPLACE PACKAGE BODY product_package AS FUNCTION get_products_ref_cursor is RETURN t_ref_cursor IS products_ref_cursor t_ref_cursor; BEGIN OPEN products_ref_cursor FOR SELECT product_id, name, price FROM Products; RETURN products_ref_cursor; END get_products_ref_cursor; END product_package;
My question is, how can I use function get_products_ref_cursor (ref cursor) to get list of products?
-2974184 0Each one is a different type execution.
ExecuteScalar is going to be the type of query which will be returning a single value.
An example would be returning a generated id after inserting.
INSERT INTO my_profile (Address) VALUES ('123 Fake St.'); SELECT CAST(scope_identity() AS int)
ExecuteReader gives you a data reader back which will allow you to read all of the columns of the results a row at a time.
An example would be pulling profile information for one or more users.
SELECT * FROM my_profile WHERE id = '123456'
ExecuteNonQuery is any SQL which isn't returning values, but is actually performing some form of work like inserting deleting or modifying something.
An example would be updating a user's profile in the database.
UPDATE my_profile SET Address = '123 Fake St.' WHERE id = '123456'
Check out this book, The Elements of Computing Systems: Building a Modern Computer from First Principles it takes you step by step through several aspects of designing a computer language, a compiler, a vm, the assembler, and the computer. I think this could help you answer some of your questions.
-13186425 0This gives the averages Medians are a pain in SQL. Simple way to calculate median with MySQL gives some ideas. The two inner queries give the result sets to median over were there a median aggregate.
Select times.eventName, avg(times.timelapse) as avg_to_fail, avg(times2.timelapse) as avg_to_start From ( Select starts.id, starts.eventName, TimestampDiff(SECOND, starts.eventTime, Min(ends.eventTime)) as timelapse From Test as starts, Test as ends Where starts.eventName != 'start' And ends.eventName = 'start' And ends.eventTime > starts.eventTime Group By starts.id ) as times2 Right Outer Join ( Select starts.id, ends.eventName, TimestampDiff(SECOND, starts.eventTime, Min(ends.eventTime)) as timelapse From Test as starts, Test as ends Where starts.eventName = 'start' And ends.eventName != 'start' And ends.eventTime > starts.eventTime Group By starts.id ) as times On times2.EventName = times.EventName Group By Times.eventName
To aid understanding I'd first consider
Select starts.id, ends.eventName, starts.eventTime, ends.eventTime From Test as starts, Test as ends Where starts.eventName = 'start' And ends.eventName != 'start' And ends.eventTime > starts.eventTime
This is the essence of the inner query times
without the group by and the min statement. You'll see this has a row combining every start event with every end event where the end event is after the start event. Call this X.
The next part is
Select X.startid, X.endeventname, TimestampDiff(SECOND, X.starttime, Min(x.endTime)) as timelapse From X Group By X.startid
The key here is that Min(x.endTime) combines with the group by. So we're getting the earliest end time after the start time (as X already constrained it to be after). Although I've only picked out the columns we need to use, we have access to start time id, end time id start event, end event, start time, min(end time) here. The reason you can adapt it to find the avg_to_start is because we pick the interesting event name, as we have both.
SQL Fiddle: http://sqlfiddle.com/#!2/90465/6
-34774201 0What I ended up having to do for this to work properly was do the logic for if the value was passed or not and then add an attribute manually to my button using Attributes.Add().
'Logic for button enable If (username Is Nothing) Then eastOpen.Attributes.Add("disabled", "disabled") Else
-28750380 0 An alternative to emmanuel's answer is to add some padding to the a
tag:
ul { list-style-type:none; } li { float:left; } a { background:grey; color:white; text-decoration:none; padding: 10px 20px 10px 20px; margin-right:1px; }
See it in action here: http://jsfiddle.net/rufneu0w/1/
-38595693 0I think the following is a much more natural way to describe your domain
class Location { String name static hasMany = [preparedToWork: Assessor] } class Assessor { //Some Properties static belongsTo = [Location] static hasMany = [preparedToWork: Location] }
Then you can retrieve all of the assessors who are prepared to work in a certain location with
Assessor.executeQuery( "from Assessor a join a.preparedToWork l where l.id = ?", [locationId])
-25722817 0 Solr Qtime difference to real time i am trying to find out what causes the difference between the Qtime and the actual response time in my Solr application. The SolrServer is running on the same maschine as the program generating the queries. I am getting Qtimes in average around 19ms but it takes 30ms to actually get my response. This may sound like it is not much, but i am using Solr for some obscure stuff where every millisecond counts.
I figured that the time difference is not caused by Disk I/O since using RAMDirectoryFactory did not speed up anything.
Using a SolrEmbeddedServer instead of a SolrHttpServer did not cause a speedup aswell (so it is not Jetty what causes the difference?)
Is the data transfer between the query-program and the Solr-instance causing the time difference? And even more important, how can i minimize this time?
regards
-34903358 0You don't need to refresh page.
Add callback to load. In callback initialize/apply your js library (for controlling datatable).
$("#filebody").load("@Url.Action("Attachments", new {collaborationId = Model.Collaboration.Id})");
to
$("#filebody").load("@Url.Action("Attachments", new {collaborationId = Model.Collaboration.Id})", function( response, status, xhr ) { //Apply Datatable js library in here });
Because you are removing elements at #filebody and adding new elements. So you should apply your js library to the new elements.
-38223729 0 How to suppress talkback programatically?Is there any way to make talkback to suppress when I open my application and resume when I stop my Application?
-22215248 0 Get user Geolocation when user uses modemI have an application that detect user's positions, uses geolocation and show it in map (google maps API)
The application work properly when user using wifi, it show user's current positions but if the user using modem,the application show isp's (Internet service provider) position not the current user's position...
How i can solved this? anysolutions? thanks before..
-20346999 0FIM doesn't do authentication. Instead, it does the user management and synchronization piece.
You would want to integrate with one of the directories FIM is synchronizing. If your app is within the firewall, you would typically use AD or LDAP (Kerberos-based). If your app is outside of the firewall, you would typically use Azure Active Directory or another SAML-based Identity Provider.
-9713898 0I'm sorry but I don't use makegood but I do know that xdebug has a function you can call from the code to trigger a break.
xdebug_break();
bool xdebug_break()
Emits a breakpoint to the debug client. This function makes the debugger break on the specific line as if a normal file/line breakpoint was set on this line.
I hope this will be of some help.
-597703 0You could also use Commodore 64 emulator. It start's right from BASIC.
-39925635 0I think it's actually not need because WidgetsModule is same as FormsModule (@angular/forms). WidgetsModule is user-defined module and FormsModule provided by angular. That's the only difference. Both of this module are used for doing some functionality.
So just think about how we can declare FormsModule once and use it in all other module, if you understood that then the problem is solved.
Just vist the following link One single NgModule versus multiples ones with Angular 2
-2767749 0If you have control over both domains, you can try a cross-domain scripting library like EasyXDM, which wrap cross-browser quirks and provide an easy-to-use API for communicating in client script between different domains using the best available mechanism for that browser (e.g. postMessage if available, other mechanisms if not).
Caveat: you need to have control over both domains in order to make it work (where "control" means you can place static files on both of them). But you don't need any server-side code changes.
In your case, you'd add javascript into one or both of your pages to look at the location.href, and you'd use the library to call from script in one page into script in the other.
Another Caveat: there are security implications here-- make sure you trust the other domain's script!
-21012601 0I am not sure whether I understand your question correctly or not.
We can get the iframe document by calling
iframeEl.contentWindow.document
Then we can control the html, css inside it.
Be careful about the same origin policy:
We can only control the iframe the same origin as the main page.
-1198893 0 Access to global data in a dll from an exported dll functionI am creating a C++ Win32 dll with some global data. There is a std::map defined globally and there are exported functions in the dll that write data into the map (after acquiring a write lock, ofcourse).
My problem is, when I call the write function from inside the dll DllMain, it works without any problems. But when I load the dll from another program and call the function that writes data into the global map, it gives me this error:
WindowsError: exception: access violation reading 0x00000008
Is there something that can be done about this? The same function when called from DllMain has access to the global data in the dll, but when called from a different process, it doesn't have access to the global data. Please advice.
I am using the TDM-MinGW gcc 4.4.0 Compiler.
EDIT: Ok, I've figured out what the problem is, and thanks for the help guys, but the problem was not with a constructor issue or inability to have maps in global space, but an issue in the boost::python that I'm using. I had tested it, but since I was calling the dll from within python or maybe something, the urllib2 module wasn't getting loaded into the dll. Now I have to see how to fix it.
-39834204 0 Multiple nested AJAX calls in jQuery: How to do it right, without falling back to synchronous?I know, there already are a lot of questions concerning AJAX and Synchronicity here, but I somehow did not find the right answer to my cause. Please be gentle, I am a noob, so, this might be a duplicate. Still, even hinting to that might help me and others finding an appropriate answer.
The Function
$.fn.facebookEvents = function(options){ var fbEvents = 'https://graph.facebook.com/'+options.id+'/events/?access_token='+options.access_token+'&since=now&limit=500'; var events = []; $.when($.getJSON(fbEvents)).then(function(json){ $.each(json.data, function(){ $.getJSON('https://graph.facebook.com/'+this.id+'/?access_token='+options.access_token, function(jsonData){ events.push(jsonData); console.log(events); // here array "events" is filled successively }); console.log(events); // here array "events" remains empty }); }).done(function(){ $("#fb_data_live").html( $("#fb_events").render(events) ); }); };
What happens in this function, is an AJAX Call (via jQuerys getJSON shorthand) for the event list of a Facebook Page. This will return a list of JSON objects representing each date. Example of one object as response:
{ "end_time": "2017-03-16T23:00:00+0100", "location": "Yuca K\u00f6ln", "name": "K\u00f6rner // G\u00e4nsehaut Tour 2017 // K\u00f6ln", "start_time": "2017-03-16T20:00:00+0100", "timezone": "Europe/Berlin", "id": "985939951529300" },
Unfortunately, these are missing the details we need. They are hidden (nested) and can be found, after making a second getJSON (line 8 in the function), using the individual "id" of each object. Now Facebook replies:
{ "description": "http://www.eventim.de/koerner\nTickets ab sofort exklusiv auf eventim.de und ab MI 07.09. \u00fcberall wo es Tickets gibt sowie auf contrapromotion.com.", "end_time": "2017-03-16T23:00:00+0100", "is_date_only": false, "location": "Yuca K\u00f6ln", "name": "K\u00f6rner // G\u00e4nsehaut Tour 2017 // K\u00f6ln", "owner": { "name": "K\u00f6rner", "category": "Musician/Band", "id": "366592010215263" }, "privacy": "OPEN", "start_time": "2017-03-16T20:00:00+0100", "timezone": "Europe/Berlin", "updated_time": "2016-09-28T10:31:47+0000", "venue": { "name": "Yuca K\u00f6ln" }, "id": "985939951529300" }
Et voila, the details I was looking for. After making this second (nested) AJAX call, I push the JSON data in the array "events" (line 12).
The Problem
This should fill up the array with every .each iteration. However, take a look at the two 'console.logs'. The first one returns the filled array, the second one returns an empty array... If the AJAX calls are being made synchronously (which is not how it is supposed to be), e.g. by adding $.ajaxSetup({async: false});
prior to the function, it works fine however. The array is filled and can be rendered (line 18).
The Question
How can this behaviour be explained and how can this function be done right? I know, there must be a way using deferred and promises? I thought i did, by using .when.then.done... obviously I erred.
With best regards, Julius
-34653126 0If SaveChanges
fails, then you will need to rollback your entity's values back to what they originally were.
In your DbContext
class, you can add a method called Rollback
, it'll look something like this:
public class MyDbContext : DbContext { //DataSets and what not. //... public void Rollback() { //Get all entities var entries = this.ChangeTracker.Entries().ToList(); var changed = entries.Where(x => x.State != EntityState.Unchanged).ToList(); var modified = changed.Where(x => x.State == EntityState.Modified).ToList(); var added = changed.Where(x => x.State == EntityState.Added).ToList(); var deleted = changed.Where(x => x.State == EntityState.Deleted).ToList(); //Reset values for modified entries foreach (var entry in modified) { entry.CurrentValues.SetValues(entry.OriginalValues); entry.State = EntityState.Unchanged; } //Remove any added entries foreach (var entry in added) entry.State = EntityState.Detached; //Undo any deleted entries foreach (var entry in deleted) entry.State = EntityState.Unchanged; } }
You can simply call this method in your catch
:
try { dataEntities.SaveChanges(); } catch (Exception oops) { //Rollback all changes dataEntities.Rollback(); }
Note that INotifyPropertyChanged
will need to be implemented on properties that are bound to the view, this will ensure that any changes that the rollback performs will be pushed back to the view.
I have this question many times and bored while trying to find good solution. Dont understand why microsoft not include method which can easy determine mode of display page: "normal display" or in "design mode". It have many advices of check different variables, but it cant uniquely say that page in design on different type of page(webpart page and wiki page) and on postback or not.
Is finally tired me and i write this:
public static bool IsDesignTime() { if (SPContext.Current.IsDesignTime) return true; if (HttpContext.Current.Request.QueryString["DisplayMode"] != null) return true; var page = HttpContext.Current.Handler as Page; if(page == null) return false; var inDesign = page.Request.Form["MSOLayout_InDesignMode"]; var dispMode = page.Request.Form["MSOSPWebPartManager_DisplayModeName"]; var wikiMode = page.Request.Form["_wikiPageMode"]; var we = page.Request.Form["ctl00$PlaceHolderMain$btnWikiEdit"]; if (inDesign == null & dispMode == null) return false; //normal display if (we == "edit") return true; //design on wiki pages if (page is WikiEditPage & page.IsPostBack & inDesign == "" & dispMode == "Browse" & wikiMode == "") return false; //display wiki on postback if (inDesign == "" & dispMode == "Browse" & (wikiMode == null | wikiMode == "")) return false; //postback in webpart pages in display mode if (inDesign == "0" & dispMode == "Browse") return false; //exiting design on webpart pages return true; }
Does anybody have better solution?
-21751558 0i think it should be better to have a user skill mapping table with fields user_id & skill_id. Every time when a user adds a skill, enter it with in mapping table so it will be easier to use this data in future
-29739501 0 Runtime error: Could not load file or assembly 'Microsoft.Owin, Version=3.0.0.0....Azure mobile servicesI have downloaded the ToDOService project from the Azure managementprotal after I created a Mobile service. Initially it had a lot of errors as the Nuget packages were outdated. I Uninstalled the Azure mobile services .net backend
package and its dependencies. Later I again installed all the packages manually and then I could build the project successfully. Somehow, when I run the service project I get this error:-
Could not load file or assembly 'Microsoft.Owin, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.Owin, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified. Source Error: Line 18: Line 19: // Use this class to set WebAPI configuration options Line 20: HttpConfiguration config = ServiceConfig.Initialize(new ConfigBuilder(options)); Line 21: Line 22: // To display errors in the browser during development, uncomment the following Source File: ...\MyProject\MyService\App_Start\WebApiConfig.cs Line: 20
My web.config looks like this
<dependentAssembly> <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" /> </dependentAssembly>
I also tried to update the assembly to the latest, but could not be updated as Ver 3.0.1 is not compatible with its other dependencies.
any help would be appreciated. Thanks
-1850127 0How large of a deployment is this? It might be better to execute the deployment of .net 3.5 as a previous enterprise deployment. And then follow up with your application. For enterprise wide deployments there are tools like Zenworks, and others that deploy applications and other file sets "invisibly" to the user.
Have you confirmed that your application will not function with .net 2.0?
If your application is only files, and does not have registry settings, etc. you may be able to copy the files to the users' computers, and copy a shortcut to their desktop, or startmenu certainly without their intervention, and probably with out their knowledge. If you have admin level credentials that apply to all your PCs and can get a list of all you r PCs' network names, you could "push" the files out through the C$ share, or if they log in to a domain you can have them "pull" them via a login-script.
There are actually lots of ways to do this. If you have server admins, they can help you with this.
-8437176 0 App load screen in AndroidOn iOS you create a load screen for when the app loads, is there a similar thing in Android. When my app loads, I get a black screen until it opens.
-26907654 0From the source:
The solution is to edit the view by adding an Argument of Node: Nid. Set it to Display all values, Validator: Node, and Argument type of Node ID.
Set Action to take if argument does not validate: Hide view / Page not found (404). Update the Argument and save the view.
-16374996 0 mysqldump.exe not taking full backup of mysql databaseI have a procedure for backing up MySQL database.And also i have different MySQL servers. This procedure works on some of MySQL servers.But on some of servers it won't works proper and create a backup file with the size of 1kb.
public void DatabaseBackup(string ExeLocation, string DBName) { try { string tmestr = ""; tmestr = DBName + "-" + DateTime.Now.ToString("hh.mm.ss.ffffff") + ".sql"; tmestr = tmestr.Replace("/", "-"); tmestr = "c:/" + tmestr; StreamWriter file = new StreamWriter(tmestr); ProcessStartInfo proc = new ProcessStartInfo(); string cmd = string.Format(@"-u{0} -p{1} -h{2} {3}", "uid", "pass", "host", DBName); proc.FileName = ExeLocation; proc.RedirectStandardInput = false; proc.RedirectStandardOutput = true; proc.Arguments = cmd; proc.UseShellExecute = false; proc.CreateNoWindow = true; Process p = Process.Start(proc); string res; res = p.StandardOutput.ReadToEnd(); file.WriteLine(res); p.WaitForExit(); file.Close(); } catch (IOException ex) { } }
Can any one tell me what is the problem and how can i solve it.
-38627339 0 Is it possible to nest SQL tables?I am wondering if it is possible to nest SQL tables? Or it the best practise to give the id to for example a person in the first table that is the key to the second table?
-33402810 0 How can I replace "true" and "false" in java?i need change the values for boolean variables, for example:
change this: boolean x = true; System.out.print(x); //console: true for this:
boolean x = true; System.out.print(x); //console: 1
Sorry for my bad engish, thanks.
This is my code
final boolean[] BOOLEAN_VALUES = new boolean [] {true,false}; for (boolean a : BOOLEAN_VALUES) { boolean x = negation(a); String chain = a+"\t"+x; chain.replaceAll("true", "1").replaceAll("false","0"); System.out.println(chain); } negation is a method: public static boolean negation(boolean a){ return !a; }
as you can see, i try using .replaceAll, but its not working, when i executed, this is the output:
a ¬a ---------------- true false false true
i really dont see my error.
-20802405 0No need to call awk
several times. You can do everything with a single awk
script. Try the following command:
awk -f t.awk GW2.log
where t.awk
is:
NR==5 { RDS_T=$1 } NR==6 { RDS_P=$1" "$2 } NR==8 { RDS_C1=$1" "$2 } NR==9 { RDS_C2=$1" "$2 } NR==16 { ALGN_T=$1 } END { fmt="%-12s %-12s %-18s %-18s %-18s %-18s\n" printf fmt, "File", "Reads", "Paired reads", "Conc reads1", "Conc Reads2", "Total align" printf fmt, "GW2.log", RDS_T, RDS_P, RDS_C1, RDS_C2, ALGN_T }
with output:
File Reads Paired reads Conc reads1 Conc Reads2 Total align GW2.log 3746112 3746112 (100.00%) 581094 (15.51%) 227387 (6.07%) 28.15%
-21458798 0 I have an idea. If you can get the element in evaluate you can fireEvent on it. So create a function that will fireEvent.
function casperFireEvent(element, eventType) { if ("createEvent" in document) { var evt = document.createEvent("HTMLEvents"); evt.initEvent(eventType, false, true); element.dispatchEvent(evt); } else { element.fireEvent("on"+eventType); } }
Then on you loop you can do this :
this.evaluate(casperFireEvent(document.getElementById('links[i]'), 'click'));
I'm not sure it it's conventional but that's a start.
-6919874 0Flymake sets a 1-second timer for each buffer that has flymake-mode enabled, to check to see if the buffer has been modified more than flymake-no-changes-timeout
seconds ago.
If you have a lot of buffers open (several hundred) in flymake-mode then this can devour a surprisingly large amount of CPU, I've a patched version of flymake that has a single global timer which fixes this, and a few other issues: https://github.com/illusori/emacs-flymake
This might not be the same issue for you, but for me it would lock Emacs up when opening in desktop-mode with 600 files open, I'd be lucky to get one keypress processed every 15 minutes.
-20602682 0 Background image looks brighter on SafariBackground image on Safari looks brighter compare to any other browsers.
When I remove background-size: cover
, image colors looks like expected.
How do I keep normal colors and background-size: cover
at the same time?
body { background-image: url('https://lh5.googleusercontent.com/-QpCNI9iXEEE/Uq5gxSpxOJI/AAAAAAAAABM/HwVK1nETGPE/I/philadelphia_night_view.jpg'); background-repeat: no-repeat; background-size: cover; }
OS X Mountain Lion 10.8.3, Safari: 6.0.3
Do you mean words or characters? If you want to count words, a very naïve approach is splitting by whitespace and check the length of the resulting array:
if ($("#et_newpost_content").text().split(/\s+/).length < 250) { alert('Message must be at least 250 words.') }
If you mean characters, then it's much easier:
if ($("#et_newpost_content").text().length < 250) { alert('Message must be at least 250 characters.') }
-14295380 0 SmartGWT has extensive built-in support for Selenium. Read about it here:
http://www.smartclient.com/smartgwtee-latest/javadoc/com/smartgwt/client/docs/UsingSelenium.html
Do not attempt to set your own DOM identifiers. This is unnecessary, and is the wrong approach.
-35769329 0 Replace month number with month name using current phone formatI'm using joda-time to process DateTime. I got date format of phone using this:
SimpleDateFormat dateFormat = (SimpleDateFormat) DateFormat.getDateFormat(context); String datePattern = dateFormat.toPattern();
And then I format a DateTime to String using this:
DateTimeFormatter dateFormatter = DateTimeFormat.forPattern(datePattern); dateFormatter.print(dateTime)
Example, it will show DateTime as String:
3/1/2016
But i want it displays:
March/1/2016
or
Mar/1/2016
How can i do that?
-15155844 0Sounds like your data might be better suited to being in one index, in which case you could use and/or filters to combine a geo distance filter with a type filter.
Another option would be to use the indicies query
-27709401 0It turns out that Microsoft does not support SHA-2 for driver signing on Windows 7.
-10278431 0In some cases, you might want to sign a driver package with two different signatures. For example, suppose you want your driver to run on Windows 7 and Windows 8. Windows 8 supports signatures created with the SHA256 hashing algorithm, but Windows 7 does not. For Windows 7, you need a signature created with the SHA1 hashing algorithm.
Suppose you want to build and sign a driver package that will run on Windows 7 and Windows 8 on x64 hardware platforms. You can sign your driver package with a primary signature that uses SHA1. Then you can append a secondary signature that uses SHA256. You can use the same certificate for both signatures, or you can use separate certificates. Here are the steps to create the two signatures using Visual Studio.
As you mentioned, MobileTerminal is probably what you're looking for. This project is open-source and you can start of it. AFAIK now it runs only on jailbroken devices, but you can definitely cut out only the terminal emulation (& screen manipulation, handling input and output, ...) and build your project on it.
Building a terminal from scratch is quite complicated and complex, so I suggest you start with this or some other open source project.
I am not aware of any ready-to-use component, so you'll probably have to put some work into integrating the terminal into your app.
-33427601 0When the mouse is dragging a div element over a droppable area, pressing the ESC key should drag the element to an area that is not droppable
I´ve created a demo
of a possible solution that you can check in plunker.
As stated by @ioneyed
, you can select the dragged element directly using the selector .ui-draggable-dragging
, which should be more efficient if you have lots of draggable elements.
The code used is the following, however, apparently it's not working in the snippet section. Use the fullscreen
feature on the plunker or reproduce it locally.
var CANCELLED_CLASS = 'cancelled'; $(function() { $(".draggable").draggable({ revert: function() { // if element has the flag, remove the flag and revert the drop if (this.hasClass(CANCELLED_CLASS)) { this.removeClass(CANCELLED_CLASS); return true; } return false; } }); $("#droppable").droppable(); }); function cancelDrag(e) { if (e.keyCode != 27) return; // ESC = 27 $('.draggable') // get all draggable elements .filter('.ui-draggable-dragging') // filter to remove the ones not being dragged .addClass(CANCELLED_CLASS) // flag the element for a revert .trigger('mouseup'); // trigger the mouseup to emulate the drop & force the revert } $(document).on('keyup', cancelDrag);
.draggable { padding: 10px; margin: 10px; display: inline-block; } #droppable { padding: 25px; margin: 10px; display: inline-block; }
<div id="droppable" class="ui-widget-header"> <p>droppable</p> </div> <div class="ui-widget-content draggable"> <p>draggable</p> </div> <div class="ui-widget-content draggable"> <p>draggable</p> </div> <div class="ui-widget-content draggable"> <p>draggable</p> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.css">
My goal is to place four divs within a single "container" div. Here's my code so far:
HTML
<body> <div id="navBar"> <div id="subDiv1"> </div> <div id="subDiv2"> </div> <div id="subDiv3"> </div> <div id="subDiv4"> </div> </div> </body>
CSS
#navBar { width: 75%; height: 75px; margin-left: 25%; margin-right: auto; margin-top: 2%; border-width: 1px; border-style: solid; border-radius: 10px; border-color: #008040; overflow: hidden; } #subDiv1, #subDiv2, #subDiv3, #subDiv4 { width: 25%; height: 75px; border-width: 1px; border-color: #000; border-style: solid; } #subDiv1 { border-top-left-radius: 10px; border-bottom-left-radius: 10px; float: left; margin-left: 0%; } #subDiv2 { float: left; margin-left: 25%; } #subDiv3 { float: left; margin-left: 50%; } #subDiv4 { border-top-right-radius: 10px; border-bottom-right-radius: 10px; float: left; margin-left: 75%; }
As far as I know this is the only part of my code that's relevant to my question so I left some other parts out.. Don't mind the width and margin of the navBar, because it's actually within another container as well.
P.S I searched Google and StackOverFlow and I could not find an answer that was helpful. There were many questions about placing two divs within a single div, but none for aligning multiple divs within a single div.
Thanks for any help in advance!
-10566598 0No. You can't use VideoView with authenticated RTSP, even with rtsp://User:Password@Server. It won't work. It is possible to use authenticated RTSP on android but it's hard and you will have to do a lot of things by yourself.
-16222364 0Use Arrays.toString(method.getParameterTypeas())
if you want to see the types. Use loop if you want to iterate over them and use them:
for (Class<?> type : method.getParameterTypeas()) { // use the type }
-25887050 0 I suppose, you want to INNER JOIN
those tables like this:
SELECT * FROM ( SELECT pi.FighterId, FName, LName, PaymentDay, PaymentDescr, PaymentAmount, Active, ROW_NUMBER() OVER (PARTITION BY fi.FighterId ORDER BY PaymentDay DESC) rn FROM FightersInfo fi LEFT JOIN PaymentInfo pi ON pi.FighterId = fi.FighterId WHERE NOT EXISTS (SELECT * FROM PaymentInfo WHERE FighterId = fi.FighterId AND DATEDIFF(month, PaymentDay, GETDATE()) = 0 ) AND Active =1) t WHERE rn = 1
All the conditions on amount are removed for readability.
-40277883 0 Positioning and then making it responsiveHey I'm currently working on a responsive web design for school and it is a disaster. Currently setting up the website before making it responsive and the text and images aren't going where I need them to go. This is my coding for css so far:
body{ background-color: #cd76dd; font-family: 'Raspoutine Medium'; color:white; } #page-wrap{ width: 950px; margin: 0 auto; } #containerIntro h1{ font-family: 'AlphaClouds'; background-color: #7ac8ff; color:white; font-size: 45px; width: 100%; padding-bottom: 10px; position: static; bottom: 0; left: 0; } #containerIntro p{ font-family: 'AlphaClouds'; background-color: #7ac8ff; color:white; text-align: left; font-size: 70px; width: 100%; } h1: hover{ text-shadow: 0px 0px 20px white; } h1 p: hover{ text-shadow: 0px 0px 20px white; } h1{ position: absolute; left: 0; bottom: 0; } p{ background-color:#ffa1ff; color:white; text-align: left; padding-top: 20px; padding-bottom: 20px; padding-left: 10px; font-size: 17px; width: 450px; height: 100%; } h2{ background-color: #ffa1ff; color:white; text-align: left; padding-top: 20px; padding-left: 10px; font-size: 20px; border: 2px #ffa1ff solid; width: 450px; height: 100%; } h3{ background-color: #ffa1ff; color:white; text-align: left; font-size: 20px; padding-left: 10px; border: 2px #ffa1ff solid; width: 450px; height: 100%; } .gummy{ float: right; } .bubble{ float: right; position: relative; right: -130px; padding-top: 15px; } .pink{ float: left; position: relative; top: -145px; } .blue{ float: right; position: relative; top: -145px; } p.select{ background-color: #5d75ed; text-align: right; padding-bottom:10px; padding-top: 10px; font-size: 17px; width: 170px; float: right; margin-top: -850px; } p.archives{ background-color: #f9e075; text-align: right; padding-bottom: 10px; padding-top: 10px; padding-left: 10px; font-size: 17px; width: 170px; float: right; margin-top: -600px; } p.resources{ background-color: #ef5b66; padding-bottom: 10px; padding-top: 10px; font-size: 17px; width: 170px; float:right; margin-top: -500px; } div{ height: 287; width: 198; }
mock up for what it will look like
-39242333 0 Tensorflow : Implementing gradient for user op in C++?I'd ideally like the operation to be wholly self-contained (gradient and operation defined in same file). The official tutorial only highlights a python implementation. Does anyone know if it's possible to implement the gradient in C++, and how to go about it?
-7777487 0If the file is not opened, the line file = open(filePath, 'w')
fails, so nothing gets assigned to file
.
Then, the except
clause runs, but nothing is in file, so file.close()
fails.
The finally
clause always runs, even if there was an exception. And since file
is still None you get another exception.
You want an else
clause instead of finally
for things that only happen if there was no exception.
try: file = open(filePath, 'w') except IOError: msg = "Unable to create file on disk." return else: file.write("Hello World!") file.close()
Why the else
? The Python docs say:
The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try ... except statement.
In other words, this won't catch an IOError
from the write
or close
calls. Which is good, because then reason woudn't have been “Unable to create file on disk.” – it would have been a different error, one that your code wasn't prepared for. It's a good idea not to try to handle such errors.
I'm trying to make new icefaces project which generated using: ICEfaces 3.3.0 project integration for Eclipse. I didn't modify anything on the project. but when i try to run on the server, i got an error:
cannot Deploy MyProject
Deployment Error for module: MyProject:
Exception while loading the app : java.lang.Exception:
java.lang.IllegalStateException: ContainerBase.addChild:
start: org.apache.catalina.LifecycleException:
java.lang.NoSuchFieldError: SKIP_ITERATION
before that, I'm using ICEfaces 3.2.0 project integration for Eclipse and no problem.
I'm using Eclipse Indigo, GlassFish server 3, Mojarra 2.1.6
Thanks before
-21263350 0On Heroku, gems are installed within the vendor/bundle/ruby/<version>/gems
directory. I just checked my Heroku instance and confirmed this.
CML files get rendered as XML from the server because the server is telling Chrome it is XML with header Content-Type:application/xml
. When a local file is opened there is no Content-Type
header so Chrome guesses off of the file extension and in this case is not aware of CML. You could open a feature request for Chrome to read CML files as XML but I don't know if they will implement it: http://new.crbug.com
I assume you want to implement some sort of a loading screen or interface widget. (Did you know you can set the showBusyCursor on a remote object instance?)
There is no way to globally intercept the method calls on your remote objects though. You'll need to solve this by either:
Option 1 is a bit more advanced but will save you the boilerplate code that option 2 has.
-145227 0In my opinion, almost any release number scheme can be made to work more or less sanely. The system I work on uses version numbers such as 11.50.UC3, where the U indicates 32-bit Unix, and the C3 is a minor revision (fix pack) number; other letters are used for other platform types. (I'd not recommend this scheme, but it works.)
There are a few golden rules which have not so far been stated, but which are implicit in what people have discussed.
Now, in practice, people do have to release fixes for older versions while newer versions are available -- see GCC, for example:
So, you have to build your version numbering scheme carefully.
One other point which I firmly believe in:
With SVN, you could use the SVN version number - but probably wouldn't as it changes too unpredictably.
For the stuff I work with, the version number is a purely political decision.
Incidentally, I know of software that went through releases from version 1.00 through 9.53, but that then changed to 2.80. That was a gross mistake - dictated by marketing. Granted, version 4.x of the software is/was obsolete, so it didn't immediately make for confusion, but version 5.x of the software is still in use and sold, and the revisions have already reached 3.50. I'm very worried about what my code that has to work with both the 5.x (old style) and 5.x (new style) is going to do when the inevitable conflict occurs. I guess I have to hope that they will dilly-dally on changing to 5.x until the old 5.x really is dead -- but I'm not optimistic. I also use an artificial version number, such as 9.60, to represent the 3.50 code, so that I can do sane if VERSION > 900
testing, rather than having to do: if (VERSION >= 900 || (VERSION >= 280 && VERSION < 400)
, where I represent version 9.00 by 900. And then there's the significant change introduced in version 3.00.xC3 -- my scheme fails to detect changes at the minor release level...grumble...grumble...
NB: Eric Raymond provides Software Release Practice HOWTO including the (linked) section on naming (numbering) releases.
-6556981 0The using
statement is really the preferred solution. It's idiomatic in C#. These classes implement IDisposable
explicitly because they already provide a method that has closing semantics: Close
. My bet is that Dispose
calls Close
, or vice-versa. But you shouldn't count on that, and should always call Dispose
anyway.
In the end, all these are equivalent:
using
, which is preferred;Close
on the finally
block, and suppress the static analysis warnings or;Dispose
on the finally
: ((IDisposable)NewReader).Dispose();
Try cleaning the project. Also, are you using the google libraries for maps? You need to add a link to Google API.
-30202774 1 Python - remove parts of a stringI have many fill-in-the-blank sentences in strings,
e.g. "6d) We took no [pains] to hide it ."
How can I efficiently parse this string (in Python) to be
"We took no to hide it"?
I also would like to be able to store the word in brackets (e.g. "pains") in a list for use later. I think the regex module could be better than Python string operations like split().
-25676448 0You want to look at websockets. A good way to do this in PHP is with a library called "Ratchet":
Unfortunately websockets don't have very good cross-browser compatibility.
-561122 0You definitely need some kind of 'in code' element, because a lack of DLL will break things in a worse way than simply disabling the modules you had intended.
-9116346 0struct C { A a; B b; C(double ta[2], vector<double> tb) { a = A(ta[0],ta[1]); // or a.x = ta[0]; a.y = ta[1] b = tb; } };
then you can initialize with something like
C c = C( {0.0, 0.1} , vector<double> bb(0.0,5) );
-24428571 0 Asterisk: How can I filter the Dial event only to my extension I am making a Asterisk Client in C# WinForms using Asterisk.NET. My client is listening to one extension only.We can view the calls, reject or transfer etc to the calls coming to my extensions. I need source channel to transfer the call, and source channel can be got only from Dial Event. Recently, I noticed that The Dial Event happens everytime when any of the extension connected to the server starts dialling. I want to filter it out, only the call coming to my extension only.
void manager_Dial(object sender, DialEvent e) { CallingInfo.src_channel = e.Channel; }
e.dialString is giving me the Destination Extension number; But I don't know if it become null according to the server status. Moreover, what will happen if some external calls coming to me, I wont get Dial event or Source channel, Then it cannot be transferred. Right ?
-16604386 0 what is the function of attribute selected in combo box while fetching data from MYSQL in phpHello i am beginner in PHP. I am trying to fetch data from MYSQL and want to show in combo box but if user does not re selects the item from item list it highlights error that nothing is selected. Is there any php function to do this particular task ? I want that when the data of particular id is loaded in form and if without making any change in combo boxes data user cliks on submit then it must submit but in my case it shows that the fields are empty while data is here. Here is my Code
<li id="foli3" class="notranslate "> <label class="desc" id="title3" for="Field3"> what is the current occupation of your guardian? <span id="req_3" class="req">*</span> </label> <span> <select id="Field3" name="occupation" class="field select addr" tabindex="8" required > <option value="" selected="selected"><?php echo $rows['occupation']; ?></option> <option>Private Sector Employee</option> <option>Social Sector Employee</option> <option>Agriculturalist</option> <option>Businessman</option> <option>Government Employee</option> <option>Other</option> </select> </span> </li>
-10089327 0 One method may be to select the appropiate column range using the Visual mode (control+v)
Once selected, the search and replace can be done using (see this question)
%s/\%Vfoo/bar/g
A regular expression for not test can be found here: Regular expression to match string not containing a word?
-39429095 0 materialized view for for a duration with fast refresh such as last ten minutes12015 while creating MV in my 3rd step:
create table tab_2 as select * from tab_1; alter table tab_2 add constraint tab_2_pk primary key (col6,col7);
create materialized view log on my_schema.tab_2 with primary key (my_date) including new values;
create materialized view my_schema.ten_minute_data refresh fast as select * from my_schema.tab_2 mt where mt.my_date > sysdate-10/(24*60);
I am trying to create mv and mv_log in the same db as replacement of normal view to query and see the the result fast.
Please suggest if it such where clause is possible.
Thanks
-8598171 0 Workaround for DELETE ... LIMIT clause (SQL)I am working on a database query abstraction layer that supports SQLite.
Unfortunately, SQLite does not support the LIMIT
clause in DELETE (and UPDATE etc.) queries - except if compiled with a special flag in more recent versions.
So is there any workaround that I could implement so that that query type can still be supported?
-3395055 0To store the history of a page, the most popular and full featured/supported way is using hashchanges. This means that say you go from yoursite/page.html#page1
to yoursite/page.html#page2
you can track that change, and because we are using hashes it can be picked up by bookmarks and back and forward buttons.
You can find a great way to bind to hash changes using the jQuery History project http://www.balupton.com/projects/jquery-history
There is also a full featured AJAX extension for it, allowing you to easily integrate Ajax requests to your states/hashes to transform your website into a full featured Web 2.0 Application: http://www.balupton.com/projects/jquery-ajaxy
They both provide great documentation on their demo pages to explain what is happening and what is going on.
Here is an example of using jQuery History (as taken from the demo site):
// Bind a handler for ALL hash/state changes $.History.bind(function(state){ // Update the current element to indicate which state we are now on $current.text('Our current state is: ['+state+']'); // Update the page"s title with our current state on the end document.title = document_title + ' | ' + state; }); // Bind a handler for state: apricots $.History.bind('/apricots',function(state){ // Update Menu updateMenu(state); // Show apricots tab, hide the other tabs $tabs.hide(); $apricots.stop(true,true).fadeIn(200); });
And an example of jQuery Ajaxy (as taken from the demo site):
'page': { selector: '.ajaxy-page', matches: /^\/pages\/?/, request: function(){ // Log what is happening window.console.debug('$.Ajaxy.configure.Controllers.page.request', [this,arguments]); // Adjust Menu $menu.children('.active').removeClass('active'); // Hide Content $content.stop(true,true).fadeOut(400); // Return true return true; }, response: function(){ // Prepare var Ajaxy = $.Ajaxy; var data = this.State.Response.data; var state = this.state; // Log what is happening window.console.debug('$.Ajaxy.configure.Controllers.page.response', [this,arguments], data, state); // Adjust Menu $menu.children(':has(a[href*="'+state+'"])').addClass('active').siblings('.active').removeClass('active'); // Show Content var Action = this; $content.html(data.content).fadeIn(400,function(){ Action.documentReady($content); }); // Return true return true;
And if you ever want to get the querystring params (so yoursite/page.html#page1?a.b=1&a.c=2
) you can just use:
$.History.bind(function(state){ var params = state.queryStringToJSON(); // would give you back {a:{b:1,c:2}} }
So check out those demo links to see them in action, and for all installation and usage details.
Edit: After seeing your code, this is all you would have to do to use it with jQuery History.
Change:
$('.tabbed_content .tabs li a').live('click', function (e){ e.preventDefault(); switchTab($(this)); });
To:
// Bind a handler for ALL hash/state changes $.History.bind(function(state){ switchTab(state); });
Or if you plan to use jQuery History for other areas too, then we would want to ensure that we only call switchTab for our tabs and not all hashes:
// Bind a handler for ALL hash/state changes $.History.bind(function(state){ if ( $('.tabbed_content > .content > li[id='+state+']').length ) switchTab(state); });
We no longer use a onclick event, instead we bind to jQuery History as that will detect the hashchange. This is the most important concept to understand, as for instance if we bookmark the site then go back to it, we never clicked it. So instead we change our clicks to bind to the hashchange. As when we click it, bookmark it, back or forward, the hashchange will always fire :-)
-12627676 0 Passing Html tag in Update queryThere is an existing table in database where I want to update one column. If I right click on the table--->select edit 200 rows and try to edit the cell data it says that the cell is read-only. I am using SQL management studio 2008R2. So I was trying to update it using an update Query but I am pretty new to the SQL queries and the whole database thing. Is this the proper way to pass an HTML tag in queries?
UPDATE OutputTemplate SET emailText='(<p>Thank you for your gift of {Amount} to the {CommunityName}</p><br />Support & Charity Campaign.<br /> -------------------------------------------- --- Transaction Detail --- -------------------------------------------- <span>Credit Card Details</span> <span style="text-decoration: underline;">Personal Info Details & Amount</span>)' WHERE id='2'
It's showing some parsing error, incorrect syntax while executing the query.
Sorry to ask such a basic question but I tried to google it, unfortunatelly nothing showed up useful.
Thanks
-29932443 0It is solved. The code works as follows. I made a wrong drill down. Truly thanks, I have learned a lot:
class func jsonAsUSDAIdAndNameSearchResults (json: NSDictionary) -> [(name: String, idValue: String)] { var usdaItemsSearchResults: [(name: String, idValue: String)] = [] var searchResult: (name: String, idValue: String) if json["hits"] != nil { let results:[AnyObject] = json["hits"]! as [AnyObject] for itemDictionary in results { let fields: NSDictionary = itemDictionary["fields"]? as NSDictionary let name:String? = fields["item_name"] as? String let idValue:String? = itemDictionary["_id"]? as? String if (name? != nil && idValue? != nil) { searchResult = (name: name!, idValue: idValue!) usdaItemsSearchResults += [searchResult] } } } return usdaItemsSearchResults }
-23401900 0 Figured it out (don't ask me how). For anyone else looking for the answer, here's what I did.
I changed this:
// Ajaxify our Internal Links $body.ajaxify();
to this:
// Ajaxify our Internal Links $('.menuLeft,.menuRight').ajaxify();
I kept trying to add the menu classes here without the parentheses and single quotes. Once I got those in, everything fell into place. Now, only those menus are ajaxified.
-30174087 0This solution below was tested and it works fine.
First:
Remove onkeydown event of digit. It should be like this:
<input type="text" name="digit" id="digit" size="50" />
Remove onclick event of the button and set the id property.
<button class="btn" id="btnClick" title="send" type="button" >
create a input hidden in your html to store $cuser php var
<input type="hidden" name="cuser" id="cuser" val="<?php echo $cuser ?>" />
Replace your javascript to the following:
$(document).ready(function(){ $("#digit").keydown(function(event){ if (event.keyCode == 13 && event.shiftKey == 0) { alert("ok1"); filltxtarea($("#digit").val()); } }); $("#btnClick").click(function(){ filltxtarea($("#digit").val()); }); function filltxtarea(desctext) { var uchat = $("#cuser").val(); $(".chatboxcontent").append('<div class=chatboxmessage><span class="chatboxmessagefrom">' + uchat + ': </span><span class="chatboxmessagecontent">' + desctext + '</span></div>'); $('#digit').val(''); $('#digit').focus(); alert("ok2"); jQuery.ajax({ type: 'POST', url: 'chat.php', dataType: 'json', data: { "newrow": "desctext" }, success: function(response) { alert(response); } }) } });
Any doubts please let me know.
Hope it help.
-23975299 0Thanks for the responses. Very helpful. I decided to go with a proxy approach for which I found a simple solution here: http://www.paulund.co.uk/make-cross-domain-ajax-calls-with-jquery-and-php
For cut and paste simplicity I've added my code here.
I created a file called crossdomain.html. Included jquery library. Created the following Javascript function:
function requestDataByProxy() { var url = "http://UrlYouWantToAcccess.html"; var data = "url=" + url + "¶meters=1¶=2"; $.ajax({ url: "our_domain_url.php", data: data, type: "POST", success: function(data, textStatus, jqXHR){ console.log('Success ' + data); $('#jsonData').html(data); }, error: function (jqXHR, textStatus, errorThrown){ console.log('Error ' + jqXHR); } }); }
I also added a simple button and pre tag in HTML to load results:
<button onclick="requestDataByProxy()">Request Data By Proxy</button> <h3>Requsted Data</h3> <pre id="jsonData"></pre>
And then, the PHP file our_domain_url.php which uses cURL (make sure you have this enabled!)
<?php //set POST variables $url = $_POST['url']; unset($_POST['url']); $fields_string = ""; //url-ify the data for the POST foreach($_POST as $key=>$value) { $fields_string .= $key.'='.$value.'&'; } $fields_string = rtrim($fields_string,'&'); //open connection $ch = curl_init(); //set the url, number of POST vars, POST data curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_POST,count($_POST)); curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string); //execute post $result = curl_exec($ch); //close connection curl_close($ch); ?>
To me, this was a fairly straight-forward solution.
Hope this helps someone else!
Rob
-37986563 0Try to use this gem: https://github.com/net-ssh/net-ssh-gateway/
require 'net/ssh/gateway' gateway = Net::SSH::Gateway.new(@jumpoffIp, @jumpoffUser) gateway.open('ont-db01-vip', 1521, 1521) gateway.open('ont-db02-vip', 1521, 1521) res = %x[sqlplus #{@sqlUsername}/#{@sqlPassword}@'#{@sqlUrl}' @scripts/populateASDB.sql > output.txt] puts "populateDb output #{res}" gateway.shutdown!
-18745200 0 We did an htaccess edit for it.
<FilesMatch "\.(ttf|otf|eot)$"> <IfModule mod_headers.c> Header set Access-Control-Allow-Origin "*" </IfModule> </FilesMatch>
-17152024 0 Instead of looping through all your messages and calling the method that displays an alert for each of them, which results in the multiple alerts being displayed to the user, while looping, add all the 'priority' messages in an array. Then, check the number of alerts in your array and you can show one alert that reflects this information: e.g. for one message you could display the title of the message and some other information as title and message of the alertView, while, when you have multiple messages, you could have a title stating something like "You have x new messages with high priority" where x is the number of messages and some other description.
-34829930 1 Is there a way to get function parameter names, including bound-methods excluding `self`?I can use inspect.getargspec
to get the parameter names of any function, including bound methods:
>>> import inspect >>> class C(object): ... def f(self, a, b): ... pass ... >>> c = C() >>> inspect.getargspec(c.f) ArgSpec(args=['self', 'a', 'b'], varargs=None, keywords=None, defaults=None) >>>
However, getargspec
includes self
in the argument list.
Is there a universal way to get the parameter list of any function (and preferably, any callable at all), excluding self
if it's a method?
EDIT: Please note, I would like a solution which would on both Python 2 and 3.
-23673818 0Remove ()
near values
INSERT INTO evraklar(evrak_tipi_grubu, evrak_tipi, evrak_konu, evrak_subeye_gelis_tarihi, evrak_gonderen, evrak_alici, evrak_tarihi, evrak_sayisi, evrak_aciklama, evrak_kurum_icindenmi, gelen_evrak_tarihi, gelen_evrak_sayi, gelen_evrak_etakip, evrak_kaydeden_ybs_kullanici_id,kaydeden_kullanici_birim_id) VALUES (6,43,'Test amaçlı girilen konu',STR_TO_DATE('12/12/2012', '%d/%m/%Y'),0,566,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555','YBS:110 nolu evrağa cevaben yazılan yazıdır. Alıcısı:Antalya Valiliği - İl Sağlık Müdürlüğü',0,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555',777777777,1,685), (6,43,'Test amaçlı girilen konu',STR_TO_DATE('12/12/2012', '%d/%m/%Y'),0,612,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555','YBS:110 nolu evrağa cevaben yazılan yazıdır. Alıcısı:Mersin Valiliği - İl Sağlık Müdürlüğü',0,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555',777777777,1,685), (6,43,'Test amaçlı girilen konu',STR_TO_DATE('12/12/2012', '%d/%m/%Y'),0,616,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555','YBS:110 nolu evrağa cevaben yazılan yazıdır. Alıcısı:Niğde Valiliği - İl Sağlık Müdürlüğü',0,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555',777777777,1,685), (6,43,'Test amaçlı girilen konu',STR_TO_DATE('12/12/2012', '%d/%m/%Y'),0,616,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555','YBS:110 nolu evrağa cevaben yazılan yazıdır. Alıcısı:Niğde Valiliği - İl Sağlık Müdürlüğü',0,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555',777777777,1,685), (6,43,'Test amaçlı girilen konu',STR_TO_DATE('12/12/2012', '%d/%m/%Y'),0,616,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555','YBS:110 nolu evrağa cevaben yazılan yazıdır. Alıcısı:Niğde Valiliği - İl Sağlık Müdürlüğü',0,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555',777777777,1,685);
-41067535 0 You can use sum
function:
In [52]: m = np.random.randint(0,9,(4,4)) In [53]: m Out[53]: array([[8, 8, 2, 1], [2, 7, 1, 2], [8, 6, 8, 7], [5, 2, 5, 2]]) In [56]: np.sum(m == 8) Out[56]: 4
m == 8
will return a boolean array contains True for each 8 then since python evaluates the True as 1 you can sum up the array items in order to get the number of intended items.
Thanks Equiso, I didn't find the question you refered to. So this is an exact duplicate of Linq query built in foreach loop always takes parameter value from last iteration.
-14876110 0Considering that all your filters are set to required=false
I'll assume the PRO version is paid and guess an answer here:
There're 2496 - 2263 devices in the world that were only released in countries that does not accept the paid area of the Play Store.
-5073928 0http://developer.android.com/guide/topics/data/data-storage.html#db
-4787264 0I can't speak for all RDBMS systems, but Postgres specifically uses estimated table sizes as part of its efforts to construct query plans. As an example, if a table has two rows, it may choose a sequential table scan for the portion of the JOIN that uses that table, whereas if it has 10000+ rows, it may choose to use an index or hash scan (if either of those are available.) Incidentally, it used to be possible to trigger poor query plans in Postgres by joining VIEWs instead of actual tables, since there were no estimated sizes for VIEWs.
Part of how Postgres constructs its query plans depend on tunable parameters in its configuration file. More information on how Postgres constructs its query plans can be found on the Postgres website.
-19356791 0You want to use an unnamed form. Here is the correct syntax :
# List the forms that are in the page for form in br.forms(): print "Form name:", form.name print form # To go on the mechanize browser object must have a form selected br.select_form(nd = "form1") # works when form has a name br.form = list(br.forms())[0] # use when form is unnamed
Python for beginners has a great cheat sheet about mechanize : http://www.pythonforbeginners.com/cheatsheet/python-mechanize-cheat-sheet/
-33357067 0Based on your case, I think you can try to use shellCommandActivity in data pipeline. It will launch a ec2 instance and execute the command you give to data pipeline on your schedule. After finishing the task, pipeline will terminate ec2 instance.
Here is doc:
http://docs.aws.amazon.com/datapipeline/latest/DeveloperGuide/dp-object-shellcommandactivity.html
http://docs.aws.amazon.com/datapipeline/latest/DeveloperGuide/dp-object-ec2resource.html
-36848540 0You can always use std::enable_if
:
template <typename T, typename ... ARGS> std::enable_if_t<(sizeof...(ARGS)>0)> func(...) { ... }
In this case, func
will only appear as part of the overload set if the size of ARGS...
is greater than 0. However, if the size is zero, you will be missing a function from your overload set. Maybe that's want you want, though.
Since you're using percentages for both top
and margin-top
, you can combine them, and simply use top: 10%
.
See this demo: http://jsfiddle.net/jackwanders/DEn6r/3/
Also, if you'd like to drop the negative left margin, you can use this trick to center the div horizontally:
#inside { position: absolute; width: 300px; height: 80%; top: 10%; left: 0; right: 0; // set left and right to 0 margin: 0 auto; // set left and right margins to auto background: white; }
-5180846 0 This looks like a case of reference versus value comparison. If you have two different instances of objects with the same property values, by default they will never be 'equal' using default comparisons. You have to compare the values of the objects. Try writing code to compare the values of each instance.
-3553540 0The documentation has this line of code:
user_db=${user_www}/${filename}-db.sqlite3
Is the filename
variable defined? Does the database exist in that location?
The convoluted way :
var t = setTimeout((function(that){ return function(){ jQuery(that).find("ul.topnavsub").hide(); console.log(that); } })(this), 1000);
The less-cool-but-still-works-(-and-is-probably-more-readable-) way :
var that = this; var t = setTimeout(function(){ jQuery(that).find("ul.topnavsub").hide(); console.log(that); }, 1000);
-27330540 0 How to use OperaChromiumDriver for opera version >12.X I understand that to work on opera versions > 12.X, Operachromiumdriver has been developed. At the same time I couldn't get this to work. I downloaded the windows version of operachromiumdriver.exe from https://github.com/operasoftware/operachromiumdriver/releases but to no avail. Can someone help me with this . Please tell me if my understanding is right.
Thanks
-20222305 0There is a particular line-height property for h3
tag with bootstrap.
h1, h2, h3 { line-height: 40px;//line 760 }
So you will have to add style to negotiate this additional height.
Also another set for your ul as :
ul, ol { margin: 0 0 10px 25px; //line 812 }
Solution :
Over-ride the ul margin as follows :
.pull-right ul{ margin: 0; }
Over-ride the line-height for the h3 as follows :
.pull-left h3{ line-height:20px; }
First one is pretty straight forward and gives you correct alignment straighaway. Second solution will need you to work some more with tweaking the negative-margins for .pull-right
.
Debugging URL : http://jsbin.com/oToRixUp/1/edit?html,css,output
Hope this helps.
-31494182 0Scanner
has a nextFloat()
for getting float
s fashion to nextInt()
. Just call it in its own loop:
System.out.print("Enter " + c.length + " float values: "); for(int index1 = 0; index1 < c.length; index1++) { c[index1] = input.nextFloat(); }
Unfortunately, there is no nextChar()
method, so you'd have to emulate it with next(String)
's variant that accepts a pattern:
System.out.print("Enter " + b.length + " char values: "); for(int index1 = 0; index1 < b.length; index1++) { b[index1] = input.next(".").charAt(0); }
-19070557 0 Try (35 >= strlen($line)
rather than (35 <= strlen($line)
if you want lines 35 chars or less. Personally, I prefer to order comparisons like that the other way around, e.g. strlen($line) <= 35
, which I think is more readable and avoids mistakes like the one you just made :)
First of all your UI will hang on button 2 click because it's stuck on the while(true) loop so use BeginAcceptSocket(IAsyncResult r, Object state) for async.
Second you must use the loopback address or otherwise the firewall should block the port 10 assuming that it's not open. Also the TcpListener(int port) is obsolote and its better to use the TcpListener(IPAddress localddr, int port) and use both the loopback address.
-26381810 0 Calculate 1 line value using 2 or more other linesI have the following query.
How this works my client sells kits. Each kit can contains 3 to 5 lines.
LINTYP = 6 - Kit Item LINTYP = 7 - Components
The sequence should always be 6-7-7 where 6 represents the start of an new kit. There will always be 1 line that would contain an gross price. In the sample below there is 2 kits each containing 2 lines with an line status of 7
So what needs to happen is I need to calculate the missing GROSPRI using LINTYP 6 and deducting all my LINTYP 7 lines
eq.
Grosprice on line 1 (Product 550412) = R1 795 Grosprice on line 3 (Product 501301) = R 185 Grosprice on line 2 (Product 650412) should be R 1795-185 = R1 610 ---------------------------------------------------------------- | Invoice No| Product| Line No| Line Type| Gross Price ---------------------------------------------------------------- |SI141000008| 550412| 1000| 6| 1795.00 ---------------------------------------------------------------- |SI141000008| 650412| 2000| 7| 0.00 | This needs to be R1610 ---------------------------------------------------------------- |SI141000008| 501301| 3000| 7| 185.00 --------------------------------------------------------------- |SI141000008| 550413| 4000| 6| 1855.00 -------------------------------------------------------------- |SI141000008| 650413| 5000| 7| 0.00 | This needs to be R1670 --------------------------------------------------------------- |SI141000008| 501301| 6000| 7| 185.00 ----------------------------------------------------------------
-33820507 0 Could not open ServletContext resource [/WEB-INF/mvc-dispatcher-servlet.xml] I am having this error when I run my code. Any help will be appreciated. Thanks.
Here is my dispatcher servlet.
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="tutorial.mvc"/> <mvc:annotation-driven/> <bean id="HandlerMapping" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/> <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
Here is my web.xml
<servlet> <servlet-name>mvc-dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>mvc-dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
Here is the error that I end up getting.
Nov 20, 2015 1:39:45 AM org.apache.catalina.core.ApplicationContext log SEVERE: StandardWrapper.Throwable org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from ServletContext resource [/WEB-INF/mvc-dispatcher-servlet.xml]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/mvc-dispatcher-servlet.xml] at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:343) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:303) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:216) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:187) at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125) at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94) at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:129) at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:540) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:454) at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:658) at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:624) at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:672) at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:543) at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:484) at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136) at javax.servlet.GenericServlet.init(GenericServlet.java:158) at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1197) at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:864) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:134) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611) at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2462) at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2451) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:745) Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/mvc-dispatcher-servlet.xml] at org.springframework.web.context.support.ServletContextResource.getInputStream(ServletContextResource.java:141) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:329) ... 35 more
-3410674 0 The builtin method you are looking for is Array#transpose
-21259556 0I believe I've come up with an alternate solution to this problem. There are certain circumstances with the other solution proposed where the label colours appear incorrect (using the system default instead of the overridden colour). This happens while scrolling the list of items.
In order to prevent this from happening, we can make use of method swizzling to fix the label colours at their source (rather than patching them after they're already created).
The UIWebSelectSinglePicker
is shown (as you've stated) which implements the UIPickerViewDelegate protocol. This protocol takes care of providing the NSAttributedString instances which are shown in the picker view via the - (NSAttributedString *)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component
method. By swizzling the implementation with our own, we can override what the labels look like.
To do this, I defined a category on UIPickerView:
@implementation UIPickerView (LabelColourOverride) - (NSAttributedString *)overridePickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component { // Get the original title NSMutableAttributedString* title = (NSMutableAttributedString*)[self overridePickerView:pickerView attributedTitleForRow:row forComponent:component]; // Modify any attributes you like. The following changes the text colour. [title setAttributes:@{NSForegroundColorAttributeName : [UIColor redColor]} range:NSMakeRange(0, title.length)]; // You can also conveniently change the background of the picker as well. // Multiple calls to set backgroundColor doesn't seem to slow the use of // the picker, but you could just as easily do a check before setting the // colour to see if it's needed. pickerView.backgroundColor = [UIColor yellowColor]; return title; } @end
Then using method swizzling (see this answer for reference) we swap the implementations:
[Swizzle swizzleClass:NSClassFromString(@"UIWebSelectSinglePicker") method:@selector(pickerView:attributedTitleForRow:forComponent:) forClass:[UIPickerView class] method:@selector(overridePickerView:attributedTitleForRow:forComponent:)];
This is the Swizzle implementation I developed based off the link above.
@implementation Swizzle + (void)swizzleClass:(Class)originalClass method:(SEL)originalSelector forClass:(Class)overrideClass method:(SEL)overrideSelector { Method originalMethod = class_getInstanceMethod(originalClass, originalSelector); Method overrideMethod = class_getInstanceMethod(overrideClass, overrideSelector); if (class_addMethod(originalClass, originalSelector, method_getImplementation(overrideMethod), method_getTypeEncoding(overrideMethod))) { class_replaceMethod(originalClass, overrideSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod)); } else { method_exchangeImplementations(originalMethod, overrideMethod); } } @end
The result of this is that when a label is requested, our override function is called, which calls the original function, which conveniently happens to return us a mutable NSAttributedString that we can modify in anyway we want. We could completely replace the return value if we wanted to and just keep the text. Find the list of attributes you can change here.
This solution allows you to globally change all the Picker views in the app with a single call removing the need to register notifications for every view controller where this code is needed (or defining a base class to do the same).
-35777586 0One solution is to use a Lookup
expression, with the minimum price as the value to match. This expression should give each vendor if there is a tie for the cheapest:
=Join(LookupSet(Min(Fields!PRICE.Value), Fields!PRICE.Value, Fields!VENDOR.Value, "pv"), " / ")
There may be a more elegant solution out there, but is the first one I found.
-26670693 0<input type="name[]" value="1"> //row1 <input type="name[]" value="2"> //row2 <input type="name[]" value="3"> // row3
this is wrong i think you are looking for this
<input type="text" name="name[]" value="1"> //row1 <input type="text" name="name[]" value="2"> //row2 <input type="text" name="name[]" value="3"> // row3
-29094706 0 jQuery - If first element has class then Function I'm looking to add a piece of code sitewide to affect all of my pages.
Right now, it goes something like this.
if($('#container > div:first').attr('id') == 'filterOptions') { $('#container').prepend('<div class="banner"></div>'); }
The output:
<div id="container"> <div class="banner"></div> <div id="filterOptions"><div> </div>
Example, if the container looked like this:
<div id="container"> <div class="existingBanner"></div> <div id="filterOptions"><div> </div>
Nothing would happen as the first div doesn't have the filterOptions ID.
Now I've hit a bump as I also have something that looks like this that the banner DOES get added to
<div id="container"> <a class="existingBanner" href="#"></a> <div id="filterOptions"><div> </div>
This will essentially have a double banner which is something I want to avoid. because it's an anchor instead of a div.
So my question is. instead of targeting div:first how would I target ALL elements?
Something like...
if($('#container >
any:first').attr('id') == 'filterOptions') { ... }
How to iterate array in json:
$(document).ready(function(){ $('#wardno').change(function(){ //any select change on the dropdown with id country trigger this code $("#wardname > option").remove(); //first of all clear select items var ward_id = $('#wardno').val(); $.ajax({ type: "POST", cache: false, url:"get_wardname/"+ward_id, //here we are calling our user controller and get_cities method with the country_id success: function(cities) { try { $.each(cities,function(id,city) { var opt = $('<option />'); // here we're creating a new select option with for each city opt.val(id[0]); opt.text(id[1]); $('#wardname').append(opt); var opt1 = $('<option />'); // here we're creating a new select option with for each city opt1.val(city[0]); opt1.text(city[1]); $('#koottaymaname').append(opt1); }); //here we will append these new select options to a dropdown with the id 'cities' } catch(e) { alert(e); } }, error: function (jqXHR, textStatus, errorThrown) { alert("jqXHR: " + jqXHR.status + "\ntextStatus: " + textStatus + "\nerrorThrown: " + errorThrown); } }); }); });
The output from the code is:
[{"1":"St. Sebastian"},{"1":"kudumbakoottayma1","2":"kudumbakoottayma2"}]
How to iterate into two different drop down list?
-459747 0There is still a good reason for a template system to use, however not Smarty, but PHPTAL. PHPTAL templates are valid XML (and hence XHTML) files. You can farther use dummy content in PHPTAL and so get valid XHTML file with the final appearance, that can be processed and tested with standard tools. Here is a small example:
<table> <thead> <tr> <th>First Name</th> <th>Last Name</th> <th>Age</th> </tr> </thead> <tbody> <tr tal:repeat="users user"> <td tal:content="user/first_name">Max</td> <td tal:content="user/last_name">Mustermann</td> <td tal:content="user/age">29</td> </tr> </tbody> </table>
PHPTAL template engine will automatically insert all values from users array and replace our dummy values. Nevertheless, the table is already valid XHTML that can be displayed in a browser of your choice.
-25610893 0If you want to avoid using valid values of float
, you could use a NAN:
#include <limits> .... float min = std::numeric_limits<float>::quiet_NaN();
You can then use std::isnan
to check:
#include <cmath> .... bool not_cool = std::isnan(min);
-9297352 0 You receive null at the end of the stream. The client correctly starts, sends Ready, and the the ends, so the stream ends.
Totally correct behaviour. If the client would end itself (but instead do something else like reading server messages on stdin), the server would never receive a null.
Edit: NEVER EVER (!!!!!) do this:
catch(IOException e){}
At least write:
catch(IOException e){ e.printStackTrace() }
This will show you your error!
In my company, this is one of the elementary rules of code style!
-10412684 0 compiling your own glibcI am trying to compile my own glibc. I have a directory glibc
, which contain the glibc
source code I downloaded from the internet. From that directory I typed mkdir ../build-glibc
. Now from the build-glibc
directory I typed ../glibc/configure
, which performed the configuration. Now I'm not sure how to call make
. I can't call it from glibc
directory since it doesn't have the configuration set, neither I can call it from build-glibc
, since makefile is not in that directory. How do I solve this problem?
var stuff= ["uyuuyu", "76gyuhj***", "uiyghj", "56tyg", "juijjujh***"]; for(var i = 0; i < stuff.length; i++) { if(stuff[i].indexOf('***') != -1) { stuff[i] = stuff[i].replace('***','0') // this is where i guess the replacing would go } console.log(stuff[i]); }
-4920668 0 Yes there's a standard method for creating these symbols known as name mangling.
-11372530 0I can't think of a good way to do this with qsub as there are no programmatic interfaces into the -o and -e options. There is, however, a way to accomplish what you want.
Run your qsub with -o and -e pointing to /dev/null. Make the command you run be some type of wrapper that redirects it's own stdout and stderr to files in whatever fashion you want (i.e., your broken down directory structure) before it execs the real job.
-32902868 0 Swift set variable to another ViewControllerI have two tabs. And i want to set data from one tab to another. For example i have a code that switch to another tab:
func foundCode(code: String) { print("Code has been found: \(code)") // MySecondViewController.codeSetter(code); self.tabBarController?.selectedIndex = 1; }
What is the best way to set it? Or maybe delegate this variable... But how ?
-10575459 0For what you want this is not the best way of doing it. However what you're talking about requires knowledge of one of the fundamental tennets of PHP and programming in general aka scope, namely what the global scope is.
So, if you declare this in the global scope:
$uom = new UOM_Class();
Then in any file afterwards you write:
global $uom; $uom->something();
it will work.
This is all wasteful however, instead you would be better with static methods, and something more like a singleton pattern e.g.:
UOM::Something();
I leave it as a task for you to learn what a singleton is, and what scope is, these are fundamental tennets of PHP, and you should not claim to know PHP without knowing about scope. The best way of putting it is when in everyday conversation, it is called context, the global scope is tantamount to shouting in everyones ear at the same time. Everyone can access it, and its not something you want to pollute
I'm sorry if I seem a bit harsh, here's some articles that should help, they talk about scope, singletons and some other methods of doing it, like object factories
http://php.net/manual/en/language.variables.scope.php http://www.homeandlearn.co.uk/php/php8p2.html
http://php.net/manual/en/language.oop5.patterns.php
-39795421 0 Show in view only object with specified idi am woking on a project about a restaurant and i need to show on my staff view only the Chef and Su-Chef which has id (Chef-2, Su-Chef 4). I need to show on my view all the Chefs and all the Su-Chefs. The view is organised at the form that is the number is odd (i have the image on left and text on right), if the number is even i have (i have the image on right and text on left) Here is my Controller
public function index() { $staff = Staff::where('visible','yes')->where('delete','no')->orderBy('name','DESC')->get(); return view('staff.staff', ['staff' => $staff]); }
And this is my View
<section class="bg-deep-yellow"> <div class="container"> <div class="row"> <!-- section title --> <div class="col-md-12 text-center"> <span class="title-small black-text text-uppercase letter-spacing-3 font-weight-600">I NOSTRI CHEF</span> <div class="separator-line-thick bg-black no-margin-bottom margin-one xs-margin-top-five"></div> </div> <!-- end section title --> </div> <div class="row margin-ten no-margin-bottom"> <!-- chef --> <div class="col-md-12 sm-margin-bottom-ten"> <div class="col-md-5 chef-img cover-background" style="background-image:url({{URL::asset('external_assets/assets/images/images_downloaded/chef.jpg') }});"> <div class="img-border"></div> </div> <div class="col-md-7 chef-text bg-white text-center"> <img src="{{URL::asset('external_assets/assets/images/images_downloaded/kapele.png') }}" alt=""/><br> <span class="text-large black-text text-uppercase letter-spacing-3 font-weight-600 margin-ten display-block no-margin-bottom">Patrick Smith</span> <span class="text-small text-uppercase letter-spacing-3">Chef, Co-Founder</span> <p class="text-med margin-ten width-90 center-col" style="text-align: justify">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s</p> </div> </div> <!-- end chef --> <!-- chef --> <div class="col-md-12"> <div class="col-md-7 chef-text bg-white text-center"> <img src="{{URL::asset('external_assets/assets/images/images_downloaded/bari.png') }}" alt=""/><br> <span class="text-large black-text text-uppercase letter-spacing-3 font-weight-600 margin-ten display-block no-margin-bottom">Sancho Pansa</span> <span class="text-small text-uppercase letter-spacing-3">Bartender</span> <p class="text-med margin-ten width-90 center-col" style="text-align: justify" >Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p> </div> <div class="col-md-5 chef-img cover-background" style="background-image:url({{URL::asset('external_assets/assets/images/images_downloaded/chef2.jpg') }});"> <div class="img-border"></div> </div> </div> <!-- end chef --> </div> </div> </section>
-2480835 0 NHibernate paging for Telerik Extensions for ASP.NET MVC How can I integrate Telerik Grid paging for ASP.NET MVC (http://demos.telerik.com/aspnet-mvc/Grid) with my NHibernate data access with minimal coding?
-39010768 0You cantry it this way, it should work:
$.ajax({ type: "GET", url: "/grafana/dashboard", contentType: "application/json", beforeSend: function(xhr, settings){ xhr.setRequestHeader("some_custom_header", "foo");}, success: function(data){ $("#output_iframe_id").attr('src',"data:text/html;charset=utf-8," + escape(data)) } });
-33492944 0 Yes, you can do it in single query. Combine those condition in one query then sort YMonth DESC and limit by ROWNUM
SELECT COUNT(*) FROM ( SELECT XXX,YMONTH FROM MyTable WHERE XXX AND YMONTH IN( TO_CHAR(add_months(SYSDATE,0),'YYYYMM'), TO_CHAR(add_months(SYSDATE,-1),'YYYYMM'), TO_CHAR(add_months(SYSDATE,-2),'YYYYMM'), TO_CHAR(add_months(SYSDATE,-3),'YYYYMM'), TO_CHAR(add_months(SYSDATE,-4),'YYYYMM') ) ORDER BY YMONTH DESC ) WHERE ROWNUM <= 3
Please try the query above, and let see if it works.
-40562875 0You need to specify the inheritance with extends the base class http://php.net/manual/en/keyword.extends.php
Try this for your child class
//Child View Class class ChildView extends View{ public function html(){ //I get a fatal error here: calling img_cache on a non-object. //But it should have inherited this from the parent class surely? return '<img src="'.$this->img_cache->thumb($this->data['img-src']).'"/>'; } }
Also as @ferdynator says, you are instantiating the parent, not the child, so your Main
class also needs to be changed to instantiate ChildView
, not the parent View
//Main class: class Main{ //construct public function Main(){ //get data from model $data = $model->getData(); //Get the view $view = new ChildView(); //Init view $view->init( $data ); //Get html $view->getHTML(); } }
-18099453 0 Why the data retrieved isn't shown I would to retrieve the data from http://api.eventful.com/rest/events/search?app_key=42t54cX7RbrDFczc&location=singapore . The tag under "title", "start_time", "longitude", "latitude". But I not sure why it couldn't be display out after I added the longitude and latitude.
This is from logcat:
08-07 17:17:44.190: E/AndroidRuntime(23734): FATAL EXCEPTION: main 08-07 17:17:44.190: E/AndroidRuntime(23734): java.lang.NullPointerException 08-07 17:17:44.190: E/AndroidRuntime(23734): at com.example.eventfulmaptry.MainActivity$ItemAdapter.getView(MainActivity.java:147) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.widget.AbsListView.obtainView(AbsListView.java:1618) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.widget.ListView.measureHeightOfChildren(ListView.java:1241) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.widget.ListView.onMeasure(ListView.java:1152) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.view.View.measure(View.java:8513) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3143) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1017) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.widget.LinearLayout.measureVertical(LinearLayout.java:386) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.widget.LinearLayout.onMeasure(LinearLayout.java:309) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.view.View.measure(View.java:8513) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3143) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.widget.FrameLayout.onMeasure(FrameLayout.java:250) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.view.View.measure(View.java:8513) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.widget.LinearLayout.measureVertical(LinearLayout.java:531) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.widget.LinearLayout.onMeasure(LinearLayout.java:309) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.view.View.measure(View.java:8513) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3143) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.widget.FrameLayout.onMeasure(FrameLayout.java:250) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.view.View.measure(View.java:8513) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.view.ViewRoot.performTraversals(ViewRoot.java:857) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.view.ViewRoot.handleMessage(ViewRoot.java:1878) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.os.Handler.dispatchMessage(Handler.java:99) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.os.Looper.loop(Looper.java:130) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.app.ActivityThread.main(ActivityThread.java:3691) 08-07 17:17:44.190: E/AndroidRuntime(23734): at java.lang.reflect.Method.invokeNative(Native Method) 08-07 17:17:44.190: E/AndroidRuntime(23734): at java.lang.reflect.Method.invoke(Method.java:507) 08-07 17:17:44.190: E/AndroidRuntime(23734): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:912) 08-07 17:17:44.190: E/AndroidRuntime(23734): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:670) 08-07 17:17:44.190: E/AndroidRuntime(23734): at dalvik.system.NativeStart.main(Native Method)
This is my code :
public class MainActivity extends Activity { ArrayList<String> title; ArrayList<String> start_time; ArrayList<String> latitude; ArrayList<String> longitude; ItemAdapter adapter1; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ListView list = (ListView) findViewById(R.id.list); title = new ArrayList<String>(); latitude = new ArrayList<String>(); longitude = new ArrayList<String>(); try { URL url = new URL( "http://api.eventful.com/rest/events/search?app_key=42t54cX7RbrDFczc&location=singapore"); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(new InputSource(url.openStream())); doc.getDocumentElement().normalize(); NodeList nodeList = doc.getElementsByTagName("event"); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); Element fstElmnt = (Element) node; NodeList nameList = fstElmnt.getElementsByTagName("title"); Element nameElement = (Element) nameList.item(0); nameList = nameElement.getChildNodes(); title.add(""+ ((Node) nameList.item(0)).getNodeValue()); NodeList websiteList = fstElmnt.getElementsByTagName("start_time"); Element websiteElement = (Element) websiteList.item(0); websiteList = websiteElement.getChildNodes(); start_time.add(""+ ((Node) websiteList.item(0)).getNodeValue()); NodeList websiteList1 = fstElmnt.getElementsByTagName("latitude"); Element websiteElement1 = (Element) websiteList1.item(0); websiteList1 = websiteElement1.getChildNodes(); latitude.add(""+ ((Node) websiteList1.item(0)).getNodeValue()); NodeList websiteList2 = fstElmnt.getElementsByTagName("longitude"); Element websiteElement2 = (Element) websiteList2.item(0); websiteList2 = websiteElement2.getChildNodes(); longitude.add(""+ ((Node) websiteList2.item(0)).getNodeValue()); } } catch (Exception e) { System.out.println("XML Pasing Excpetion = " + e); } adapter1 = new ItemAdapter(this); list.setAdapter(adapter1); } class ItemAdapter extends BaseAdapter { final LayoutInflater mInflater; private class ViewHolder { public TextView title_text; public TextView des_text; public TextView lat_text; public TextView long_text; } public ItemAdapter(Context context) { // TODO Auto-generated constructor stub super(); mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } //@Override public int getCount() { return title.size(); } //@Override public Object getItem(int position) { return position; } //@Override public long getItemId(int position) { return position; } //@Override public View getView(final int position, View convertView, ViewGroup parent) { View view = convertView; final ViewHolder holder; if (convertView == null) { view = mInflater.inflate(R.layout.mainpage_list,parent, false); holder = new ViewHolder(); holder.title_text = (TextView) view.findViewById(R.id.title_text); holder.des_text = (TextView) view.findViewById(R.id.des_text); holder.lat_text = (TextView) view.findViewById(R.id.lat_text); holder.long_text = (TextView) view.findViewById(R.id.long_text); view.setTag(holder); } else { holder = (ViewHolder) view.getTag(); } holder.title_text.setText(""+title.get(position)); holder.des_text.setText(""+Html.fromHtml(start_time.get(position))); holder.lat_text.setText(""+Html.fromHtml(latitude.get(position))); holder.long_text.setText(""+Html.fromHtml(longitude.get(position))); return view; } } }
-15404711 0 in the javascript function. Then it will not postback.
$j(".colorBoxLink").click((function () { $j("div#popup").show(); var editor = new wysihtml5.Editor("wysihtml5_textarea", { // id of textarea element toolbar: "wysihtml5-toolbar", // id of toolbar element parserRules: wysihtml5ParserRules, // defined in parser rules set stylesheets: ["Styles/wysihtml5.css", "Styles/wysihtml5.css"] }); $j.colorbox({ inline: true, href: "#popup", modal: true, scrolling: false, onCleanup: function () { $j("div#popup").hide(); } }); return false; }));
-11773518 0 Could it be because you want to measure the font before it's been fully loaded ?
In my example it seems to be working fine : Font example
-10176059 0The images you are using might be too large for an animation. How large are they? In an animation, Android loads all of the images into memory and uncompresses them meaning that every pixel will take 4 bytes. So 50k would mean that your image is 111px x 111px. It seems from the error each frame is about 480 x 640, which is really large. Try using smaller images.
-28839887 0 number bytes read from gpio input is zeroI have some strange behaviour when trying to read gpio output pin. I get that the first read return 1 (1 bytes read), but all next read from same gpio return 0. I would assume that it should always read 1, because there is always something to read from input pin.
gpio = 8; fd = open("/sys/class/gpio/export", O_WRONLY); sprintf(buf, "%d", gpio); rc = write(fd, buf, strlen(buf)); if (rc == -1) printf("failed in write 17\n"); close(fd); sprintf(buf, "/sys/class/gpio/gpio%d/direction", gpio); fd = open(buf, O_WRONLY); rc = write(fd, "in", 2); if (rc == -1) printf("failed in write 18\n"); close(fd); sprintf(buf, "/sys/class/gpio/gpio%d/value", gpio); gpio_tdo = open(buf, O_RDWR); rc = read(gpio_tdo, &value, 1); <-- rc here is 1 rc = read(gpio_tdo, &value, 1); <-- rc here is 0 rc = read(gpio_tdo, &value, 1); <-- rc here is 0
Should the read of one byte from the gpio input always return 1 ?
-29310107 0You want to use Mysql Join to join the two tables together which reference the user id.
Account Table
CREATE TABLE `account` ( `id` INT UNSIGNED AUTO_INCREMENT, `username` VARCHAR(10) NOT NULL, PRIMARY KEY(`id`) );
Suspension Table
CREATE TABLE `suspension` ( `user_id` INT UNSIGNED DEFAULT NULL, FOREIGN KEY (`user_id`) REFERENCES account(`id`) ON DELETE CASCADE ON UPDATE CASCADE );
Query
SELECT A.username, A.id FROM `account` AS A LEFT JOIN `suspension` AS S ON S.user_id = A.id WHERE A.id = 5 AND S.user_id IS NULL;
If the user appears in Suspension, no results are returned. If the user isn't suspended then the user result is returned. To return the user and their suspension status, you can use the below query.
SELECT A.username, A.id, (S.user_id IS NOT NULL) AS `suspended` FROM `account` AS A LEFT JOIN `suspension` AS S ON S.user_id = A.id WHERE A.id = 5;
-35814790 0 stack.top()
is illegal if the stack
is empty.while((!highPrecedence(stack.top(),c)) && (stack.size()!=0)){
while((!stack.empty()) && (!highPrecedence(stack.top(),c))){
i
is not good and you are printing uninitialized variable, which has indeterminate value.int i=0;
to int i=-1;
Which C++ function changes text or background color (MS Visual studio)? For example cout<<"This text";
how to make "This text" red color.
import acm.program.*; public class Practice3 extends ConsoleProgram { public static int powersOf2(int k) { int x = 0; while (k < 1000) { x = k; k *= 2; } return x; } public void run() { println(powersOf2(1)); println(powersOf2(0)); println(powersOf2(2)); println(powersOf2(-1)); println(powersOf2(3000)); }
I don't think I really get right values from powersOf2
. Only 512 is displayed when I run program. And if I run it by each println
, it gives me:
512 none 512 none 0
Is there something wrong? or values are correct?
-18961158 0 Formatting data based on string or number - google visualizationI have database in PHPMyAdmin, Excel and CSV format (all the same just different formats). To put this data in a table in google visualization numbers are written as they are but string values need to have a ' either side of the text. For example:
['MESSI','FC BARCELONA','ARGENTINA',169,67,25,'Left foot','SS',98,99,38,74,9855704866],
My database has over 2000 rows so manually doing this isn't an option. Is there a way in any of these formats to make all string variables have the ' either side and all numbers to be written by themselves. The CSV format already splits cells using a comma which I need but it would also be useful if each row started with [ and ended with ] . Anyone know how to do this using any of these formats?
-3193062 0You can make C++ callable from C by using the extern "C"
construct.
You are forgetting an AND in this line.
SELECT * FROM users WHERE id ='" . $_SESSION['UserRow'] . "' AND note='$noteSequence'", $connection
-17293590 0 How efficient is .clone()? I have a page with a canvas area (nothing to do wth HTML5) where people can create "art" by dragging in photos, creating divs that they can drag, stretch, color, etc. etc. etc. The canvas div is inside a canvasContainer div. Now I'd like to implement an UNDO option. My thought was to do a
canvasBackup$ = $('#canvas').clone();
when an operation began, say at every dragStart event, and at the end of the operation an UNDO, if asked for with Ctrl-Z, would execute
$('#canvas').remove(); canvasBackup$.appendTo($('#canvasContainer');
My concern is that the clone, and perhaps the append, might be a bit compute intensive as the page grows and start slowing down the page's responsiveness. I suppose it depends on how jQuery does the clone. If it just breaks off the section from the DOM and does a straight memory copy, it shouldn't be bad. But if there's a lot of calculation and building going on it could be a problem.
Does anyone have a feel for whether this is a reasonable approach to implementing UNDO?
Thanks
-4024056 0 Threads vs. AsyncI have been reading up on the threaded model of programming versus the asynchronous model from this really good article. http://krondo.com/blog/?p=1209
However, the article mentions the following points.
I remember reading that threads are managed by the operating system by moving around TCBs between the Ready-Queue and the Waiting-Queue(amongst other queues). In this case, threads don't waste time on waiting either do they?
In light of the above mentioned, what are the advantages of async programs over threaded programs?
-32481778 0Quick answer:
First af all you are starting from x=0 and then increasing it which is not the best solution since you are looking for the maximum value and not the first one. So for that I would go from an upperbound that can be
x=abs((b)^(1/4))
than decrease from that value, and as soon you find an element <=b you are done.
You can even think in this way:
for y=b to 1 solve(x^4+x^3+x^2+x+1=y) if has an integer solution then return solution
See this
This is a super quick answer I hope I didn't write too many stupid things, and sorry I don't know yet how to write math here.
-5167035 0 Excutereader is very slow when taking data by oledbcommand objectI am fetching data from dBase4 database by using object of oledbcommand and load it into datatable. but it is taking too much time to fetch 160 records around 5-10 minutes. Please Help me Out.
Code:
using (OleDbConnection cn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;" + @"Data Source=" + TrendFilePath + "\\" + Pathname + ";" + @"Extended Properties=dBASE III;")) using (OleDbCommand cm = cn.CreateCommand()) { cn.Open(); for (int L = 0; L <= months; L++) { DataTable dt_Dbf = new DataTable(); From_Date = DateTime.ParseExact(frmdate, dateFormat2, provider); From_Date = From_Date.AddMonths(L); int month = From_Date.Month; string year = "1" + From_Date.Year.ToString().Substring(2, 2); if (L == 0) { cm.CommandText = @"SELECT * FROM 128.DBF where DATE_Y =" + year + " and DATE_M = " + month + " and DATE_D>=" + From_Day + ""; dt_Dbf.Load(cm.ExecuteReader(CommandBehavior.CloseConnection)); } } }
-20116797 0 Scala has implemented also the async/await paradigm, which can simplify some algorithms.
Here is the proposal: http://docs.scala-lang.org/sips/pending/async.html
Here is the implementation: https://github.com/scala/async
-23311182 0 Convert JSON String to Object - jqueryI have a JSON String like this.
{"label":"label","label1":"67041","label2":"745","label3":"45191","label4":"11464"}
I wanted to convert it to object like this
[{"label":"label","label1":"67041","label2":"745","label3":"45191","label4":"11464"}]
I did figure that out like this.
'[' + {"label":"label","label1":"67041","label2":"745","label3":"45191","label4":"11464"} + ']'
And using $.parseJSON()
to make it a JSON.
But instead of concatenating. Is there any elegant way to do it?
If so please do share me.
Thanks in advance.
-25766028 0What you want to do is not called "instantiation." You can instantiate a universally quantified hypothesis and you can instantiate an existentially quantified conclusion, but not vice versa. I'm thinking the proper name is "introduction". You can introduce existential quantification in a hypothesis and you can introduce universal quantification in the conclusion. If it seems like you're "eliminating" instead, that's because, when proving something, you start at the bottom of a sequent calculus deriviation, and work your way backwards to the top.
Anyway, use the tactic firstorder
. Also, use the command Set Firstorder Depth 0
to turn off proof search if you only want to simplify your goal.
If your goal has higher order elements though, you'll probably get an error message. In that case, you can use something like simplify
.
Ltac simplify := repeat match goal with | h1 : False |- _ => destruct h1 | |- True => constructor | h1 : True |- _ => clear h1 | |- ~ _ => intro | h1 : ~ ?p1, h2 : ?p1 |- _ => destruct (h1 h2) | h1 : _ \/ _ |- _ => destruct h1 | |- _ /\ _ => constructor | h1 : _ /\ _ |- _ => destruct h1 | h1 : exists _, _ |- _ => destruct h1 | |- forall _, _ => intro | _ : ?x1 = ?x2 |- _ => subst x2 || subst x1 end.
-9885459 0 In my case (label on a panel) I set label.AutoSize = false
and label.Dock = Fill
. And the label text is wrapped automatically.
You should set your categories in beforeFilter() of appController for that because navigation will be included in every page .
function beforeFilter() { parent::beforeFilter(); ///set your categories here $this->set('Categories',$Categories); }
-21777508 0 I am not sure you are asking for this.
If the path of the folders are same you can use -or
with find
find $CATALINA_HOME/webapps/myapp/WEB-INF/lib/ -name "*.jar" -or -type d
-type d
will also find directories
Im trying to use SendInput to simulate keyboard presses in my app and want to support both 32-bit and 64-bit.
I've determined that for this to work, I need to have 2 different INPUT structs as such
[StructLayout(LayoutKind.Sequential)] public struct KEYBDINPUT { public ushort wVk; // Virtual Key Code public ushort wScan; // Scan Code public uint dwFlags; public uint time; public IntPtr dwExtraInfo; } [StructLayout(LayoutKind.Explicit, Size = 28)] public struct INPUT32 { [FieldOffset(0)] public uint type; // eg. INPUT_KEYBOARD [FieldOffset(4)] public KEYBDINPUT ki; } [StructLayout(LayoutKind.Explicit, Size = 40)] public struct INPUT64 { [FieldOffset(0)] public uint type; // eg. INPUT_KEYBOARD [FieldOffset(8)] public KEYBDINPUT ki; }
I wanted to know if there was a way to set the StructLayout
size and FieldOffsets
at runtime so I could use just one INPUT
struct and determine the size and fieldoffset depending on the machine.
I have tried the code below but I would like to know if the same is possible at runtime instead of compile time.
#if _M_IX86 [StructLayout(LayoutKind.Explicit, Size = 28)] #else [StructLayout(LayoutKind.Explicit, Size = 40)] #endif public struct INPUT { [FieldOffset(0)] public uint type; // eg. INPUT_KEYBOARD #if _M_IX86 [FieldOffset(4)] #else [FieldOffset(8)] #endif public KEYBDINPUT ki; }
-27625701 0 You did not even use a search engine to look for the error message.
In google, the first result is the MDB2 FAQ page which explains the error and the reason for it.
-1673178 0 cvs2svn changes binary filesI'm using cvs2svn to migrate from CVS to SVN.
I've noticed a problem with my binary file after the conversion was completed.
I'm using auto-props file, which is very helpful.
After the conversion I took the file from CVS and compared it to the same file from SVN. The file is binary. Using WinMerge, I see that there is a difference between the files.
What can be the problem?
-28022612 0This might hepls you
declare @t table(a date,b time) insert into @t values (getdate(),'7:00:00 AM') select * from @t where a>'2015/01/19' or (a=getdate() and a>'6:00:00 AM')
-314693 0 select * from canonical_list_of_tags where tag not in (select tag from used_tags)
At least that works in T-SQL for SQL Server ...
Edit: Assuming that the table canonical_list_of_tags
is populated with the result of "Given a collection of user specified tags"
I placed files in my root folder and copy when user try to download the files like
/root/filelocation/file.mp3
when user on download page
copy("/root/filelocation/file.mp3","download/file.mp3");
i use this command but it takes too much load time
i have ffmpeg installed in server also
-18265414 0 PHP login with PDO, doesnt seem to workThere aren't any errors given, but for some reason the code doesnt seem to work..
Here is the code:
<?php session_start(); require_once('inc/db.php'); if(isset($_SESSION['username'])) { header("location: index.php"); } else { try { $username = mysql_real_escape_string($_POST['username']); $password = mysql_real_escape_string($_POST['password']); $SQL = $dbh->prepare('SELECT * FROM users WHERE username =:username AND password =:password'); $SQL->bindParam(':username', $username); $SQL->bindParam(':password', $password); $SQL->execute(); $total = $SQL->rowCount(); $row = $SQL->fetch(); if($total > 0) { if($row['verified'] > 0) { $_SESSION['username'] = $username; } else { echo "Unverified"; } } else { echo "Incorrect"; } } catch(PDOException $e) { } } ?>
Can anyone help me see what's wrong? Thank you a lot in advance :)
EDIT::::
Here is my db.php
<?php try { $DB_NAME = 'users'; $DB_USER = 'root'; $DB_PASS = ''; $dbh = new PDO('mysql:host=localhost;dbname='.$DB_NAME, $DB_USER, $DB_PASS, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")); $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e) { echo "Error?"; } ?>
-37164244 0 Do we need a second thread to process time-consuming jobs with inotify? Referenc: How to monitor a folder with all subfolders and files inside?
I need to monitor a directory for any file with extension of *.log. If a new file is created or is moved in, I will process the file. it takes variable time to process each file.
Question> Do I need to create one thread to listen the inotify event and push the new file name into queue and use another thread to process the queue? My concern is that if I don't use separate threads, then the inotify may fail to track changes caused by some large files.
I have simulated the problem with sleep
while processing each log file without any multi-thread code. It seems to me that inotify always corrects get all created/moved files in the directory.
Here is my simulation.
Terminate 1: I run the app and listen the inotify event within the main. Whenever processing one log file, I will sleep for 10 second then print the file name to console.
Terminte 2: I will copy multiple files at time T1 to the monitored directory. Before the app finishing processing all previous files, I will move multiple files at time T2. Then again time T3, I will copy multiple files to the directory before the app finishes.
Observation: The app processed all log files as I expected.
Question> Is this expected behavior of inotify or I just run lucky this morning? In other words, will inotify cache unprocessed events in case of simulation as above?
FYI: the code snippet I used:
#define EVENT_SIZE ( sizeof (struct inotify_event) ) #define BUFFER_LEN ( 1024 * ( EVENT_SIZE + NAME_MAX + 1) ) wd = inotify_add_watch( fd, root.string().c_str(), IN_CREATE | IN_MOVED_TO ); while ( true ) { length = read( fd, buffer, BUFFER_LEN ); for ( int i = 0; i < length; ) { const inotify_event *ptrEvent = reinterpret_cast<inotify_event *>(&buffer[i]); ... // processing the event sleep(10); // to simulate the long work i += INO_EVENT_SIZE + ptrEvent->len; } }
-13701479 0 You can simply extend your code:
if ( (str[i] == '-' && minus) || (str[i] >= '0' && str[i] <= '9') || (str[i] == 'e' || str[i] == 'E') )
to
char separator = ','; //or whatever you want int have_separator = 0; if ( (str[i] == '-' && minus) || (str[i] >= '0' && str[i] <= '9') || (str[i] == 'e' || str[i] == 'E') || str[i] == separator ) { if (str[i] == separator && have_separator == 0) { have_separator = 1; str_dbl[j++] = str[i]; continue; } ...
Please note that this is only some try to show the idea - not the real working code (but it could work anyway). You can use similar concept.
-27301946 0As Jake Wharton said
You can use a "@FieldMap Map<String, String>" for that.
Looks like Robospice Retrofit module is out of date.
-18907389 0For MySQL 5.7:
ALTER TABLE tbl_name RENAME INDEX old_index_name TO new_index_name
For MySQL older versions:
ALTER TABLE tbl_name DROP INDEX old_index_name, ADD INDEX new_index_name (...)
See http://dev.mysql.com/doc/refman/5.7/en/alter-table.html
-11654411 0 Single criteria query with two separate sets of restrictionsI'm wondering if you can create a single criteria query then somehow create two separate sets of restrictions with two completely different sets of results without having to issue a second query?
-35723634 0Simplest way would be to use a wild card character (*) and add the wildcarded
option
cts:search(fn:doc(),cts:word-query("*226", ('wildcarded')))
EDIT:
Although this matches the example documents, as Kishan points out in the comments, the wildcard also matches unwanted documents (e.g. containing "226226").
Since range indexes are not an option in this case because the data is mixed, here is an alternative hack:
cts:search( fn:doc(), cts:word-query( for $lead in ('', '0', '00', '000') return $lead || "226"))
Obviously, this depends on how many leading zeros there can be and will only work if this is known and limited.
-24274151 0The "enhanced for loop" as you call it (it's actually called the foreach
loop) internally uses an iterator for any iterable - including linked lists.
In other words it is O(n)
It does handle looping over arrays by using an integer and iterating over it that way but that's fine as it performs well in an array.
The only advantages of using an iterator manually are if you need to remove some or all of the elements as you iterate.
-21697697 0Yes, performing method calls like this is perfectly fine. They're marked as private
so they remain encapsulated within your class and unexposed to the outside world.
If these method calls started to cause the class/object to deviate its main purpose, breaking single responsibility principle, then it would be worth looking at breaking the class into finer units and injecting this new dependency via dependency injection. An example of this would be if the checkBaz
method was performing a database look-up.
In terms of unit testing, what you really want to do is program to an interface not implementation by creating an interface for your foo class and implementing it. This means whenever you program to it you're programming to a contract - allowing you to easily mock your IFoo
implementation.
eg:
class Foo implements IFoo { }
Your interface will look like this:
interface IFoo { public function setBaz($baz) public function setBar($bar) }
I would also recommend following the PEAR coding standard and make your class names uppercase first. Though if this is a decision made by you or your team then that's entirely your call.
-2674853 0 How to delete a string inside a file (.txt) in Java ProgrammingI would like to delete a string or a line inside a ".txt" file (for example filen.txt). For example, I have these lines in the file:
1JUAN DELACRUZ
2jUan dela Cruz
3Juan Dela Cruz
Then delete the 2nd line (2jUan dela Cruz
), so the ".txt" file will look like:
1JUAN DELACRUZ
3Juan Dela Cruz
How can I do this?
-36784340 0 Finding the last row with data using vbaI am creating a program in which everytime it generates, the generated data will appear in a specific sheet and arranged in specific date order . It looks like this.
But when I generate again, the existing data will be replaced/covered by the new data generated. Looks like this.
Now my idea is, before I am going to paste another data, I want to find out first what is the last used cell with value so that in the next generation of data, it wont be replaced/covered by the new one. Can someone help me with this. The output should look like this.
Any help everyone? Thanks!
-23514209 0One of the first things you need to learn about SQL (and relational databases) is that you shouldn't store multiple values in a single field.
You should create another table and store one value per row.
This will make your querying easier, and your database structure better.
select case when exists (select countryname from itemcountries where yourtable.id=itemcountries.id and countryname = @country) then 'national' else 'regional' end from yourtable
-22104970 0 Looking at the source of Set::new
:
# File set.rb, line 80 def initialize(enum = nil, &block) # :yields: o @hash ||= Hash.new enum.nil? and return if block do_with_enum(enum) { |o| add(block[o]) } else # you did not supply any block, when you called `new` # thus else part will be executed here merge(enum) end end
it seems that Set.new
calls method #add
internally. In the OP's example, block
is nil
, thus #merge
is called:
# File set.rb, line 351 def merge(enum) if enum.instance_of?(self.class) @hash.update(enum.instance_variable_get(:@hash)) else # in your case this else part will be executed. do_with_enum(enum) { |o| add(o) } end self end
Hence add
is called for each element of enum
([1,2]
). Here, you overrode the original #add
method, and within that method, you are calling the old #add
method with the argument 5
.
Set implements a collection of unordered values with no duplicates. Thus even if you added 5
twice, you are getting only one 5
. This is the reason you are not getting #<Set: {1,2}>
, but #<Set: {5}>
. As below, when you call Set.new
, the object #<Set: {5}>
is created just as I explained above:
require 'set' class Set alias :old_add :add def add(arg) arg = 5 old_add arg end end s = Set.new ([1,2]) s # => #<Set: {5}>
When you called s.add(3)
, your overridden add
method was called, and it again passed the 5
to the old add
method. As I said earlier, Set
doesn't contain duplicate values, thus the object will still be the same as the earlier #<Set: {5}>
.
I'm looking for a way to parse unicode strings of html and essentially split all of the elements of the string (html elements as well as individual tokens) and store them in a list. BeautifulSoup
obviously has some nice functionality for parsing html, such as the .get_text
method, but this doesn't preserve the tags themselves.
What I need is something like this. Given an html unicode string such as
s = u'<b>This is some important text!</b>
,
what I would like to have as a result is a list like this:
['<b>', 'This', 'is', 'some', 'important', 'text!', '</b>']
There must be an easy way to do this with BeautifulSoup that I'm just not seeing in SO searches. Thanks for reading.
EDIT: since this has been getting some questions as to the purpose of storing the tags, I'm interested in using the tags as features for a project in text classification. I'm experimenting with using different structural features from an online discussion forum in addition to the n-grams present within forum posts.
-13795206 0 Strange output from Java typecastI am playing around with simple encryption using RSA algorithms and found a strange bug.
private static Integer testEnc(Integer value){ Integer val = (int)Math.pow(value, 37); return val % 437; } private static Integer testDec(Integer value){ Integer val = new Integer((int)Math.pow(value, 289)); return val % 437; } public static void main(String[] args) { System.out.print("Encode 55 = "); Integer encoded = testEnc(2); System.out.println(encoded + "\n"); System.out.print(encoded + " decoded = "); Integer decoded = testDec(3977645); System.out.println(decoded + "n"); }
Both of the following functions return 97 regardless of input. If I comment out the modulus and just return val, the returned value is 2147483647.
Type casting double to int seems to be the issue but I am not sure why this is. These methods are static only because I was calling them from a main method.
-26871943 0You're looking for the extend
method.
>>> l = [1, 2, 3] >>> l.extend([4, 5, 6]) >>> print l [1, 2, 3, 4, 5, 6]
-23109791 0 I had a similar problem recently, specifically making the width match the parent div and also respond. I couldn't work out why Trust Pilot thought it appropriate to set something to make the height of the frame dynamic and not the width, but anyway.
Firstly, I had some CSS for the parent div, like:
<style type="text/css"> div.trust-pilot{ width: 100% !important; height: auto; } </style>
This may not actually be necessary, but I put it there anyway.
These are the 'trustbox' settings I used (see http://trustpilot.github.io/developers/#trustbox):
<div id="trust-pilot" class="trust-pilot"> <div class="tp_-_box" data-tp-settings="domainId: xxxxxxx, bgColor: F5F5F5, showRatingText: False, showComplementaryText: False, showUserImage: False, showDate: False, width: -1, numOfReviews: 6, useDynamicHeight: False, height: 348 "> </div> <script type="text/javascript"> (function () { var a = "https:" == document.location.protocol ? "https://ssl.trustpilot.com" : "http://s.trustpilot.com", b = document.createElement("script"); b.type = "text/javascript"; b.async = true; b.src = a + "/tpelements/tp_elements_all.js"; var c = document.getElementsByTagName("script")[0]; c.parentNode.insertBefore(b, c) })(); </script> </div>
Replace the domainId with something valid (in the case of this question, it's 3660907). Note that the width: -1 parameter might work already for you except if you want the page to be responsive (that is below).
Firstly, to make the width match the parent div, I used:
<script type="text/javascript"> jQuery( window ).load(function() { _width = jQuery('#trust-pilot').innerWidth(); jQuery('#tpiframe-box0').attr('width',_width); }); </script>
And then to make the box respond, I used:
<script type="text/javascript"> jQuery( window ).resize(function() { _width = jQuery('#trust-pilot').innerWidth(); jQuery('#tpiframe-box0').attr('width',_width); }); </script>
I hope that this helps. Shaun.
-16341343 0 Exactly which content-inserting block helpers have changed behaviour in Rails 3?The release notes for Rails 3.0 include this change:
7.4.2 Helpers with Blocks
Helpers like
form_for
ordiv_for
that insert content from a block use<%=
now:<%= form_for @post do |f| %> ... <% end %>
Your own helpers of that kind are expected to return a string, rather than appending to the output buffer by hand.
Helpers that do something else, like
cache
orcontent_for
, are not affected by this change, they need<%
as before.
We're in the process of migrating a web application from Rails 2.3.18 to Rails 3.1.12, and it would be very useful to have a complete list of such helpers that have changed, so that we can check all of their occurrences in our source code, but I'm having trouble finding an authoritative list of this kind.
I've tried looking through the git history of the rails project, but there seem to be many commits with related changes, and they're not obviously grouped on particular branch. For example, it seems to be clear that this list includes:
form_for
form_tag
fields_for
field_set_tag
... from 7b622786f,
link_to
... alluded to in e98474096 and:
div_for
content_tag_for
... alluded to in e8d2f48cff
remote_form_for
.... alluded to in 0982db91f, although it's removed in Rails 3.
However, I'm sure that's not complete - can anyone supply a complete list?
-20669873 0This cannot be done using only CSS3. CSS3 does not allow you to reference parent elements based on a hover of the child element. You'll need to use JavaScript for this.
Hopefully browsers will soon support the parent selector that is featured in the new CSS4 documentation
-38444485 0 Use std::bind to remove argumentsI'm currently coding against a library that uses an event system to signify user interface interactions. Each listener can either be a pointer to an object and a function to call, or a std::function. For example, the MenuItem object defines an OnClick event that will call a function that takes a MenuItem*:
someMenuItem->OnClick.addListener( this, &myObj.doSomeAction ); ... void myObj::doSomeAction( MenuItem* menuItem ) {}
or
someMenuItem->OnClick.addListener( []( MenuItem* menuItem ) {} );
It's often the case that doSomeAction is part of the public API of the class that we might want to call for some reason other than the user selecting the menu item. Is it possible to use std::bind to throw away the MenuItem* argument so that doSomeAction( MenuItem* menuItem )
could be defined as simply doSomeAction()
?
PS - I do realize that I could use lambdas to do the same thing, but if bind can do the same thing then it might be more stylistically pleasing to some.
-23350686 0Spring Social Facebook is a module within the Spring Social family of projects that enables you to connect your Spring application with the Facebook Graph API.
You invoke the nextToken() method 3 times. That will get you 3 different tokens
int pos = productsTokenizer .nextToken().indexOf("-"); String product = productsTokenizer .nextToken().substring(0, pos+1); String count= productsTokenizer .nextToken().substring(pos, pos+1);
Instead you should do something like:
String token = productsTokenizer .nextToken(); int pos = token.indexOf("-"); String product = token.substring(...); String count= token.substring(...);
I'll let you figure out the proper indexes for the substring() method.
Also instead of using a do/while structure it is better to just use a while loop:
while(productsTokenizer .hasMoreTokens()) { // add your code here }
That is don't assume there is a token.
-33224978 0 Is there a way to a prevent a String from being interpolated in Swift?I'm experimenting around the idea of a simple logger that would look like this:
log(constant: String, _ variable: [String: AnyObject]? = nil)
Which would be used like this:
log("Something happened", ["error": error])
However I want to prevent misuse of the constant/variable pattern like the following:
log("Something happened: \(error)") // `error` should be passed in the `variable` argument
Is there a way to make sure that constant
wasn't constructed with a string interpolation?
You can add directly the content string
var iframe = document.createElement('iframe'); var html = '<body><scr'+ 'ipt>alert(1)</s' + 'cript>Content</body>'; iframe.src = 'data:text/html;charset=utf-8,' + encodeURI(html); document.body.appendChild(iframe);
-10710677 0 Login in JSF 2.0 with Glassfish 3.1.2 and JAAS I'm having problems when I try to login with JSF 2. I am getting the following message:
WEB9102: Web Login Failed: com.sun.enterprise.security.auth.login.common.LoginException: Login failed: Security Exception
This is my login page:
<?xml version='1.0' encoding='UTF-8' ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" template="./modeloLogin.xhtml" xmlns:p="http://primefaces.prime.com.tr/ui" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html"> <ui:define name="content"> <p:growl id="growl" showDetail="true" life="3000" /> <div id="formulario"> <p:panel id="pnl" header="Login"> <h:form> <h:panelGrid columns="2" cellpadding="5"> <h:outputLabel for="username" value="Usuário:" /> <p:inputText value="#{beanLogin.username}" id="username" required="true" label="username" /> <h:outputLabel for="password" value="Senha:" /> <p:password value="#{beanLogin.password}" feedback="false" minLength="" id="password" label="password" /> <p:commandButton id="loginButton" value="Efetuar Login" update=":growl" action="#{beanLogin.login()}" ajax="false"/> <p:commandLink value="Esqueceu a senha?" ></p:commandLink> </h:panelGrid> </h:form> </p:panel> </div> </ui:define> </ui:composition>
And this is my BeanLogin:
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package sonic.action.login; import java.security.Principal; import javax.ejb.Stateless; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.context.FacesContext; import javax.inject.Named; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; /** * * @author 081315620876 */ @ManagedBean @SessionScoped public class BeanLogin { private String username; private String password; public BeanLogin() { } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String login() { FacesContext context = FacesContext.getCurrentInstance(); HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest(); System.out.println(context == null); System.out.println(request == null); try { request.login(this.username, this.password); if(request.isUserInRole("admin")) { return "/pages/protected/admin/index.xhtml?faces-redirect=true"; } else if(request.isUserInRole("professor")){ return "/pages/protected/professor/index.xhtml?faces-redirect=true"; } } catch (ServletException e) { context.addMessage(null, new FacesMessage("Login failed.")); return "error"; } return "login.xhtml"; } public void logout() { FacesContext context = FacesContext.getCurrentInstance(); HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest(); try { request.logout(); } catch (ServletException e) { context.addMessage(null, new FacesMessage("Logout failed.")); } } }
Thanks in advance for help :)
-30001286 0It is because the whitespace between the <li>
elements is significant. If you remove all whitespace, the elements will be right next to each other. Either you just do this:
<li class="orange start"><a href="">Home</a></li><li class="orange center"><a href="">Forum</a></li>
Or, if you want to keep the line breaks in code, which I usually think is a good thing, you can insert an HTML comment like this:
<li class="orange start"><a href="">Home</a></li><!-- --><li class="orange center"><a href="">Forum</a></li>
It's a matter of taste, but I tend to favor the latter because I find it more readable.
-1653217 0 How do I figure out the smtp_port for my localhost?I am using a script that is sending out emails and I am receiving the following error:
Warning: mail() [function.mail]: Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set() in C:\wamp\bin\php\php5.3.0\PEAR\Mail\mail.php on line 125
How to i figure out the stmp_port for my localhost?
EDIT:
I am sorry. I don't have my own server on my computer and I don't think I want to set one up either. I didn't realiza that it what it takes. I do have a hosting provider though and would like to figure out how to use their smtp information to send my mail though if anyone knows how to do that.
According to the reply by Nathan Adams, I can use my hosting provider's smtp information. What exactly do I need to find out where do I put that information in my php.ini file?
-35382289 1 Controlling pygame animation through text inputI need to create a fighting game that gives prompts and accepts input through text, such as a raw input and then performs the animation, while still have the characters animated, e.g. moving back and forth in a ready to fight stance. How would I go about this?
-18016725 0 Update specific object in arrayI have a DataTable and an array of objects that I loop through.
For each row in a data table, I search through my collection of objects with Linq, and if found, that object needs to be updated. But how do I refresh my collection without reloading it from the database?
Car[] mycars = Cars.RetrieveCars(); //This is my collection of objects //Iterate through Cars and find a match using (DataTable dt = data.ExecuteDataSet(@"SELECT * FROM aTable").Tables[0]) { foreach (DataRow dr in dt.Rows) //Iterate through Data Table { var found = (from item in mycars where item.colour == dr["colour"].ToString() && item.updated == false select item).First(); if (found == null) //Do something else { found.updated = true; Cars.SaveCar(found); //HERE: Now here I would like to refresh my collection (mycars) so that the LINQ searches on updated data. //Something like mycars[found].updated = true //But obviously mycars can only accept int, and preferably I do not want to reload from the database for performance reasons. }
How else can I search and update a single item in the array?
-5004015 0<s:HGroup gap="0"> <s:Label text="234 cm" fontSize="14"/> <s:Label text="2" baselineShift="4" fontSize="10"/> </s:HGroup>
The HGroup might not actually be needed, depending on context.
-8711744 0function displaymessage() { $("select").each(function() { this.selectedIndex = 0 }); }
this selects the first option (not necessarily having value = 0)
-16891837 0 Restrict a user to visit a particular page only certain number of timesHow to restrict a user (role) to visit a particular page only certain number of times?
I am using drupal 6. It's for premium content, I just want to give 5 premium content free.
-1545284 0i found this problem earlier and the work around was to use the builder directly
def test = { def sw = new StringWriter() def b = new MarkupBuilder(sw) b.html(contentType: "text/html") { div(id: "myDiv") { p "somess text inside the div" b.form(action: 'get') { p "inside form" } } } render sw }
will render the following HTML
<html contentType='text/html'> <div id='myDiv'> <p>somess text inside the div</p> <form action='get'> <p>inside form</p> </form> </div> </html>
-23445517 0 calculate expected cost of final product using atleast k out of n items in c Suppose I have 4 items and i have to pick at least 1 item to make a product out of them. I have cost corresponding to each item as Item1 -> 4 , Item2 -> 7 , Item3 -> 2 , Item4 -> 5.I have to to find expected cost of the final product means an average of all possible combinations Item used like if I use only 1 item then cost may be 4 , 7 , 2 , 5 and if if i use 2 items the cost would be 4+7 , 4+2 , 4+5 , 7+2 , 7+5 , 2+5 and similarly all combinations for using three items and 4+2+7+5 for using four items.Adding those all combinations and dividng them with no. of combination gives me expected cost of the final product.So I want to find sum of all these combinations then how can I go for it??
I think recursion will be used for calculating these combination but unable to apply ???
-36428352 0To make it works, you can use padding-left
instead of margin-left
and also adapt the width of the td
.modules-table > tbody > tr > td:nth-child(2) { width:256px; padding-left:80px; }
-18184897 0 HTML5 solution, min 5, max 10 characters
http://jsfiddle.net/xhqsB/102/
<form> <input pattern=".{5,10}"> <input type="submit" value="Check"></input> </form>
-22970292 0 A problem I ran into was related to the ordering in Application_Start(). Note the order of Web API configuraton below:
This does NOT work
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); GlobalConfiguration.Configure(WebApiConfig.Register); }
This does work
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); }
-11785670 0 Closing generic handlers before logging and other functionalities I am working on a high volumne API that needs to provide substantial logging for reporting purposes. In order to limit the effect of this logging functionality to the api users, I would like to finish the request, and then start logging all the stuff that needs to be logged.
Will flush, then close cause this to occur or will the client system wait until all the "Business Stuff " (BS for short) is complete?
-28901933 0Ok, i found a way to do that.
Basically i changed trigger()
function to debugEmail()
, and inside the class-wc-email-customer-invoice.php
file, copied the trigger()
into debugEmail()
and removed the this line to avoid the send of the email:
$this->send( $this->get_recipient(), $this->get_subject(), $this->get_content(), $this->get_headers(), $this->get_attachments() );
-12958793 0 onclick to clear form fields JavaScript I hope this question isn't duplicating something in the archives; I've looked but can't find an answer that solves my problem because I seem to be following the advice given.
I am making a dynamic form with JavaScript and would like to clear the prompts in each field when a user clicks in it. Here is part of what I have for one of the form fields. I can't figure out why onlick="this.value=' '"; isn't working. Any help would be much appreciated.
var VMake1 = document.createElement("input"); VMake1.name = "veh_1_make"; VMake1.type = "text"; VMake1.value= "Please enter the make of vehicle 1"; if (VMake1.value=="Please enter the make of vehicle 1") { onclick="this.value=''"; } placeVeh1Make.parentNode.insertBefore(VMake1,placeVeh1Make);
Thank you in advance for your help.
-34448066 0 Time the execution of batch file commands of VB scripts without using WScript.sleepI have a batch file which starts telnet server and stops telnet server with sleep time in between.
Script:
set OBJECT=WScript.CreateObject("WScript.Shell") WScript.sleep 5000 OBJECT.SendKeys "net stop TlntSvr{ENTER}" WScript.sleep 30000 OBJECT.SendKeys "net start TlntSvr{ENTER}" WScript.sleep 30000 OBJECT.SendKeys "exit"
Like you see the above code stops telnet services using net stop TlntSvr
and then starts telnet services using net start TlntSvr
with a sleep time in between like WScript.sleep 3000
.
Issue: Now I need to run this batch file in multiple systems PCs/laptop and in each execution cases, the time taken to start/stop telnet services/telnet service installation varies and hence I had to modify the sleep time every time when I am running the script in different systems.
Question: Is there a way to time the next execution such that as soon as the first execution completes only then it will start the next execution? Meaning I don't need to configure the sleep time for each laptops/PCS, the next execution will start only when the first execution is over according to each PC's own execution behavior.
-7460474 0Look at this post. It seems that the problem may be in the mapping of IUser in NH
-32997838 0 Number of times one string occurs within another in CI have written a function that uses the strstr() function to determine if string2 has any matches in string1. This works fine (I also convert both strings to lower case so that I can do a case-insensitive match.). However, strstr() only finds the first time the match occurs. Is there a way to use it to find each time a match occurs? For example:
string1[] = "ABCDEFABC"; string2[] = "ABC";
Would return 0 as a match is found in position 0, and 6 as it's found again in position 6?
Here's the original function as written (including call to function in main):
#include <stdio.h> #include <string.h> #include <stdlib.h> char *strstrnc(const char *str1, const char *str2); int main() { char buf1[80],buf2[80]; printf("Enter the first string to be compared: "); gets(buf1); printf("Enter the second string to be compared: "); gets(buf2); strstrnc(buf1,buf2); return 0; } char *strstrnc(const char *buf1, const char *buf2) { char *p1, *ptr1, *p2, *ptr2, *loc; int ctr; ptr1 = malloc(80 * sizeof(char)); ptr2 = malloc(80 * sizeof(char)); p1 = ptr1; p2 = ptr2; for (ctr = 0; ctr < strlen(buf1);ctr++) { *p1++ = tolower(buf1[ctr]); } *p1 = '\0'; for (ctr = 0; ctr < strlen(buf2);ctr++) { *p2++ = tolower(buf2[ctr]); } *p2 = '\0'; printf("The new first string is %s.\n", ptr1); printf("The new first string is %s.\n", ptr2); loc = strstr(ptr1,ptr2); if (loc == NULL) { printf("No match was found!\n"); } else { printf("%s was found at position %ld.\n", ptr2, loc-ptr1); } return loc; }
-35177242 0 Try to checkout your branch to a different folder than your original work folder, git will not delete the existing folders (from the different folder structure) to this new one - so you would still have folders in Tests\x-test and Tests\y-test.
However, git clean -fd
could be used to remove untracked directories.
I want to design animations, short animated video clips but even after Googling a little I got no clue about it.
I want ways that include programming rather than mouse clicks.
-24368496 0You, of course, could do this. You should loop all existing htmlElement instances with current class
$(".sel_region").each(function(index, element) { element.prototype.yourFunction = function() { console.log("exists!"); }; });
You should call this loop on Dom load
-19572181 0 CSS Generated Content allows us to insert and move content around a document. We can use this to create footnotes, endnotes, and section notes, as well as counters and strings, which can be used for running headers and footers, section numbering, and lists. -30758924 0
- Do I really need to use a mutex in a thread each time I access the data from the read-only array? If so could you explain why?
No. Because the data is never modified, there cannot be synchronization problem.
- Do I need to use a mutex in a thread when it writes to the result array even though this will be the only thread that ever writes to this element?
Depends.
In any case, take care of not writing into adjacent memory locations by different threads a lot. That could destroy the performance. See "false sharing". Considering, you probably don't have a lot of cores and therefore not a lot of threads and you say write is done only once, this is probably not going to be a significant problem though.
- Should I use atomic data types and will there be any significant time over head if I do?
If you use locks (mutex), atomic variables are not necessary (and they do have overhead). If you need no synchronization, atomic variables are not necessary. If you need synchronization, then atomic variables can be used to avoid locks in some cases. In which cases can you use atomics instead of locks... is more complicated and beyond the scope of this question I think.
Given the description of your situation in the comments, it seems that no synchronization is required at all and therefore no atomics nor locks.
- ...Would my array elements in this example be aligned, or is there some way to ensure they are?
As pointed out by Arvid, you can request specific alignment using the alginas keyword which was introduced in c++11. Pre c++11, you may resort to compiler specific extensions: https://gcc.gnu.org/onlinedocs/gcc-5.1.0/gcc/Variable-Attributes.html
-24873633 0Here's one possible way of reading a file and getting just the "chunks":
import java.io.*; import java.util.Scanner; public class ScanXan { public static void main(String[] args) throws IOException { Scanner s = null; try { s = new Scanner(new BufferedReader(new FileReader("xanadu.txt"))); while (s.hasNext()) { System.out.println(s.next()); } } finally { if (s != null) { s.close(); } } } }
You can take a look at the Java Scanner Tutorial for other ideas.
-20391612 0Note: its not a tested code. but it tries to solve your problem. Please give it a try
import csv with open(file_name, 'rb') as csvfile: marksReader = csv.reader(csvfile) for row in marksReader: if len(row) < 8: # 8 is the number of columns in your file. # row has some missing columns or empty continue # Unpack columns of row; you can also do like fname = row[0] and lname = row[1] and so on ... (fname,lname,subj1,marks1,subj2,marks2,subj3,marks3) = *row # you can use float in place of int if marks contains decimals totalMarks = int(marks1) + int(marks2) + int(marks3) print '%s %s scored: %s'%(fname, lname, totalMarks) print 'End.'
-15237073 0 D3.js: "Uncaught SyntaxError: Unexpected token ILLEGAL"? I've just downloaded D3.js from d3js.org (link to zip file), unzipped it, and referenced it in the following HTML page:
<html> <head> <title>D3 Sandbox</title> <style> </head> <body> <script src="/d3.v3.js"></script> </body> </html>
But when I load this page, my console (in Chrome) is giving me this error:
Uncaught SyntaxError: Unexpected token ILLEGAL: line 2
It doesn't like the pi and e symbols at the start of the file. Errrr... what can I do about this? I am serving the file with python's SimpleHTTPServer.
Update: yes I know I can just link to a CDN version, but I would prefer to serve the file locally.
-30795069 0While you could use AntiSamy to do it, I don't know how sensible that would be. Kinda defeats the purpose of it's flexibility, I think. I'd be curious about the overhead, even if minimal, to running that as a filter over just a regex.
Personally I'd probably opt for the regex route in this scenario. Your example appears to only strip the brackets. Is that acceptable in your situation? (understandable if it was just an example) Perhaps use something like this:
reReplace(string, "<[^>]*>", "", "ALL");
-1143722 0 Does the machine running IE 6 have its security settings set to reject cookies? Alternatively, if you are using one of the various techniques that supposedly allow you to run multiple versions of IE on the same machine, be aware that the results are not perfect, and often cause subtle aspects of the browser to break on one or more of the versions: for example, see this comment on Tredosoft's Multiple IE page about cookies failing in IE 6.
-2218937 0 HAS-A, IS-A terminology in object oriented languageI was just reading through the book and it had the terms, "HAS-A" and "IS-A" in it. Anyone know what they mean specifically? Tried searching in the book, but the book is 600 pages long. Thanks!
-24947366 0 Ruby on Rails: How to change the Foriegn Key values on a collection_select drop down?I have a drop down on my form which is a foreign key to another table:
<div class="field"> <td><%= f.label "#{column_name}" %></td> <td><%= f.collection_select "#{column_name}", Table.all, :id, :message_id %></td> </div>
"Table" has a column "message_id" which is a foreign_key to a different table "Messages".
The "Messages" table contains all the text/strings in my application.
When I load this code on my page it will give me a drop down list of all records but it will only show foreign key ID numbers pointing to the "Messages" table.
How can I change the foreign key ID numbers in the drop down to switch with message content I have on my Messages table?
-28332602 0The code you've shared seems very close. See below to output the first child <tr>
of the table, if an <a>
element is found, then stop looping through additional <a>
elements. What specific problems are you having with your code?
foreach ($html->find('table') as $name) { foreach ($name->find('a') as $elem) { echo $name->find('tr', 0)->plaintext; // echo first TR element echo $elem->plaintext.'<br>'; // echo A element break 1; // skip to the next table } }
-1383277 0 Using preprocessor directives in BlackBerry JDE plugin for eclipse? How to use preprocessor directives in BlackBerry JDE plugin for eclipse?
-29945137 0 Should I add the sass source map to my git repo?I had added style.css.map
to my .gitignore
file thinking that this was some kind of internal file that was not needed for public consumption.
Now I'm seeing that when Chrome (not Firefox) loads my page, it is looking for style.css.map
and returning a 404. I'm not explicitly asking it to load that file, but it seems to be getting called automatically.
For further context, this is a Wordpress site and I am including the style.scss
file in the repo.
I had a similar request from a client. but instead of an "x" to close the pop up it was to make it fade after x number of seconds.
see the see this link: http://ausauraair.com.au/product/ausaura-air/
by adding some jQuery i was able to make the box fade.
jQuery(document).ready(function( $ ) { $('.woocommerce-message').fadeTo(7000,1).fadeOut(2000); });
you could possibly use a similar technique but add a "x" button and then an on-click function to make the box close on click.
-5077413 0Try this:
DateTime dt = DateTime.ParseExact(strDate, "MMM dd, yyyy", CultureInfo.InvariantCulture);
-5873725 0
-12103872 0 The slaveOk property is now known as ReadPreference (.SECONDARY in this case) in newer Mongo Java driver versions. This can be set at the Mongo/DB/Collection level. Note that when you set ReadPreference at these levels, it applies for all callers (i.e. these objects are shared across threads).
Another approach is to try the ReadPreference.SECONDARY and if it fails, try without it and go to the master. This logic can be isolated to your repository layer, so the service layer doesn't have to deal with it. If you are doing this, you may want to set the ReadPreference at the DBQuery object, which is on a per-use basis.
-38287434 0If you run
getAnywhere("complete")
where is the package providing that function located? Is that package loaded in your .Rmd
file?
Just like Perl,
loop1: for (var i in set1) { loop2: for (var j in set2) { loop3: for (var k in set3) { break loop2; // breaks out of loop3 and loop2 } } }
as defined in EMCA-262 section 12.12. [MDN Docs]
Unlike C, these labels can only be used for continue
and break
, as Javascript does not have goto
(without hacks like this).
You can find the extra braces by making use of stack as below:
public static void main(final String[] args) { Stack<String> stack = new Stack<String>(); File file = new File("InputFile"); int lineCount = 0; try (BufferedReader br = new BufferedReader(new FileReader(file))) { String line; while ((line = br.readLine()) != null) { lineCount++; for (int i = 0; i < line.length(); i++) { if (line.charAt(i) == '{') { stack.push("{"); } else if (line.charAt(i) == '}') { if (!stack.isEmpty()) { stack.pop(); } else { System.out.println("Extra brace found at line number : " + lineCount); } } } } if (!stack.isEmpty()) { System.out.println(stack.size() + " braces are opend but not closed "); } } catch (Exception e) { e.printStackTrace(); } }
-38113933 0 Plivo Sales Engineer here.
Pavan is correct. You need to specify the Content-Type
header as application/json
for Parse to make a JSON string of the body:
headers: { "Content-Type": "application/json" },
You also should console.log(httpResponse)
(aka the Plivo API response) which will tell if you are doing something wrong (sending the wrong data, not authenticating correctly) or if you do something right. Either way it will show you an api_id
which you can use to look in your Plivo account dashboard debug logs and figure out what need to be changed. You can also go directly to the debug logs for a specific api_id
by making a url like this: https://manage.plivo.com/logs/debug/api/e58b26e5-3db5-11e6-a069-22000afa135b/
and replacing e58b26e5-3db5-11e6-a069-22000afa135b
with the api_id
returned by your Parse.Cloud.httpRequest
I've been using <div><jsp:text/></div>
It is very simple
Let me make you understand
first
public MyClass() { }
is simply a default public constructor
But when you write this
public MyClass() { this(); }
that means you are applying constructor chaining. Constructor Chaining is simply calling another constructor of the same class. This must be the first statement of the Constructor. But in your scenario you are passing nothing in this();
that means you are again calling the same constructor which will result in infinite loop. your class may have another constructor like this
public MyClass(int a) { }
then you may have called this
public MyClass(){ this(10); }
the above statement will make you to jump to the constructor receiving the same arguments that you have passed
Now,
public Myclass(){ super(); }
signifies that you are calling the constructor of the super class which is inherited by the class MyClass
. the same scenario occurs here, you have passed nothing in the super();
which will call the default constructor of the Super class.
I am having a problem on my Ionic2 application when deployed to an android 4.2.2
device, all the content appears heavily padded to the right as shown in the image attachment.
Your help will be greatly appreciated.
-3614420 0 I need an easy way to extract data from a few thousand emails (apple mail)I have about 2000 emails from a web contest my company did. All the emails are arranged in the following fashion:
You have received a new contest submission. Here are the details: Name: Bob Jones Email: bobjones@internet.com Location: Springfield, MA Age: 83 Mailinglist: true
All of these emails are saved in apple mail, is there any way I can extract this data into a text file, excel sheet, or something else more useable?
-6153541 0I found the problem/solution!
The problem is that in my Controller_Website I had this in my action_before()
:
// Create a new DM_Nav object to hold our page info // Make this page info available to all views as well $this->page_info = new DM_Nav; View::bind_global('page_info', $this->page_info);
The problem is the bind_global
– which is actually working as it's supposed to by letting you change the value of this variable after the fact... (A very neat feature indeed.)
The workaround/solution was to force the template to use only the original page_info
by detecting if it was an initial/main request. So at the very end of the action_before()
method of Controller_Website
where it says:
// Only if auto_render is still TRUE (Default) if ($this->auto_render === TRUE AND $this->request->is_initial()) {
I added this line to the end of that if
statement:
$this->template->page_info = $this->page_info; }
This line is redundant on initial/main requests, but it means that any additional sub-requests can still have access to their own page_info
values without affecting the values used in the template. It appears, then, that if you assign a property to a view and then attempt to bind_global()
the same property with new values, it doesn't overwrite it and uses the original values instead... (Which is why this solution works.) Interesting.
Someone noticed that on one of our Datomic transactor boxes, our process running the Datomic console is exposing database credentials.
Here is what our we get back when running ps aux | grep datomic
(linebreaks added for readability):
[ian@testtransactor ~]$ ps aux | grep datomic datomic 18372 0.8 55.7 6898068 4495820 ? Sl Nov01 31:20 java -server -cp lib/*:datomic-transactor-pro-0.9.5394.jar:samples/clj:bin:resources -Xmx4g -Xms4g -Ddatomic.printConnectionInfo=false -Doracle.net.tns_admin=/usr/lib/oracle/11.2/client64/network/admin -Dgraphite.host=graphite -Dgraphite.port=2003 -Dgraphite.prefix=datomic.testransactor clojure.main --main datomic.launcher /opt/datomic-pro-0.9.5394/config/transactor.properties root 18821 0.2 10.2 3503992 826664 ? Sl May20 504:04 java -server -Xmx1g -Doracle.net.tns_admin=/usr/lib/oracle/11.2/client64/network/admin -cp lib/console/*:lib/*:datomic-transactor-pro-0.9.5327.jar:samples/clj:bin:resources clojure.main -i bin/bridge.clj --main datomic.console -p 3035 dev datomic:sql://?jdbc:oracle:thin:USERNAME/PASSWORD@DB_SID
Our security team would prefer that the password be passed to the console process via a properties file, like we do with the transactor. Unfortunately, just mirroring it with clojure.main -i bin/bridge.clj --main datomic.console /opt/datomic-pro-0.9.5394/config/console.properties
doesn't work. Does anyone have suggestions on how to set this up?
There are some different matters in your question. First of all:
1: I don't really understand what you do in your query, but the limit clause must be at the end of a query, so you could try
select * from A join B on A.id = B.id limit 10
And this should work. More info on:
https://dev.mysql.com/doc/refman/5.0/en/select.html
2: Join vs. IN clause: the IN clause should always perform worse than the join. Imagine something like:
select * from A where A.id in (select id from B)
This will do a full scan on B table (select id from B
subquery) and then another full scan on A to try match the results.
However,
select * from A join B on A.id = B.id
should do a hash join between both tables, and if you have planned it right, id will be an index column, so it should be quite faster (and do no full scans on neither of them)
-13245470 1 Python: What is zip doing in this list comprehensionI am trying to understand this:
a = "hello" b = "world" [chr(ord(x) ^ ord(y)) for (x, y) in zip(a[:len(b)], b)]
I understand the XOR
part but I don't get what zip is doing.
Some CSS :
table td, table td * { vertical-align: top; }
-26091260 0 you have to add pull-left to the h1 too.. to have both of them floated..
also add a .cleafix class to the page-header div
<div class="container"> <div class="page-header clearfix"> <h1 class="pull-left"> <img src="logo.png"> Page title </h1> <div class="panel panel-primary pull-right"> ...content... </div> </div> ... </div>
-2233408 0 The "redundant include guard", as you call it, speeds up compilation.
Without the redundant guard, the compiler will iterate the entire foo.h file, looking for some code that might be outside the #ifndef
block. If it's a long file, and this is done many places, the compiler might waste a lot of time. But with the redundant guard, it can skip the entire #include
statement and not even reopen that file.
Of course, you'd have to experiment and see the actual amount of time wasted by the compiler iterating through foo.h and not actually compiling anything; and perhaps modern compilers actually look for this pattern and automatically know not to bother opening the file at all, I don't know.
(Begin edit by 280Z28)
The following header structure is recognized by at least GCC and MSVC. Using this pattern negates virtually all benefits you could gain with guards in the including files. Note that comments are ignored when the compiler examines the structure.
// GCC will recognize this structure and not reopen the file #ifndef SOMEHEADER_H_INCLUDED #define SOMEHEADER_H_INCLUDED // Visual C++ uses #pragma once to mark headers that shouldn't be reopened #if defined(_MSC_VER) && (_MSC_VER >= 1020) # pragma once #endif // header text goes here. #endif
(End edit)
-5668801 0 Entity framework code-first null foreign keyI have a User
< Country
model. A user belongs to a country, but may not belong to any (null foreign key).
How do I set this up? When I try to insert a user with a null country, it tells me that it cannot be null.
The model is as follows:
public class User{ public int CountryId { get; set; } public Country Country { get; set; } } public class Country{ public List<User> Users {get; set;} public int CountryId {get; set;} }
Error: A foreign key value cannot be inserted because a corresponding primary key value does not exist. [ Foreign key constraint name = Country_Users ]"}
What version of Opentaps are you running ? did you clone from the master git repository ?
are you trying to compile the code in the ide? I suggest you run ./ant inside the project and don't use the ide to compile
-4619893 0 Form submission in rails 3I decided to start a little project in rails 3 and I am a little bit stuck on a form... Where can I specified the f.submit action should go to a special controller / action ?
The code in the form is:
<%= form_for @user, :url => { :action => "login" } do |f| %> <div class="field"> <%= f.text_field :email %><br /> <%= f.text_field :password %> </div> <div class="actions"> <%= f.submit %> </div> <% end %>
User is defined as @user = User.new in "index" method of "home_controller".
but I have the error:
No route matches {:controller=>"home", :action=>"login"}
as soon as I run http://0.0.0.0:3000
I am very sorry for this newbee question but I cannot find the routing details (I worked a little bit with rails a couple of years ago but...)
Thanks, Luc
-26211646 0 Include Bootstrap form css aloneI have site created already which is not bootstrap, and now i need to implement the bootstrapValidator for the validation purpose, if i include bootstrap css then my site style also changing,
Is there any way to include bootstrap form styles alone in html, apart from cut copy in bootstrap css file?
-24274017 0This is the solution, I didn't change anything in the original code and script:
<div id="content"> <div id="tab1">@{ Html.RenderAction("TabbedIndex", "Stuff", new { claimed = false }); }</div> <div id="tab2">@{ Html.RenderAction("TabbedIndex", "Stuff", new { claimed = true }); }</div> </div>
-5255938 0 as someone who spent time looking for such a solution for my company's product--I can tell you that you are not going to find one. It does not exist. Sorry, dude. :(
-38048090 0It's a bug in iex
. I've tracked down and fixed it: https://github.com/elixir-lang/elixir/pull/4895
Before,I use
<select id="queryUser" parameterType="userInfo"> select * from uc_login_${tableSuffix} </select> userInfo:{ private String tableSuffix; }
and I create userInfo with tableSuffix like
new DateTime().getYear() + "_" + new DateTime().getMonthOfYear();
and now I select from uc_login_nowYear_nowMonth(uc_login_2015_12). Now,I don't want create tabkeSuffix by myself,I want Mybatis help me to dynamic create sql in xml. How can I do that?
-5092644 0In the end I canned the joined DataTable idea and just read the data straight into a List of my objects with a DataReader. So this whole question is now pretty redundant for me. Hopefully someone else will find it useful.
-12711873 0 Excel VBA Dynamic Ranges/Index selectionsI'm trying to create a talent calculator for myself, and the entire first sheet calls to a Data sheet that does all the background work. On the excel sheet itself, everything calls to INDEX(TableName,Row,Column) because it's much easy to keep track of and I find I often have to move data around while working on it so handling Names is easier than handling cell references.
However, I also use VBA on this sheet, and I'm rather new to it. Instead of, for example, using Range("C1"), if C1 was part of table TableOne, would there be a way to reference it like in the Excel formulas such as INDEX(TableOne,1)?
-26522897 0Usually using
lxml
and xpath is a common approach in Python.
As you want to use minidom
explicitly, you can use the following method to get all HTML elements of a particular tag.
matches = dom.getElementsByTagName("foo") for e in matches: print(e.firstChild.nodeValue)
-840421 0 You can check if its a digit:
char c; scanf( "%c", &c ); if( isdigit(c) ) printf( "You entered the digit %c\n", c );
-11020766 0 I really liked Phaxmohdem solution, so I added a bit more to it. I hope others continue to improve this. =)
<NotepadPlus> <UserLang name="X12" ext=""> <Settings> <Global caseIgnored="no" /> <TreatAsSymbol comment="no" commentLine="no" /> <Prefix words1="no" words2="no" words3="no" words4="no" /> </Settings> <KeywordLists> <Keywords name="Delimiters">000000</Keywords> <Keywords name="Folder+"></Keywords> <Keywords name="Folder-"></Keywords> <Keywords name="Operators">* : ^ ~ +</Keywords> <Keywords name="Comment"></Keywords> <Keywords name="Words1">ISA IEA GS GE ST SE</Keywords> <Keywords name="Words2">AAA ACT ADX AK1 AK2 AK3 AK4 AK5 AK6 AK7 AK8 AK9 AMT AT1 AT2 AT3 AT4 AT5 AT6 AT7 AT8 AT9 AT8 AT9 B2 B2A BEG BGN BHT BPR CAS CL1 CLM CLP CN1 COB CR1 CR2 CL3 CL4 CR5 CR6 CRC CTX CUR DMG DN1 DN2 DSB DTM DTP EB EC ENT EQ FRM G61 G62 HCP HCR HD HI HL HLH HSD ICM IDC III IK3 IK4 IK5 INS IT1 K1 K2 K3 L3 L11 LIN LQ LUI LX MEA MIA MOA MPI MSG N1 N2 N3 N4 NM1 NTE NX OI PAT PER PLA PLB PO1 PRV PS1 PWK QTY RDM REF RMR S5 SAC SBR SLN STC SV1 SV2 SV3 SV4 SV5 SVC SVD TA1 TOO TRN TS2 TS3 UM</Keywords> <Keywords name="Words3">LS LE</Keywords> <Keywords name="Words4">00 000 0007 001 0010 0019 002 0022 003 004 00401 004010 004010X061 004010X061A1 004010X091 004010X091A1 004010X092 004010X092A1 004010X093 004010X093A1 004010X094 004010X094A1 004010X095 004010X095A1 004010X096 004010X096A1 004010X098 004010X098A1 005 00501 005010 005010X212 005010X217 005010X218 005010X220 005010X220A1 005010X221 005010X221A1 005010X222 005010X222A1 005010X223 005010X223A1 005010X223A2 005010X224 005010X224A1 005010X224A2 005010X230 005010X231 005010X279 005010X279A1 006 007 0078 008 009 01 010 011 012 013 014 015 016 017 018 019 02 020 021 022 023 024 025 026 027 028 029 03 030 031 032 035 036 04 05 050 06 07 08 09 090 091 096 097 0B 0F 0K 102 119 139 150 151 152 18 193 194 196 198 1A 1B 1C 1D 1E 1G 1H 1I 1J 1K 1L 1O 1P 1Q 1R 1S 1T 1U 1V 1W 1X 1Y 1Z 200 232 233 270 271 276 277 278 286 290 291 292 295 296 297 2A 2B 2C 2D 2E 2F 2I 2J 2K 2L 2P 2Q 2S 2U 2Z 30 300 301 303 304 307 31 314 318 330 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 356 357 36 360 361 374 382 383 385 386 388 393 394 3A 3C 3D 3E 3F 3G 3H 3I 3J 3K 3L 3M 3N 3O 3P 3Q 3R 3S 3T 3U 3V 3W 3X 3Y 3Z 40 405 41 417 431 434 435 438 439 441 442 444 446 45 452 453 454 455 456 458 46 461 463 471 472 473 474 480 481 484 492 4A 4B 4C 4D 4E 4F 4G 4H 4I 4J 4K 4L 4M 4N 4O 4P 4Q 4R 4S 4U 4V 4W 4X 4Y 4Z 539 540 543 573 580 581 582 598 5A 5B 5C 5D 5E 5F 5G 5H 5I 5J 5K 5L 5M 5N 5O 5P 5Q 5R 5S 5T 5U 5V 5W 5X 5Y 5Z 607 636 695 6A 6B 6C 6D 6E 6F 6G 6H 6I 6J 6K 6L 6M 6N 6O 6P 6Q 6R 6S 6U 6V 6W 6X 6Y 70 71 72 738 739 74 77 771 7C 82 820 831 834 835 837 85 850 866 87 8H 8U 8W 938 997 999 9A 9B 9C 9D 9E 9F 9H 9J 9K 9V 9X A0 A1 A172 A2 A3 A4 A5 A6 A7 A8 A9 AA AAE AAG AAH AAJ AB ABB ABC ABF ABJ ABK ABN AC ACH AD ADD ADM AE AF AG AH AI AJ AK AL ALC ALG ALS AM AN AO AP APC APR AQ AR AS AT AU AV AX AY AZ B1 B2 B3 B4 B6 B680 B7 B9 BA BB BBQ BBR BC BD BE BF BG BH BI BJ BK BL BLT BM BN BO BOP BP BPD BQ BR BS BT BTD BU BV BW BX BY BZ C1 C2 C3 C4 C5 C6 C7 C8 C9 CA CAD CB CC CCP CD CE CER CF CG CH CHD CHK CI CJ CK CL CLI CLM01 CM CN CNJ CO CON CP CQ CR CS CT CV CW CX CY CZ D2 D3 D8 D9 D940 DA DB DCP DD DEN DEP DG DGN DH DI DJ DK DM DME DN DO DP DQ DR DS DT DX DY E1 E1D E2 E2D E3 E3D E5D E6D E7 E7D E8 E8D E9 E9D EA EAF EBA ECH ED EI EJ EL EM EMP EN ENT01 EO EP EPO ER ES ESP ET EV EW EX EXS EY F1 F2 F3 F4 F5 F6 F8 FA FAC FAM FB FC FD FE FF FH FI FJ FK FL FM FO FS FT FWT FX FY G0 G1 G2 G3 G4 G5 G740 G8 G9 GB GD GF GH GI GJ GK GM GN GO GP GR GW GT GY H1 H6 HC HE HF HH HJ HLT HM HMO HN HO HP HPI HR HS HT I10 I11 I12 I13 I3 I4 I5 I6 I7 I8 I9 IA IAT IC ID IE IF IG IH II IJ IK IL IN IND IP IR IS IV J1 J3 J6 JD JP KG KH KW L1 L2 L3 L4 L5 L6 LA LB LC LD LI LM LOI LR LT LU LTC LTD M1 M2 M3 M4 M5 M6 M7 M8 MA MB MC MD ME MED MH MI MJ ML MM MN MO MOD MP MR MRC MS MSC MT N5 N6 N7 N8 NA ND NE NF NH NI NM109 NL NN NON NQ NR NS NT NTR NU OA OB OC OD ODT OE OF OG OL ON OP OR OT OU OX OZ P0 P1 P2 P3 P4 P5 P6 P7 PA PB PC PD PDG PE PI PID PL PN PO POS PP PPO PQ PR PRA PRP PS PT PU PV PW PXC PY PZ Q4 QA QB QC QD QE QH QK QL QM QN QO QQ QR QS QV QY R1 R2 R3 R4 RA RB RC RD8 RE REC RET RF RGA RHB RLH RM RN RNH RP RR RT RU RW RX S1 S2 S3 S4 S5 S6 S7 S8 S9 SA SB SC SD SEP SET SFM SG SJ SK SL SP SPC SPO SPT SS STD SU SV SWT SX SY SZ T1 T10 T11 T12 T2 T3 T4 T5 T6 T7 T8 T9 TC TD TE TF TJ TL TM TN TNJ TO TPO TQ TR TRN02 TS TT TTP TU TV TWO TZ UC UH UI UK UN UP UPI UR UT V1 V5 VA VER VIS VN VO VS VV VY W1 WA WC WK WO WP WR WU WW X12 X3 X4 X5 X9 XM XN XP XT XV XX XX1 XX2 XZ Y2 Y4 YR YT YY Z6 ZB ZH ZK ZL ZM ZN ZO ZV ZX ZZ</Keywords> </KeywordLists> <Styles> <WordsStyle name="DEFAULT" styleID="11" fgColor="000000" bgColor="FFFFFF" fontName="" fontStyle="0" /> <WordsStyle name="FOLDEROPEN" styleID="12" fgColor="000000" bgColor="FFFFFF" fontName="" fontStyle="0" /> <WordsStyle name="FOLDERCLOSE" styleID="13" fgColor="000000" bgColor="FFFFFF" fontName="" fontStyle="0" /> <WordsStyle name="KEYWORD1" styleID="5" fgColor="0000FF" bgColor="FFFFFF" fontName="" fontStyle="1" /> <WordsStyle name="KEYWORD2" styleID="6" fgColor="800000" bgColor="FFFFFF" fontName="" fontStyle="1" /> <WordsStyle name="KEYWORD3" styleID="7" fgColor="00FF00" bgColor="FFFFFF" fontName="" fontStyle="1" /> <WordsStyle name="KEYWORD4" styleID="8" fgColor="8000FF" bgColor="FFFFFF" fontName="" fontStyle="0" /> <WordsStyle name="COMMENT" styleID="1" fgColor="000000" bgColor="FFFFFF" fontName="" fontStyle="0" /> <WordsStyle name="COMMENT LINE" styleID="2" fgColor="000000" bgColor="FFFFFF" fontName="" fontStyle="0" /> <WordsStyle name="NUMBER" styleID="4" fgColor="000000" bgColor="FFFFFF" fontName="" fontStyle="0" /> <WordsStyle name="OPERATOR" styleID="10" fgColor="FF00FF" bgColor="FFFFFF" fontName="" fontStyle="0" /> <WordsStyle name="DELIMINER1" styleID="14" fgColor="000000" bgColor="FFFFFF" fontName="" fontStyle="0" /> <WordsStyle name="DELIMINER2" styleID="15" fgColor="000000" bgColor="FFFFFF" fontName="" fontStyle="0" /> <WordsStyle name="DELIMINER3" styleID="16" fgColor="000000" bgColor="FFFFFF" fontName="" fontStyle="0" /> </Styles> </UserLang> </NotepadPlus>
-971828 0 There is also garbage collection to consider - if you are using new() a lot, then that will create lots of objects on the heap that will have to be garbage collected, but Clear() won't create any new heap objects (although this is only really an issue if you're doing this thousands of times)
-13026080 0If you want to AUTOMATICALLY redirect from www.google.com
to www.google.com#something
you can use firefox's redirector addon.
Whenever you load www.google.com, the addon will automatically change the URL in the location bar to www.google.com#something (or whatever you specify.)
Alternately, you could use firefox addon, called greasemonkey, to write the 1 line script given by Jacob. That will also serve the purpose.
Off course, both these solutions are specific to firefox.
-31940324 0 vb.net to pull data from Excel Data GridViewI have 78 excel columns and I have 5 datagridviews.
How do I make connection?
-18114495 0 Imagemagick position and size of a sub-imageIn imagemagick, it is very easy to diff two images using compare, which produces an image with the same size as the two images being diff'd, with the diff data. I would like to use the diff data and crop that part from the original image, while maintaining the image size by filling the rest of the space with alpha.
I am now trying to figure the bounding box of the diff, without luck. For example, below is the script I am using to produce the diff image, see below. Now, I need to find the bounding box of the red color part of the image. The bounding box is demonstrated below, too. Note that the numbers in the image are arbitrary and not the actual values I am seeking.
compare -density 300 -metric AE -fuzz 10% ${image} ${otherImage} -compose src ${OUTPUT_DIR}/diff${i}-${j}.png
According to Microsoft Developer Network, both Range.Delete
and Worksheet.Delete
method will return a value. However, by using the MsgBox
function I can only view the return value for the Worksheet.Delete
method but have no luck with the Range.Delete
method. The code I used is MsgBox Worksheets("Sheet1").Delete
Here are the two articles from MSDN for your information: https://msdn.microsoft.com/en-us/library/office/ff837404.aspx https://msdn.microsoft.com/en-us/library/office/ff834641.aspx
-9514715 0It might be possible, try setting the window background color to clear, as well as the view controller's view background color.
I say it might be possible because I've seen my home screen while using some apps, for example, the Facebook app sometimes shows it during a transition (it might be a bug on either Facebook or the OS).
Anyway, I'm pretty sure that kind of app would be rejected from the App Store, so be advised.
-21366036 0 Correctly serializing objects in javacan anyone help me to spot the mistake? I am trying to pass certain information (min/max/avg ages) from file people.txt (which consists of 200 lines like 'Christel ; MacKay ; 4"2' ; 38'), to another file, by serializing. Here's the first class, where I process some info about these people:
import java.io.Serializable; @SuppressWarnings("serial") public class Person implements Serializable { private String firstname; private String lastname; private int age; public Person (String PersonFN, String PersonLN, int PersonA) { firstname = PersonFN; lastname = PersonLN; age = PersonA; } public String toString() { return "Name: "+firstname+" "+lastname+" Age: "+age; } public int getAge() { return age; } }
And another one, which does all the job:
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.*; public class Collection { int min; int max; int total; private static ArrayList<Person> people; public Collection() { people = new ArrayList<Person>(); min = 100; max = 1; total = 0; } BufferedReader fr = null; BufferedWriter fw = null; public void readFromFile() throws IOException { fr = new BufferedReader (new FileReader("people.txt")); String line = null; StringTokenizer st; while (fr.ready()) { line = fr.readLine(); st = new StringTokenizer(line); String name = st.nextToken(";"); String surname = st.nextToken(";").toUpperCase(); String height = st.nextToken(";"); int age = Integer.parseInt(st.nextToken(";").trim()); Person p = new Person (name, surname, age); p.toString(); people.add(p); //for the 2nd part if(age < min) min = age; if (age > max) max = age; total = total + age; } } public int minAge() { int minA = 100; for (int i = 0; i < people.size(); i++) { Person p = people.get(i); int age = p.getAge(); if (age < minA) { minA = age; } } System.out.print(minA+"; "); return minA; } public int maxAge() { int maxA = 1; for (int i = 0; i < people.size(); i++) { Person p = people.get(i); int age = p.getAge(); if (age > maxA) { maxA = age; } } System.out.print(maxA+"; "); return maxA; } public float avgAge() { int sum = 0; for (int i = 0; i < people.size(); i++) { Person p = people.get(i); int age = p.getAge(); sum = sum + age; } float avgA = sum / people.size(); System.out.print(avgA); return avgA; } public int fastMinAge() { //System.out.print("Minimum age: " + min); return min; } public int fastMaxAge() { return max; } public float fastAvgAge() { return total / people.size(); } public void writeToFile(String filename) throws IOException { StringBuffer val = new StringBuffer ("Minimum age: "); val.append(fastMinAge()); val.append("\n Maximum age: "); val.append(fastMaxAge()); val.append("\n Average age: "); val.append(fastAvgAge()); BufferedWriter out = new BufferedWriter(new FileWriter(filename)); String outText = val.toString(); out.write(outText); out.close(); } public static void main(String[] args) throws IOException, ClassNotFoundException { Collection c = new Collection(); c.readFromFile(); for(Person d: people) { System.out.println(d); } c.minAge(); c.maxAge(); c.avgAge(); c.fastMinAge(); c.fastMaxAge(); c.fastAvgAge(); c.writeToFile("RESULTS.txt"); String filename = "people.txt"; //FileOutputStream fos = new FileOutputStream(filename); ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(filename)); os.writeObject(c); os.close(); String filename1 = "results1.txt"; FileInputStream fis = new FileInputStream(filename1); ObjectInputStream ois = new ObjectInputStream(fis); Collection p = (Collection) ois.readObject(); ois.close(); } }
When I run the code, it creates the RESULTS.txt file and adds the correct information there. I'm sure there's something wrong with this exact part of code:
String filename = "people.txt"; //FileOutputStream fos = new FileOutputStream(filename); ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(filename)); os.writeObject(c); os.close(); String filename1 = "results1.txt"; FileInputStream fis = new FileInputStream(filename1); ObjectInputStream ois = new ObjectInputStream(fis); Collection p = (Collection) ois.readObject(); ois.close();
By the way, my people.txt file changes into "¬ķ {sr java.io.NotSerializableException(Vx ē†5 xr java.io.ObjectStreamExceptiondĆäk¨9ūß xr java.io.IOExceptionl€sde%š« xr java.lang.ExceptionŠż>;Ä xr java.lang.ThrowableÕĘ5'9wøĖ L causet Ljava/lang/Throwable;L detailMessaget Ljava/lang/String;[ stackTracet [Ljava/lang/StackTraceElement;L suppressedExceptionst Ljava/util/List;xpq ~ t SD3lab1.Collectionur [Ljava.lang.StackTraceElement;F*<<ż"9 xp sr java.lang.StackTraceElementa Å&6Ż… I lineNumberL declaringClassq ~ L fileNameq ~ L methodNameq ~ xp˙˙˙˙t java.io.ObjectOutputStreampt writeObject0sq ~ ˙˙˙˙q ~ pt writeObjectsq ~ ©q ~ t Collection.javat mainsr &java.util.Collections$UnmodifiableListü%1µģˇ L listq ~ xr ,java.util.Collections$UnmodifiableCollectionB €Ė^÷ L ct Ljava/util/Collection;xpsr java.util.ArrayListxŅ™Ēa¯ I sizexp w xq ~ x", and I get these errors on the console:
Exception in thread "main" java.io.NotSerializableException: SD3lab1.Collection at java.io.ObjectOutputStream.writeObject0(Unknown Source) at java.io.ObjectOutputStream.writeObject(Unknown Source) at SD3lab1.Collection.main(Collection.java:169)
MANY THANKS FOR ANY HELP
-5724765 0You can check for the license for the first time, then cache it. The next time when your app runs, read the license from the cache, and also start a Thread that gets the license from your server. If the license that you got from the server is now invalid. You can pop up a dialog box to tell the user that the license is invalid, remove the cached license, and quit the app.
-38156646 0 Using @RequestParam for multipartfile is a right way?I'm developing a spring mvc application and I want to handle multipart request in my controller. In the request I'm passing MultiPartFile
also, currently I'm using @RequestParam
to get the file paramaeter, the method look like,
@RequestMapping(method = RequestMethod.POST) public def save( @ModelAttribute @Valid Product product, @RequestParam(value = "image", required = false) MultipartFile file) { ..... }
Above code works well in my service and the file is getting on the server side. Now somewhere I seen that in case of file need to use @RequestPart
annotation instead of @RequestParam
. Is there anything wrong to use @RequestParam
for file ? Or it may cause any kind of error in future?
You can do like this (note that I have moved some of your generic parameters and constraints around).
public class MyType { public void doStuff(int i){} } public abstract class ABase<T>where T : class, new() { public abstract T method(int arg); } public class AChild : ABase<MyType> { override public MyType method(int arg) { MyType e = new MyType(); e.doStuff(arg); // no more error here return e; } }
-2579588 0 Incorrect emacs indentation in a C++ class with DLL export specification I often write classes with a DLL export/import specification, but this seems to confuse emacs' syntax parser. I end up with something like:
class myDllSpec Foo { public: Foo( void ); };
Notice that the "public:" access spec is indented incorrectly, as well as everything that follows it.
When I ask emacs to describe the syntax at the beginning of the line containing public, I get a return of:
((label 352))
If I remove the myDllSpec, the indentation is correct, and emacs tells me that the syntax there is:
((inclass 352) (access-label 352))
Which seems correct and reasonable. So I conclude that the syntax parser is not able to handle the DLL export spec, and that this is what's causing my indentation trouble.
Unfortunately, I don't know how to teach the parser about my labels. Seems that this is pretty common practice, so I'm hoping there's a way around it.
-23893046 0 How to add timestamp to the existing mysql tableI am updatng my application from standard php into laravel and i am creating two new field in each of my table which is created_at and updated_at.
The problem is both field has being set as null for the existing data. How to make a query to set the created_at and updated_at to the current date time??
-32405642 0I need to see the full query, but at a guess it is going to be:
LEFT JOIN adcfvc ON adcfvc.advert_id = $table.id
Where $table is the tablename of the first table.
-34273628 0You have to tell the server that your body is in a JSON format by adding the right request header:
... request.HTTPBody = [newNewString dataUsingEncoding:NSUTF8StringEncoding]; request.HTTPMethod = @"POST"; [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; ...
-5625589 0 Javac erroring out when compiling Servlet libraries I am using ubuntu and I have set my paths to be the following:
JAVA_HOME=/usr/local/jdk1.6.0_24 export CLASSPATH=/usr/local/tomcat/lib export JAVA_HOME
I thought that would put the servlet libraries in the compile path, but I am still getting compile errors like this:
package javax.servlet does not exist [javac] import javax.servlet.ServletException;
Any ideas how to fix this or what I am doing wrong? The general Java libraries seem to be working fine.
-6356792 0I thought I'd answer this one since it has a few votes, although based on Christina's other questions I don't think this will be a usable answer for her since a 50,000-word language model almost certainly won't have an acceptable word error rate or recognition speed (or most likely even function for long) with in-app recognition systems for iOS that use this format of language model currently, due to hardware constraints. I figured it was worth documenting it because I think it may be helpful to others who are using a platform where keeping a vocabulary this size in memory is more of a viable thing, and maybe it will be a possibility for future device models as well.
There is no web-based tool I'm aware of like the Sphinx Knowledge Base Tool that will munge a 50,000-word plaintext corpus and return an ARPA language model. But, you can obtain an already-complete 64,000-word DMP language model (which can be used with Sphinx at the command line or in other platform implementations in the same way as an ARPA .lm file) with the following steps:
In that folder is a file called language_model.arpaformat.DMP which will be your language model.
https://cmusphinx.svn.sourceforge.net/svnroot/cmusphinx/trunk/pocketsphinx/model/lm/en_US/cmu07a.dic
Convert the contents of cmu07a.dic to all uppercase letters.
If you want, you could also trim down the pronunciation dictionary by removing any words from it which aren't found in the corpus language_model.vocabulary (this would be a regex problem). These files are intended for use with one of the Sphinx English-language acoustic models.
If the desire to use a 50,000-word English language model is driven by the idea of doing some kind of generalized large vocabulary speech recognition and not by the need to use a very specific 50,000 words (for instance, something specialized like a medical dictionary or 50,000-entry contact list), this approach should give those results if the hardware can handle it. There are probably going to be some Sphinx or Pocketsphinx settings that will need to be changed which will optimize searches through this size of model.
-34835581 0 Buy Google search result data?Wanted to use GoogleAPI to search the Internet and return the results in JSON.
Google API allows this to search within a specific website, but I could not find this to the entire web. Is this possible? Thanks
I have data like this
DECLARE @Employee TABLE (EmployeeName NVARCHAR(50), EmployeeAddress NVARCHAR(50), WorkedLocations NVARCHAR(50), IdNumbers NVARCHAR(50), UpdatedOn Date ) Insert into @Employee Values ('Alex',' Alex address','Cisco','12345',GETDATE()), ('John','John Address','Microsoft','23456',GETDATE()), ('Bob','Bob Address','CiscoMicrosoft','78903,89067',GETDATE()), ('Bill','Bill Address','Microsoft','54652',GETDATE()) select * from @Employee
In 3rd row based on the 3rd column value a row has to be created and 4th row value should be split and assigned to respective 3rd column. Please see below required output
DECLARE @Employee TABLE ( EmployeeName NVARCHAR(50) , EmployeeAddress NVARCHAR(50) , WorkedLocations NVARCHAR(50) , IdNumbers NVARCHAR(50) ,UpdatedOn Date) Insert into @Employee Values ('Alex',' Alex address','Cisco','12345',GETDATE()), ('John','John Address','Microsoft','23456',GETDATE()), ('Bob','Bob Address','Cisco','78903',GETDATE()), ('Bob','Bob Address','Microsoft','89067',GETDATE()), ('Bill','Bill Address','Microsoft','54652',GETDATE()) select * from @Employee
Thanks in advance!
-31613403 0I was seing this same issue today, and I didn't have any code changes. Twitter just suddenly stopped authorizing and told me it couldn't get request token.
I just had to restart my emulator and it started working again.
-35776087 0You need to modify web.xml to use the special role ** as indicated here: Authorization section for Jetty Authentication:
access granted to any user who is authenticated, regardless of roles. This is indicated by the special value of "**" for the <role-name> of a <auth-constraint> in the <security-constraint>
So, this is what my security-constraint looks like:
<security-constraint> <web-resource-collection> <web-resource-name>Secured Solr Admin User Interface</web-resource-name> <url-pattern>/*</url-pattern> </web-resource-collection> <auth-constraint> <role-name>**</role-name> </auth-constraint> </security-constraint>
-21756702 0 WCF service Endpoint X509 certificate Identity I have service on one machine which I would like to access from another machine. So I need a help with setting the identity of the endpoints because i am getting
The identity check failed for the outgoing message. The expected identity is 'identity(http://schemas.xmlsoap.org/ws/2005/05/identity/right/possessproperty:http://schemas.xmlsoap.org/ws/2005/05/identity/claims/thumbprint)' (http://schemas.xmlsoap.org/ws/2005/05/identity/claims/thumbprint%29%27) for the 'net.tcp:...' target endpoint.
My service is configured to use certificate for transport security and validation mode is set to ChainTrust.
What type of identity should I set on the client of this service since I am accessing the service using the ip address of the machine hosting it and not the dns name? More precisely what EndpointIdentity setting should I set to the EndpointAddress when I am setting the service host and what should I use on the client when I am setting the EndpointAddress?
On both client and the service machine the issuer of the certificates used to secure the transport is in the trusted authorities.
-23987241 0 I'm trying to sort an NSMutableArray of objects by a field of type doublethe code I'm currently trying doesn't give any errors but after it runs nothing is sorted. This is my first time in objective-c so I'm hoping there's something obvious here that I'm missing.
NSSortDescriptor * sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"distanceOfPlace" ascending:true] ; [surroundingRestaurants sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
-10165928 0 Yes, set the proxy_max_temp_file_size
to zero, or some other reasonably small value. Another option (which might be a better choice) is to set the proxy_temp_path
to faster storage so that nginx can do a slightly better job of insulating the application from buggy or malicious hosts.
One way is to wait until the infinite loop shows up, then use jstack -l <pid>
to get a stack dump, and analyze that.
With a modicum of luck, this should suggest some lines of further inquiry.
-28945990 0 MVC 4: Create HTML textboxes dynamically with JQUERY and PartialViewResult. How to fill the model if the code is added dynamically?I am creating form input fields with JQUERY like
$('#students').live('change', function () { var value = $(this).val(); if (value) { $.ajax({ type: "GET", timeout: 10000, url: "@Url.Action(MVC.Company.ManageWorkReport.GetStudent())", data: { studentId: value }, cache: false, success: function (data) { if (data) { $("#students tbody").html(data); } }, error: function (xhr, status, error) { alert(xhr.responseText); } }); } return false; });
HTML code to insert data is
@using (Html.BeginDefaultForm(MVC.Company.ManageWorkReport.Create())) { <table class="table table-striped table-bordered bootstrap-datatable datatable" id="students"> <thead> <tr> <th>Ime in Priimek</th> <th>Vrsta</th> <th>Začetek dela</th> <th>Konec dela</th> <th>Enota</th> <th>Cena za enoto</th> <th>Količina</th> <th>Neto znesek</th> <th>Bruto znesek</th> <th></th> </tr> </thead> <tbody> <tr> <td colspan="11">Podatek še ne obstaja</td> </tr> </tbody> </table> @Html.SimpleSubmitAndCancelButton(Translations.Global.SAVE, Translations.Global.CANCEL) }
and C#
[HttpGet] public virtual PartialViewResult GetStudent(int studentId) { StudentsWorksReportsFormModel studentsWorksReportsFormModel = new StudentsWorksReportsFormModel(); ..... var view = PartialView("StudentWorkReportResult", studentsWorksReportsFormModel); return view;
}
Problem is that when I enter data in form and click SUBMIT button model is always empty. Why model is empty if I fill page with JQUERY and later enter data in text fields? How to fill the model also that I can insert data in DB.
-20837913 0The approach will not succeed, as you can search, but you cannot sort by a multivalued field. This pointed out in Sorting with Multivalued Field in Solr and written in Solr's Wiki
Sorting can be done on the "score" of the document, or on any multiValued="false" indexed="true" field provided that field is either non-tokenized (ie: has no Analyzer) or uses an Analyzer that only produces a single Term (ie: uses the KeywordTokenizer)
Update
About the alternatives, as you point out that you need to find similar documents for one given ID, why not create a second core with a schema like
<fields> <field name="doc_id" type="int" indexed="true" stored="true" /> <field name="similar_to_id" type="int" indexed="true" stored="true" /> <field name="similarity" type="string" indexed="true" stored="true" /> </fields> <types> <fieldType name="int" class="solr.TrieIntField"/> <fieldType name="string" class="solr.StrField" /> </types>
Then you could do a second query, after performing the actual search
-16130137 0q=similar_to_id=42&sort=similarity
Notes :
i think best approach is sort your query result and paging your result by Last code accessed and use this :
void NextPage()
{
Qr="select Top N from tbl where Code>LastCode order by Code asc";
//reading data
FirstCode=Drr["Code"];//for first record result
LastCode=Drr["Code"];//for last record result
}
void PreviousPage()
{
Qr="select Top N from tbl where Code < FirstCode order by Code asc";
//reading data
FirstCode=Drr["Code"];//for first record result
LastCode=Drr["Code"];//for last record result
}
Hope this Help
-23503635 0This statement, for instance,
String studAnswers[][] = answerArray[rowIndex][1].replace(" ", "S");
gives the compilation error
Type mismatch: cannot convert from String to String[][]
because
answerArray[rowIndex][1].replace(" ", "S");
returns a String
.
answerArray
is a 2D String
array.answerArray[rowIndex][1]
gets a element from the array which is a string answerArray[rowIndex][1].replace...
replaces a character in thatString
with another character, ending up as another String
(with the replaced character)You are trying to assign it to a String
array.
Also, you cannot use equals
on primitives (int
, char
...). You need to use ==
for comparison.
Here's another way. Of course this is just for int but the code could easily be altered for other datatypes.
AOMatrix.h:
#import <Cocoa/Cocoa.h> @interface AOMatrix : NSObject { @private int* matrix_; uint columnCount_; uint rowCount_; } - (id)initWithRows:(uint)rowCount Columns:(uint)columnCount; - (uint)rowCount; - (uint)columnCount; - (int)valueAtRow:(uint)rowIndex Column:(uint)columnIndex; - (void)setValue:(int)value atRow:(uint)rowIndex Column:(uint)columnIndex; @end
AOMatrix.m
#import "AOMatrix.h" #define INITIAL_MATRIX_VALUE 0 #define DEFAULT_ROW_COUNT 4 #define DEFAULT_COLUMN_COUNT 4 /**************************************************************************** * BIG NOTE: * Access values in the matrix_ by matrix_[rowIndex*columnCount+columnIndex] ****************************************************************************/ @implementation AOMatrix - (id)init { return [self initWithRows:DEFAULT_ROW_COUNT Columns:DEFAULT_COLUMN_COUNT]; } - (id)initWithRows:(uint)initRowCount Columns:(uint)initColumnCount { self = [super init]; if(self) { rowCount_ = initRowCount; columnCount_ = initColumnCount; matrix_ = malloc(sizeof(int)*rowCount_*columnCount_); uint i; for(i = 0; i < rowCount_*columnCount_; ++i) { matrix_[i] = INITIAL_MATRIX_VALUE; } // NSLog(@"matrix_ is %ux%u", rowCount_, columnCount_); // NSLog(@"matrix_[0] is at %p", &(matrix_[0])); // NSLog(@"matrix_[%u] is at %p", i-1, &(matrix_[i-1])); } return self; } - (void)dealloc { free(matrix_); [super dealloc]; } - (uint)rowCount { return rowCount_; } - (uint)columnCount { return columnCount_; } - (int)valueAtRow:(uint)rowIndex Column:(uint)columnIndex { // NSLog(@"matrix_[%u](%u,%u) is at %p with value %d", rowIndex*columnCount_+columnIndex, rowIndex, columnIndex, &(matrix_[rowIndex*columnCount_+columnIndex]), matrix_[rowIndex*columnCount+columnIndex]); return matrix_[rowIndex*columnCount_+columnIndex]; } - (void)setValue:(int)value atRow:(uint)rowIndex Column:(uint)columnIndex { matrix_[rowIndex*columnCount_+columnIndex] = value; } @end
-15692210 0 What's the difference between 301 and 302 in HTTP for Search engine I read this question and know What's the difference between 301 and 302 in HTTP but my question is What's the difference between 301 and 302 in HTTP for Search engine?
-17532229 1 What does "Cannot have more than on screen object" error mean?I'm working on a timer template for use in my games that I create. This is the code I have for a timer module (haven't put it into a class yet)
import time import math import pygame from livewires import games, color timer = 0 games.init(screen_width = 640, screen_height = 480, fps = 50) gamefont = pygame.font.Font(None, 30) timertext = gamefont.render('Timer: ' +str(timer), 1, [255,0,0]) screen.blit(timertext, [scoreXpos,20])
Eventually, I'm going to have a live timer which is why I use the the render and blit methods, but for now, I just have a static variable called timer set equal to 0. When I run this program however, I get an error that says "Cannot have more than on screen object." I'm really confused because I don't think I've ever seen this error before, and definitely don't know what it means, or how to fix it. If someone could help me understand what's happening, I would very much appreciate it. Also, the reason I've imported games and color from livewires, is to use it for another purpose later on in the code.
-4309378 0 Association Extensions no longer working in Rails 2.3.10I have an app that we just upgrade from 2.1.0 to 2.3.10. After the upgrade, an Association Extension that previously worked causes a failure. Here is the code on the model for the extension:
Class Classroom has_many :registrations has_many :students, :through => :registrations, :uniq => true do def in_group(a_group) if a_driver scoped(:conditions => ['registrations.group_id = ?', a_group]) else in_no_group end end def in_no_group scoped(:conditions => 'registrations.group_id is null') end end end
This is a simplified model of my actual issue, but basically I used to be able to do
classroom.students.in_group(honor_students)
This no longer works, with the following output:
classroom.students.in_group(honor_students) ActiveRecord::StatementInvalid: Mysql::Error: Unknown column 'registrations.group_id' in 'where clause': SELECT * FROM `students` WHERE (registrations.group_id = 1234)
When I just grab the list of students, the SQL has all the expected join syntax there thats missing from the above version:
SELECT DISTINCT `students`.* FROM `students` INNER JOIN `registrations` ON `students`.id = `registrations`.student_id WHERE ((`registrations`.classroom_id = 9876))
Why is the association extension missing all the join SQL?
-18094751 0Use e.Cancel = true;
to cancel back navigation.
Please correct me if I'm wrong. Your code is looking messed up. I think you last page/back page is mainpage.xaml
and in OK
you are again navigating to this page. If this is the case then there is no need of navigating again you can use below code.
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e) { MessageBoxResult res = MessageBox.Show("Are you sure that you want to exit?", "", MessageBoxButton.OKCancel); if (res != MessageBoxResult.OK) { e.Cancel = true; //when pressed cancel don't go back } }
-31244421 0 You have the following errors:
<p>
tag. Replace it with a <div>
tag.<input />
.Use this snippet:
<li> <div> <label for="request" id="officallabel">Purpose</label> <input type = "radio" name = "approvalbuttons" id = "approved" value = "Approved" /> <label for = "approved">Approved</label> <input type = "radio" name = "approvalbuttons" id = "denied" checked = "checked" value = "denied" /> <label for = "denied">Denied</label> </div> </li>
I guess you mean the category tree, And this should give you category tree. you can see the various filters being applied. (You can always do according to your need.)
<?php $rootCatId = Mage::app()->getStore()->getRootCategoryId(); $catlistHtml = getTreeCategories($rootCatId, false); echo $catlistHtml; function getTreeCategories($parentId, $isChild){ $allCats = Mage::getModel('catalog/category')->getCollection() ->addAttributeToSelect('*') ->addAttributeToFilter('is_active','1') ->addAttributeToFilter('include_in_menu','1') ->addAttributeToFilter('parent_id',array('eq' => $parentId)) ->addAttributeToSort('position', 'asc'); $class = ($isChild) ? "sub-cat-list" : "cat-list"; $html .= '<ul class="'.$class.'">'; foreach($allCats as $category) { $html .= '<li><span>'.$category->getName()."</span>"; $subcats = $category->getChildren(); if($subcats != ''){ $html .= getTreeCategories($category->getId(), true); } $html .= '</li>'; } $html .= '</ul>'; return $html; } ?>
EDIT: getting all parent category using an id/current category id..
$id = Mage::registry('current_category'); //or if you are retrieving other way around $category = Mage::getModel('catalog/category')->load($id); $categorynames = array(); foreach ($category->getParentCategories() as $parent) { $categorynames[] = $parent->getName(); } print_r($categorynames); //dumping category names for eg.
-14371345 1 Get field value within Flask-MongoAlchemy Document I've looked at documentation, and have searched Google extensively, and haven't found a solution to my problem.
This is my readRSS
function (note that 'get' is a method of Kenneth Reitz's requests module):
def readRSS(name, loc): linkList = [] linkTitles = list(ElementTree.fromstring(get(loc).content).iter('title')) linkLocs = list(ElementTree.fromstring(get(loc).content).iter('link')) for title, loc in zip(linkTitles, linkLocs): linkList.append((title.text, loc.text)) return {name: linkList}
This is one of my MongoAlchemy classes:
class Feed(db.Document): feedname = db.StringField(max_length=80) location = db.StringField(max_length=240) lastupdated = datetime.utcnow() def __dict__(self): return readRSS(self.feedname, self.location)
As you can see, I had to call the readRSS
function within a function of the class, so I could pass self
, because it's dependent on the fields feedname
and location
.
I want to know if there's a different way of doing this, so I can save the readRSS
return value to a field in the Feed
document. I've tried assigning the readRSS
function's return value to a variable within the function __dict__
-- that didn't work either.
I have the functionality working in my app, but I want to save the results to the Document to lessen the load on the server (the one I am getting my RSS feed from).
Is there a way of doing what I intend to do or am I going about this all wrong?
-11968366 0 cURL loop memory growthI have this problem with a loop using cURL where memory grows exponentially. In this example script, it starts using approximately 14MB of memory and ends with 28MB, with my original script and repeating to 1.000.000, memory grows to 800MB, which is bad.
PHP 5.4.5
cURL 7.21.0
for ($n = 1; $n <= 1000; $n++){ $apiCall = 'https://api.instagram.com/v1/users/' . $n . '?access_token=5600913.47c8437.358fc525ccb94a5cb33c7d1e246ef772'; $options = Array(CURLOPT_URL => $apiCall, CURLOPT_RETURNTRANSFER => true, CURLOPT_FRESH_CONNECT => true ); $ch = curl_init(); curl_setopt_array($ch, $options); $response = curl_exec($ch); curl_close($ch); unset($ch); }
-25353469 0 Two issues while trying to update wordpress user meta I have a form that is submitting data to a php script. Here is some of the code in the script.
foreach ($newuser_values as $key => $value) { echo $key; echo $value; switch ($key) { case "show_name": echo "1"; switch ($value) { case "first": $update_val = $current_user->user_firstname; break; case "first_initial": echo "HI"; $update_val = $current_user->user_firstname . " " . substr($current_user->user_lastname,0,0) . "."; break; case "first_last": $update_val = $current_user->user_firstname . " " . $current_user->user_lastname; break; default: echo "HELLO"; $update_val = $user_identity; } echo $update_val; update_user_meta($user_ID, $show_name, $update_val); echo get_user_meta($user_ID, $show_name); ... } }
$newuser_values is an array of form info. I get it like this:
$newuser_values = $_POST['edit-profile'];
I have two issues here. They can both be seen from the beginning of the script output (from echo statements). The script output is:
show_namefirst_intital1HELLOtestuser1Array
Problem 1: As you can see, the script prints a 1 which means that it is entering the case titled "show_name" of the switch on $key. However, it does not enter the case entitled "first_intial" of the switch on $value. Why is this?
Problem 2: Anyway the script enters the default case of the switch on $value and prints HELLO. Then, it prints the $update_val which is the testuser1. However, that value is not getting assigned to the user_meta because it is printing "Array". Why is this?
Thanks in advance. I apologize if these questions are simplistic. I am pretty new to wordpress and web development.
-18138512 0The correct thing to do is to set an execution policy on your machine (a one-time action), at which point you won't need to bypass it every time, and the Jenkins plugin should "just work". Are you unable to?
A reasonable starting setting would be RemoteSigned, which will allow you to execute local scripts fine but would still disallow scripts downloaded from the internet.
From an elevated PowerShell prompt, you would run:
Set-ExecutionPolicy RemoteSigned
See also: http://technet.microsoft.com/library/hh849812.aspx
UPDATE: excerpt from Help on applying policy and how it's supposed to behave:
If you set the execution policy for the local computer (the default) or the current user, the change is saved in the registry and remains effective until you change it again.
Of course, if your machine is on a Domain, then Group Policy could revert this.
-17133620 0 Setting timeout on blocking I/O ops with ServerSocketChannel doesn't work as expectedI'm working on a small group conversation server in Java and I'm currently hacking network code, but it seems like I cannot set right timeout on blocking I/O ops: chances are I've been bitten by some Java weirdness (or, simply, I misinterpret javadoc).
So, this is the pertinent code from ConversationServer
class (with all security checks and logging stripped for simplicity):
class ConversationServer { // ... public int setup() throws IOException { ServerSocketChannel server = ServerSocketChannel.open(); server.bind(new InetSocketAddress(port), Settings.MAX_NUMBER_OF_PLAYERS + 1); server.socket().setSoTimeout((int) Settings.AWAIT_PLAYERS_MS); int numberOfPlayers; for (numberOfPlayers = 0; numberOfPlayers < Settings.MAX_NUMBER_OF_PLAYERS; ++numberOfPlayers) { SocketChannel clientSocket; try { clientSocket = server.accept(); } catch (SocketTimeoutException timeout) { break; } clients.add(messageStreamFactory.create(clientSocket)); } return numberOfPlayers; } // ... }
The expected behaviour is to let connect Settings.MAX_NUMBER_OF_PLAYERS
clients at most, or terminate setup anyway after Settings.AWAIT_PLAYER_MS
milliseconds (currently, 30000L
).
What happens, is that if I connect Settings.MAX_NUMBER_OF_PLAYERS
clients, everything is fine (exit because of for
condition), but if I don't, the SocketTimeoutException
I'd expect is never thrown and the server hangs forever.
If I understand right, server.socket().setSoTimeout((int) Settings.AWAIT_PLAYERS_MS);
should be sufficient, but it doesn't give the expected behaviour.
So, can anyone spot the error here?
-37428778 0just try with adding this piece of code
<supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:resizeable="true" android:smallScreens="true" android:xlargeScreens="true" />
<!-- all normal size screens --> <screen android:screenDensity="ldpi" android:screenSize="normal" /> <screen android:screenDensity="mdpi" android:screenSize="normal" /> <screen android:screenDensity="hdpi" android:screenSize="normal" /> <screen android:screenDensity="xhdpi" android:screenSize="normal" />
This code involves everything even tablets refer this to exclude tablets
-33217783 0 Optimizing opencl kernelI am trying to optimize this kernel. The CPU version of this kernel is 4 times faster than the GPU version. I would expect that the GPU version would be faster. It might be that we have a lot of memory accesses and that is why we have a low performance. I am using an Intel HD 2500 and OpenCL 1.2.
The GPU kernel is:
__kernel void mykernel(__global unsigned char *inp1, __global unsigned char *inp2, __global unsigned char *inp3, __global unsigned char *inp4, __global unsigned char *outp1, __global unsigned char *outp2, __global unsigned char *outp3, __global unsigned char *outp4, __global unsigned char *lut, uint size ) { unsigned char x1, x2, x3, x4; unsigned char y1, y2, y3, y4; const int x = get_global_id(0); const int y = get_global_id(1); const int width = get_global_size(0); const uint id = y * width + x; x1 = inp1[id]; x2 = inp2[id]; x3 = inp3[id]; x4 = inp4[id]; y1 = (x1 & 0xff) | (x2>>2 & 0xaa) | (x3>>4 & 0x0d) | (x4>>6 & 0x02); y2 = (x1<<2 & 0xff) | (x2 & 0xaa) | (x3>>2 & 0x0d) | (x4>>4 & 0x02); y3 = (x1<<4 & 0xff) | (x2<<2 & 0xaa) | (x3 & 0x0d) | (x4>>2 & 0x02); y4 = (x1<<6 & 0xff) | (x2<<4 & 0xaa) | (x3<<2 & 0x0d) | (x4 & 0x02); // lookup table y1 = lut[y1]; y2 = lut[y2]; y3 = lut[y3]; y4 = lut[y4]; outp1[id] = (y1 & 0xc0) | ((y2 & 0xc0) >> 2) | ((y3 & 0xc0) >> 4) | ((y4 & 0xc0) >> 6); outp2[id] = ((y1 & 0x30) << 2) | (y2 & 0x30) | ((y3 & 0x30) >> 2) | ((y4 & 0x30) >> 4); outp3[id] = ((y1 & 0x0c) << 4) | ((y2 & 0x0c) << 2) | (y3 & 0x0c) | ((y4 & 0x0c) >> 2); outp4[id] = ((y1 & 0x03) << 6) | ((y2 & 0x03) << 4) | ((y3 & 0x03) << 2) | (y4 & 0x03); }
I use :
size_t localWorkSize[1], globalWorkSize[1]; localWorkSize[0] = 1; globalWorkSize[0] = X*Y; // X,Y define a data space of 15 - 20 MB
LocalWorkSize can vary between 1 - 256.
for LocalWorkSize = 1 I have CPU = 0.067Sec GPU = 0.20Sec for LocalWorkSize = 256 I have CPU = 0.067Sec GPU = 0.34Sec
Which is really weird. Can you give me some ideas why I get these strange numbers? and do you have any tips on how I can optimize this kernel?
My main looks like this:
int main(int argc, char** argv) { int err,err1,j,i; // error code returned from api calls and other clock_t start, end; // measuring performance variables cl_device_id device_id; // compute device id cl_context context; // compute context cl_command_queue commands; // compute command queue cl_program program_ms_naive; // compute program cl_kernel kernel_ms_naive; // compute kernel // ... dynamically allocate arrays // ... initialize arrays cl_uint dev_cnt = 0; clGetPlatformIDs(0, 0, &dev_cnt); cl_platform_id platform_ids[100]; clGetPlatformIDs(dev_cnt, platform_ids, NULL); // Connect to a compute device err = clGetDeviceIDs(platform_ids[0], CL_DEVICE_TYPE_GPU, 1, &device_id, NULL); // Create a compute context context = clCreateContext(0, 1, &device_id, NULL, NULL, &err); // Create a command queue commands = clCreateCommandQueue(context, device_id, 0, &err); // Create the compute programs from the source file program_ms_naive = clCreateProgramWithSource(context, 1, (const char **) &kernelSource_ms, NULL, &err); // Build the programs executable err = clBuildProgram(program_ms_naive, 0, NULL, NULL, NULL, NULL); // Create the compute kernel in the program we wish to run kernel_ms_naive = clCreateKernel(program_ms_naive, "ms_naive", &err); d_A1 = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, mem_size_cpy/4, h_A1, &err); d_A2 = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, mem_size_cpy/4, h_A2, &err); d_A3 = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, mem_size_cpy/4, h_A3, &err); d_A4 = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, mem_size_cpy/4, h_A4, &err); d_lut = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, 256, h_ltable, &err); d_B1 = clCreateBuffer(context, CL_MEM_WRITE_ONLY, mem_size_cpy/4, NULL, &err); d_B2 = clCreateBuffer(context, CL_MEM_WRITE_ONLY, mem_size_cpy/4, NULL, &err); d_B3 = clCreateBuffer(context, CL_MEM_WRITE_ONLY, mem_size_cpy/4, NULL, &err); d_B4 = clCreateBuffer(context, CL_MEM_WRITE_ONLY, mem_size_cpy/4, NULL, &err); int size = YCOLUMNS*XROWS/4; int size_b = size * 4; err = clSetKernelArg(kernel_ms_naive, 0, sizeof(cl_mem), (void *)&(d_A1)); err |= clSetKernelArg(kernel_ms_naive, 1, sizeof(cl_mem), (void *)&(d_A2)); err |= clSetKernelArg(kernel_ms_naive, 2, sizeof(cl_mem), (void *)&(d_A3)); err |= clSetKernelArg(kernel_ms_naive, 3, sizeof(cl_mem), (void *)&(d_A4)); err |= clSetKernelArg(kernel_ms_naive, 4, sizeof(cl_mem), (void *)&d_B1); err |= clSetKernelArg(kernel_ms_naive, 5, sizeof(cl_mem), (void *)&(d_B2)); err |= clSetKernelArg(kernel_ms_naive, 6, sizeof(cl_mem), (void *)&(d_B3)); err |= clSetKernelArg(kernel_ms_naive, 7, sizeof(cl_mem), (void *)&(d_B4)); err |= clSetKernelArg(kernel_ms_naive, 8, sizeof(cl_mem), (void *)&d_lut); //__global err |= clSetKernelArg(kernel_ms_naive, 9, sizeof(cl_uint), (void *)&size_b); size_t localWorkSize[1], globalWorkSize[1]; localWorkSize[0] = 256; globalWorkSize[0] = XROWS*YCOLUMNS; start = clock(); for (i=0;i< EXECUTION_TIMES;i++) { err1 = clEnqueueNDRangeKernel(commands, kernel_ms_naive, 1, NULL, globalWorkSize, localWorkSize, 0, NULL, NULL); err = clFinish(commands); } end = clock(); return 0; }
-37501223 0 I can not print correctly mysql to xml I do not know where I went wrong. I want to this.
<mekan> <Soguk Icecekler> <yemek> <urunismi>Kola</urunismi> <fiyat>2</fiyat> <efiyat>0</efiyat> </yemek> <yemek> <urunismi>Kola</urunismi> <fiyat>2</fiyat> <efiyat>0</efiyat> </yemek> </Soguk Icecekler> <Sicak Icecekler> <yemek> <urunismi>cay</urunismi> <fiyat>2</fiyat> <efiyat>0</efiyat> </yemek> <yemek> <urunismi>kahve</urunismi> <fiyat>2</fiyat> <efiyat>0</efiyat> </yemek> </Sicak Icecekler> </mekan>
What is my mistake?
$xml = new SimpleXMLElement('<mekan/>'); while($data = mysql_fetch_array($resultID)) { $kategori=$xml->addChild('Kategori'); $kategori->addChild('kategori_adi', $data["kategoriadi"]); $kategori->addChild('urunismi', $data["urunadi"]); $kategori->addChild('fiyat', $data["fiyat"]); $kategori->addChild('efiyat', $data["eskifiyat"]); } Header('Content-type: text/xml'); echo $xml->asXML();
XML is read, but I get mistaken result.
-24100405 0 How to dynamically configure DataSource in Spring based on application mode?We have an application which runs both as standalone Spring application and as Webservice in Weblogic. The standalone application creates the database DataSource as show below by reading the properties file.
However for the Webservices part, I'd like to use the DataSource configured in Weblogic via JNDI. I'm not sure how to make that dynamic DataSource switch based on the mode my application runs. Any help here please?
@Configuration @PropertySources(value = {@PropertySource("classpath:app.properties")}) public class DAOConfig { @Autowired Environment env; @Bean(destroyMethod = "close") public DataSource dataSource() { return new DataSources.Builder() .host(env.getProperty("dbhost")) .port(env.getProperty("dbport", Integer.class)) .service(env.getProperty("dbservice")) .user(env.getProperty("dbuser")) .pwd(env.getProperty("dbpwd")) .initialConnectionsInPool(env.getProperty("dbinitialConnectionsInPool", Integer.class)) .maxConnectionsInPool(env.getProperty("dbmaxConnectionsInPool", Integer.class)) .build(); } }
-32739558 0 Media Foundation EVR no video displaying I've been trying in vain to come up with a no frills example of displaying video using Microsoft's Media Foundation Enhanced Video Renderer (EVR). I'm testing on Windows 7 with Visual Studio 2013.
I'm pretty sure I've got the media types configured correctly as I can export and save the buffer from the IMFSample in my read loop to a bitmap. I can also get the video to render IF I get MF to automatically generate the topology but in this case I need to wire up the source reader and sink writer manually so I can get access to the different parts of the pipeline.
I have used mftrace to see if I can spot anything different between the automatically generated topology and the manually wired up example but nothing obvious jumps out.
The code is below (full sample project at https://github.com/sipsorcery/mediafoundationsamples/tree/master/MFVideoEVR).
Is there a step I've missed to get the IMFSample from the SinkWriter to display on the video window? I've been looking at a few examples that go deeper into the DirectX pipeline but should that be necessary or is the EVR meant to abstract those mechanics aways?
#include <stdio.h> #include <tchar.h> #include <evr.h> #include <mfapi.h> #include <mfplay.h> #include <mfreadwrite.h> #include <mferror.h> #include "..\Common\MFUtility.h" #include <windows.h> #include <windowsx.h> #pragma comment(lib, "mf.lib") #pragma comment(lib, "evr.lib") #pragma comment(lib, "mfplat.lib") #pragma comment(lib, "mfplay.lib") #pragma comment(lib, "mfreadwrite.lib") #pragma comment(lib, "mfuuid.lib") #pragma comment(lib, "Strmiids") #pragma comment(lib, "wmcodecdspuuid.lib") #define CHECK_HR(hr, msg) if (hr != S_OK) { printf(msg); printf("Error: %.2X.\n", hr); goto done; } void InitializeWindow(); // Constants const WCHAR CLASS_NAME[] = L"MFVideoEVR Window Class"; const WCHAR WINDOW_NAME[] = L"MFVideoEVR"; // Globals. HWND _hwnd; using namespace System::Threading::Tasks; int main() { CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE); MFStartup(MF_VERSION); IMFMediaSource *videoSource = NULL; UINT32 videoDeviceCount = 0; IMFAttributes *videoConfig = NULL; IMFActivate **videoDevices = NULL; IMFSourceReader *videoReader = NULL; WCHAR *webcamFriendlyName; IMFMediaType *videoSourceOutputType = NULL, *pvideoSourceModType = NULL, *pSrcOutMediaType = NULL; IMFSourceResolver *pSourceResolver = NULL; IUnknown* uSource = NULL; IMFMediaSource *mediaFileSource = NULL; IMFAttributes *pVideoReaderAttributes = NULL; IMFMediaType *pVideoOutType = NULL; MF_OBJECT_TYPE ObjectType = MF_OBJECT_INVALID; IMFMediaSink *pVideoSink = NULL; IMFStreamSink *pStreamSink = NULL; IMFMediaTypeHandler *pMediaTypeHandler = NULL; IMFMediaType *pMediaType = NULL; IMFMediaType *pSinkMediaType = NULL; IMFSinkWriter *pSinkWriter = NULL; IMFVideoRenderer *pVideoRenderer = NULL; IMFVideoPresenter *pVideoPresenter = nullptr; IMFVideoDisplayControl *pVideoDisplayControl = nullptr; IMFGetService *pService = nullptr; IMFActivate* pActive = NULL; MFVideoNormalizedRect nrcDest = { 0.5f, 0.5f, 1.0f, 1.0f }; IMFPresentationTimeSource *pSystemTimeSource = nullptr; IMFMediaType *sinkPreferredType = nullptr; IMFPresentationClock *pClock = NULL; IMFPresentationTimeSource *pTimeSource = NULL; CHECK_HR(MFTRegisterLocalByCLSID( __uuidof(CColorConvertDMO), MFT_CATEGORY_VIDEO_PROCESSOR, L"", MFT_ENUM_FLAG_SYNCMFT, 0, NULL, 0, NULL ), "Error registering colour converter DSP.\n"); Task::Factory->StartNew(gcnew Action(InitializeWindow)); Sleep(1000); if (_hwnd == nullptr) { printf("Failed to initialise video window.\n"); goto done; } // Set up the reader for the file. CHECK_HR(MFCreateSourceResolver(&pSourceResolver), "MFCreateSourceResolver failed.\n"); CHECK_HR(pSourceResolver->CreateObjectFromURL( L"..\\..\\MediaFiles\\big_buck_bunny.mp4", // URL of the source. MF_RESOLUTION_MEDIASOURCE, // Create a source object. NULL, // Optional property store. &ObjectType, // Receives the created object type. &uSource // Receives a pointer to the media source. ), "Failed to create media source resolver for file.\n"); CHECK_HR(uSource->QueryInterface(IID_PPV_ARGS(&mediaFileSource)), "Failed to create media file source.\n"); CHECK_HR(MFCreateAttributes(&pVideoReaderAttributes, 2), "Failed to create attributes object for video reader.\n"); CHECK_HR(pVideoReaderAttributes->SetGUID(MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE, MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID), "Failed to set dev source attribute type for reader config.\n"); CHECK_HR(pVideoReaderAttributes->SetUINT32(MF_SOURCE_READER_ENABLE_VIDEO_PROCESSING, 1), "Failed to set enable video processing attribute type for reader config.\n"); CHECK_HR(MFCreateSourceReaderFromMediaSource(mediaFileSource, pVideoReaderAttributes, &videoReader), "Error creating media source reader.\n"); CHECK_HR(videoReader->GetCurrentMediaType((DWORD)MF_SOURCE_READER_FIRST_VIDEO_STREAM, &videoSourceOutputType), "Error retrieving current media type from first video stream.\n"); Console::WriteLine("Default output media type for source reader:"); Console::WriteLine(GetMediaTypeDescription(videoSourceOutputType)); Console::WriteLine(); // Set the video output type on the source reader. CHECK_HR(MFCreateMediaType(&pvideoSourceModType), "Failed to create video output media type.\n"); CHECK_HR(pvideoSourceModType->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video), "Failed to set video output media major type.\n"); CHECK_HR(pvideoSourceModType->SetGUID(MF_MT_SUBTYPE, MFVideoFormat_RGB32), "Failed to set video sub-type attribute on EVR input media type.\n"); CHECK_HR(pvideoSourceModType->SetUINT32(MF_MT_INTERLACE_MODE, MFVideoInterlace_Progressive), "Failed to set interlace mode attribute on EVR input media type.\n"); CHECK_HR(pvideoSourceModType->SetUINT32(MF_MT_ALL_SAMPLES_INDEPENDENT, TRUE), "Failed to set independent samples attribute on EVR input media type.\n"); CHECK_HR(MFSetAttributeRatio(pvideoSourceModType, MF_MT_PIXEL_ASPECT_RATIO, 1, 1), "Failed to set pixel aspect ratio attribute on EVR input media type.\n"); CHECK_HR(CopyAttribute(videoSourceOutputType, pvideoSourceModType, MF_MT_FRAME_SIZE), "Failed to copy video frame size attribute from input file to output sink.\n"); CHECK_HR(CopyAttribute(videoSourceOutputType, pvideoSourceModType, MF_MT_FRAME_RATE), "Failed to copy video frame rate attribute from input file to output sink.\n"); CHECK_HR(videoReader->SetCurrentMediaType((DWORD)MF_SOURCE_READER_FIRST_VIDEO_STREAM, NULL, pvideoSourceModType), "Failed to set media type on source reader.\n"); Console::WriteLine("Output media type set on source reader:"); Console::WriteLine(GetMediaTypeDescription(pvideoSourceModType)); Console::WriteLine(); // Create EVR sink . //CHECK_HR(MFCreateVideoRenderer(__uuidof(IMFMediaSink), (void**)&pVideoSink), "Failed to create video sink.\n"); CHECK_HR(MFCreateVideoRendererActivate(_hwnd, &pActive), "Failed to created video rendered activation context.\n"); CHECK_HR(pActive->ActivateObject(IID_IMFMediaSink, (void**)&pVideoSink), "Failed to activate IMFMediaSink interface on video sink.\n"); // Initialize the renderer before doing anything else including querying for other interfaces (https://msdn.microsoft.com/en-us/library/windows/desktop/ms704667(v=vs.85).aspx). CHECK_HR(pVideoSink->QueryInterface(__uuidof(IMFVideoRenderer), (void**)&pVideoRenderer), "Failed to get video Renderer interface from EVR media sink.\n"); CHECK_HR(pVideoRenderer->InitializeRenderer(NULL, NULL), "Failed to initialise the video renderer.\n"); CHECK_HR(pVideoSink->QueryInterface(__uuidof(IMFGetService), (void**)&pService), "Failed to get service interface from EVR media sink.\n"); CHECK_HR(pService->GetService(MR_VIDEO_RENDER_SERVICE, __uuidof(IMFVideoDisplayControl), (void**)&pVideoDisplayControl), "Failed to get video display control interface from service interface.\n"); CHECK_HR(pVideoSink->GetStreamSinkByIndex(0, &pStreamSink), "Failed to get video renderer stream by index.\n"); CHECK_HR(pStreamSink->GetMediaTypeHandler(&pMediaTypeHandler), "Failed to get media type handler.\n"); // Set the video output type on the source reader. CHECK_HR(MFCreateMediaType(&pVideoOutType), "Failed to create video output media type.\n"); CHECK_HR(pVideoOutType->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video), "Failed to set video output media major type.\n"); CHECK_HR(pVideoOutType->SetGUID(MF_MT_SUBTYPE, MFVideoFormat_RGB32), "Failed to set video sub-type attribute on EVR input media type.\n"); CHECK_HR(pVideoOutType->SetUINT32(MF_MT_INTERLACE_MODE, MFVideoInterlace_Progressive), "Failed to set interlace mode attribute on EVR input media type.\n"); CHECK_HR(pVideoOutType->SetUINT32(MF_MT_ALL_SAMPLES_INDEPENDENT, TRUE), "Failed to set independent samples attribute on EVR input media type.\n"); CHECK_HR(MFSetAttributeRatio(pVideoOutType, MF_MT_PIXEL_ASPECT_RATIO, 1, 1), "Failed to set pixel aspect ratio attribute on EVR input media type.\n"); CHECK_HR(CopyAttribute(videoSourceOutputType, pVideoOutType, MF_MT_FRAME_SIZE), "Failed to copy video frame size attribute from input file to output sink.\n"); CHECK_HR(CopyAttribute(videoSourceOutputType, pVideoOutType, MF_MT_FRAME_RATE), "Failed to copy video frame rate attribute from input file to output sink.\n"); //CHECK_HR(pMediaTypeHandler->GetMediaTypeByIndex(0, &pSinkMediaType), "Failed to get sink media type.\n"); CHECK_HR(pMediaTypeHandler->SetCurrentMediaType(pVideoOutType), "Failed to set current media type.\n"); Console::WriteLine("Input media type set on EVR:"); Console::WriteLine(GetMediaTypeDescription(pVideoOutType)); Console::WriteLine(); CHECK_HR(MFCreatePresentationClock(&pClock), "Failed to create presentation clock.\n"); CHECK_HR(MFCreateSystemTimeSource(&pTimeSource), "Failed to create system time source.\n"); CHECK_HR(pClock->SetTimeSource(pTimeSource), "Failed to set time source.\n"); //CHECK_HR(pClock->Start(0), "Error starting presentation clock.\n"); CHECK_HR(pVideoSink->SetPresentationClock(pClock), "Failed to set presentation clock on video sink.\n"); Console::WriteLine("Press any key to start video sampling..."); Console::ReadLine(); IMFSample *videoSample = NULL; DWORD streamIndex, flags; LONGLONG llTimeStamp; while (true) { CHECK_HR(videoReader->ReadSample( MF_SOURCE_READER_FIRST_VIDEO_STREAM, 0, // Flags. &streamIndex, // Receives the actual stream index. &flags, // Receives status flags. &llTimeStamp, // Receives the time stamp. &videoSample // Receives the sample or NULL. ), "Error reading video sample."); if (flags & MF_SOURCE_READERF_ENDOFSTREAM) { printf("End of stream.\n"); break; } if (flags & MF_SOURCE_READERF_STREAMTICK) { printf("Stream tick.\n"); } if (!videoSample) { printf("Null video sample.\n"); } else { printf("Attempting to write sample to stream sink.\n"); CHECK_HR(videoSample->SetSampleTime(llTimeStamp), "Error setting the video sample time.\n"); //CHECK_HR(videoSample->SetSampleDuration(41000000), "Error setting the video sample duration.\n"); CHECK_HR(pStreamSink->ProcessSample(videoSample), "Streamsink process sample failed.\n"); } SafeRelease(&videoSample); } done: printf("finished.\n"); getchar(); return 0; } LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { return DefWindowProc(hwnd, uMsg, wParam, lParam); } void InitializeWindow() { WNDCLASS wc = { 0 }; wc.lpfnWndProc = WindowProc; wc.hInstance = GetModuleHandle(NULL); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.lpszClassName = CLASS_NAME; if (RegisterClass(&wc)) { _hwnd = CreateWindow( CLASS_NAME, WINDOW_NAME, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 640, 480, NULL, NULL, GetModuleHandle(NULL), NULL ); if (_hwnd) { ShowWindow(_hwnd, SW_SHOWDEFAULT); MSG msg = { 0 }; while (true) { if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); } else { Sleep(1); } } } } }
-15481263 0 The short answer is no, there isn't. You always should write the access specifier in front of your field/method.
public int var1; public char var2;
Note that private
is the default specifier. It is a question of design, but I would always explicitly designate the modifier. (And even if it is just for the consistent indentation!)
Read more on Accessibility Levels (C#) at msdn.
-34390276 0Just do it, like this:
Update TableTest SET COL3 = newdata Where Col1= D11
-9401392 0 You can add panels to a form at runtime the same way the designer does - construct the Panel, and add it to the form (via this.Controls.Add(thePanel);
).
The easiest way to see the appropriate code is to add a panel to the form using the designer, then open up the "YourForm.designer.cs" file. The designer just generates the required code for you - but you can see the exact code required to duplicate what the designer would create.
As for the layout, I'd recommend watching the Layout Techniques for Windows Forms Developers video. It may give you some good clues as to the various options available for layout. There is nothing exactly like Java's GridLayout, though there are some open source projects that attempt to duplicate this functionality.
-22980802 0SendMailAsync and all methods that use the Task Parallel Library execute in a threadpool thread, although you can make them use a new thread if you need to. This means that instead of creating a new thread, an available thread is picked from the pool and returned there when the method finishes.
The number of threads in the pool varies with the version of .NET and the OS, the number of cores etc. It can go from 25 threads per core in .NET 4 to hundreds or per core in .NET 4.5 on a server OS.
An additional optimization for IO-bound (disk, network) tasks is that instead of using a thread, an IO completion port is used. Roughly, this is a callback from the IO stack when an IO operation (disk or network) finishes. This way the framework doesn't waste a thread waiting for an IO call to finish.
When you start an asynchronous network operation, .NET make the network call, registers for the callback and releases the threadpool thread. When the call finishes, the framework gets notified and schedules the rest of the asynchronous method (essentially what comes after the await
or ContinueWith
) on a threadpool thread.
Submitting a 100 asynchronous operations doesn't mean that 100 threads will be used nor that all 100 of them will execute in parallel. Rather, the framework will take into account the number of cores, the load and the number of available threads to execute as many of them as possible, without hurting overall performance. Waiting on the network calls may not even use a thread at all, while processing the messages themselves will execute on threadpool threads
-20908161 0 Special character in concatenated sql script causing errorI save stored procedure code as files and then execute them in several different databases. I am trying to concatenate multiple files (100's). Every utility I use seems to create some special characters in the file that cause an error when i execute the script in sql.
Currently, i used
type *.sql > script.sql
in DOS. I am getting the following error in many places.
Msg 102, Level 15, State 1, Line 1 Incorrect syntax near ''.
How can I find this character so I can do a find/replace? Thanks!
-36973295 0 Balloon synopsis - jQuery plugin - which file specifically?I have downloaded what seems to be a handy tool called Balloon Synopsis (homepage: http://schlegel.github.io/balloon/index.html GitHub: https://github.com/balloonLD/balloon-synopsis) and ran the Gruntfile. All there is however is bunch of .js files (/src/js) and I am not sure which one (or several) are the jQuery plugin. Alternatively, have I been misled completely? There is no documentation or how-to whatsoever, so any help or advice would be great :) Thanks!
-24777375 0This is not a cross-domain issue. You are mixing the dynamic proxy and proxyless approaches. $.hubConnection
and createHubProxy
are from the proxyless API, but .client
is available only with dynamic proxies. Check the documentation about both and you will be able to fix it (I don't go further with code because I do not know which approach you really want to use).
You can also do it in pure xaml, just use trigger action:
<Button> <Button.Triggers> <EventTrigger RoutedEvent="PreviewMouseDown"> <BeginStoryboard Storyboard="{DynamicResource BotRotation}"/> </EventTrigger> </Button.Triggers> </Button>
-5605025 0 The system NAND flash for the emulator has run out of space. Your host system D: is not the issue, but for some reason the system.img file that represents a NAND flash for the emulator is full. You can try creating a new emulator, or doing a factory default reset in the emulator to clean it up. To do this, either issue a Factory Data Reset inside Android under Settings -> Privacy, or start the emulator from the command-line:
android list avd emulator -avd My_Avd_Name -wipe-data
The first command list all Android Virtual Devices. You need the name for the second command. The emulator should not already be running. A third option would be to delete the disk images located under your Windows profile. Under your profiles, it's .android/avd/My_Avd_Name.avd
You should only need to delete userdata-qemu.img
and maybe cache.img
. You can try deleting other image files if necessarily, but note, sdcard.img
won't be re-created automatically. You need to run mksdcard
from the command-line.
If you could change your student class properties to match the Xml element names and/or decorate the properties with attributes indicating what XML value goes to what class property, then you could use the .Net to deserialise the XML into a List Students in one line.
Then just persist to the DB as you normally would.
-39297430 0you should use a table
as grid
Try this
<table> <tr> <?php $numbers_per_row = 5; $rowi= 0; $numbers_limit = 25; for($b=1; $b<=$numbers_limit ; $b++) { echo '<td><a href="index.php?page='.$b.'">'.$b.'</td>'; if($rowi<=$numbers_per_row) { $rowi++; } else { echo '</tr><tr style="margin-top:10px;">'; /* <-- change it ^ to what you want */ /* Reset counter */ $rowi = 0; } } ?> </table>
-6971446 0 distribution provisioning and code signing issues I just generated a ad hoc distribution provisioning. I dragged this into xcode and then set my ad hoc build to be iphone distribution. Followed every single step in this tutorial. The issue is that when I follow this instruction to see my list of devices it doesn't even have a ProvisionedDevices key in the embedded.mobileprovison. The key goes something like this:
<key>Entitlements</key> <dict> <key>application-identifier</key> <string>8CH38P5X6X.*</string> <key>get-task-allow</key> <false/> <key>keychain-access-groups</key> <array> <string>8CH38P5X6X.*</string> </array> </dict> <key>ExpirationDate</key> <date>2012-03-17T00:31:45Z</date> <key>Name</key> <string>Fever</string> //this is not my app name, how come it's here <key>TimeToLive</key> <integer>291</integer> <key>UUID</key> <string>101F3A06-B33C-411A-8173-A4CEAFF5E673</string> <key>Version</key> <string>101F3A06-B33C-411A-8173-A4CEAFF5E673</string> <key>Version</key> <integer>1</integer> </dict> </plist>
The weirdest issue is that it has an app name in the , which is not my app name!! How is this even possible? Something is messed up..
This 8CH38P5X6X is also the App ID of my other app called Fever... how.. how is this possible. I've code signed adhoc using iphone distribution and it clearly says this:
UPDATE:
I removed/clear the provisioning profile that I have for the Fever app, restart xcode, and tried to build the archive again and it works! Anyone ever have issues with multiple provisioning profile on your xcode being mixed up like this?
-32798837 0#app/models/review.rb class Review < ActiveRecord::Base validates :movie_id, uniqueness: { scope: :user_id, message: "You've reviewed this movie!" } end
This is considering your review
model belongs_to :movie
You could also use an ActiveRecord callback:
#app/models/review.rb class Review < ActiveRecord::Base before_create :has_review? belongs_to :user, inverse_of: :reviews belongs_to :movie def has_review? return if Review.exists?(user: user, movie_id: movie_id) end end #app/models/user.rb class User < ActiveRecord::Base has_many :reviews, inverse_of: :user end
Is there any way to improve the lookup in my has_reviewed? method?
def has_reviewed? redirect_to album_reviews_path, notice: "You've already written a review for this album." if current_user.reviews.exists?(movie: @movie) end
-21572016 1 List connected Bluetooth LE devices to Windows 8 with python I want to be able to read out information about connected Bluetooth Low Energy HID devices in Windows 8. My main application uses Qt, but I thought it could be much easier to get help from a Python script. Since Windows 8.1 supports Bluetooth Low Energy natively, I connect my mouse to it and tried using the pywinusb package, but it doesn't seem to be able to read out this wirelessly connected device, only connected HID devices.
How can I read out information about my BLE device with Python?
-39388527 0All answers are creating NEW arrays before projecting the final result : (filter
and map
creates a new array each) so basically it's creating twice.
Another approach is only to yield expected values :
Using iterator functions
function* foo(g) { for (let i = 0; i < g.length; i++) { if (g[i]['images'] && g[i]["images"].length) yield g[i]['images'][0]["name"]; } } var iterator = foo(data1) ; var result = iterator.next(); while (!result.done) { console.log(result.value) result = iterator.next(); }
This will not create any additional array and only return the expected values !
However if you must return an array , rather than to do something with the actual values , then use other solutions suggested here.
https://jsfiddle.net/remenyLx/7/
-27845377 0 Issues connecting to mySql database on target machineI'm using hostgator
for hosting my website and I have added my IP
address as remote access host. And then I connected with mySql workbench and tested the connection and I get the message that all parameters are correct. On hostgator, I added myself as a the admin user granting myself all privileges. Now I want to manipulate the database via a PHP script using PDO but this is the error I'm getting in my browser when I try to run the PHP file:
Connection failed: SQLSTATE[28000] [1045] Access denied for user 'user'@'host' (using password: YES)
On mySQL workbench Users and Privileges tab, I get this:
"The account you are currently using does not have sufficient privileges to make changes to MySQL users and privileges.
"
I'm not sure whats going wrong here and I'm quiet new to this. Can somebody please help?
edit:
php code below:
<?php ini_set('display_errors',1); error_reporting(E_ALL); //this block tries to connect to the database //if there's an error connecting, the code under catch will //and the program will end $host="host"; $port="3306"; $user="xxx"; $password="xxx"; $dbname="database"; try { $conn = new PDO("mysql:host=$host;dbname=$dbname;", $user, $password); // set the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo "Connected successfully"; } catch(PDOException $e) { echo "Connection failed: " . $e->getMessage(); } //$con->close(); ?>
-20081748 0 Drawing layers with jcanvas: performance optimization )
I have a small web-application which uses jquery and jcanvas (http://calebevans.me/projects/jcanvas/) to print some shapes onto a canvas.
It's basically a map. The user can zoom into it and drag it around and whenever he does so everything has to be drawn again.
As you may see in the code below I remove and recreate layers pretty often (whenever the user drags the map, zooms or resizes his window). I need the layers to handle hover- and click-events. My question is whether there is a big performance impact of this way to handle events in comparison to other solutions. If this is the case, how could I optimize my performance?
var posX = 0, posY = 0; var zoom = 100; var points = []; //array of up to 1000 points retrieved by ajax function draw(){ $("canvas").removeLayers(); $("canvas").clearCanvas(); var xp, yp, ra; var name; $.each(points, function(index) { xp = (this["x"]-posX)/zoom; yp = (this["y"]-posY)/zoom; ra = 1000/zoom; $("#map").drawArc({ layer:true, fillStyle: "black", x: xp, y: yp, radius: ra, mouseover: function(layer) { $(this).animateLayer(layer, { fillStyle: "#c33", scale: 1.0 },200); }, mouseout: function(layer) { $(this).animateLayer(layer, { fillStyle: "black", scale: 1.0 },200); }, mouseup: function(layer){ context(index,layer.x,layer.y); } }); }); }
Thank you for your time :-)
-3991107 0You should not be using HTML Entities in XML. Using normal UTF-8 characters should be fine.
The occurrence of Osnabrück
means that at some point, most likely, the city name is processed as ISO-8859-1 instead of UTF-8. It is not htmlentities()
's fault. You need to find that point and fix it.
You are just passing that function a string. For it to make any sense of that, it would have to parse the string to split up the key/value pairs. I'm not saying it's the best approach, but if you want to do that, you should use parse_str()
.
Note that this is not by any means a language feature of PHP, but I am just providing a means to handle what you've shown.
-9716871 0Try this
return Fluently.Configure().Database(MsSqlConfiguration.MsSql2008 .ConnectionString(@"Data Source=CHRIS-PC\\SQLEXPRESS;Initial Catalog=TestDB;User ID=test")) .Mappings(m => m.AutoMappings.Add(model)) .ExposeConfiguration(BuildSchema) .BuildSessionFactory();
or use this let mymodel be a sample model
Fluently.Configure() .Database(MsSqlConfiguration.MsSql2008 .ConnectionString(ConfigurationManager.ConnectionStrings["CHRIS-PC\\SQLEXPRESS"].ConnectionString)) .Mappings(m => m.FluentMappings.AddFromAssemblyOf<mymodel>().Add<UsersMap>()) .ExposeConfiguration(cfg => { new SchemaExport(cfg).Execute(false, true, false); // new SchemaUpdate(cfg).Execute(true, true); }).BuildSessionFactory();
-16583017 0 For formatting options, see this
Dim v1 as Double = Val(txtD.Text) / Val(txtC.Text) * Val(txtF.Text) / Val(txtE.Text) txtA.text = v1.ToString("N2");
-11855579 0 STL containers in VS Debug are notoriously slow. Game programmers forums are rife with complaints about this. Often people choose alternative implementations. However, from what I've read, you can get a performance boost up front by disabling iterator debugging/checking:
#define _HAS_ITERATOR_DEBUGGING 0 #define _SECURE_SCL 0
Other things that can affect debug performance are excessive calls to new and delete. Memory pools can help with that. You haven't provided details for PropMsg::add_v_var_repeated()
or PropMsg::~PropMsg()
, so I can't comment. But I assume there's a vector or other STL container inside that class?
I used the following code to change the background of Progress Dialog. But the color changes on the outside frame too as below. I want to change only inside the dialog.
<style name="StyledDialog" parent="@android:style/Theme.Panel"> <item name="android:background">#083044</item> </style>
As per the answer given at this question Change background of ProgressDialog
<style name="StyledDialog" parent="@android:style/Theme.Dialog"> <item name="android:alertDialogStyle">@style/CustomAlertDialogStyle</item> <item name="android:textColorPrimary">#000000</item> </style> <style name="CustomAlertDialogStyle"> <item name="android:bottomBright">@color/background</item> <item name="android:bottomDark">@color/background</item> <item name="android:bottomMedium">@color/background</item> <item name="android:centerBright">@color/background</item> <item name="android:centerDark">@color/background</item> <item name="android:centerMedium">@color/background</item> <item name="android:fullBright">@color/background</item> <item name="android:fullDark">@color/background</item> <item name="android:topBright">@color/background</item> <item name="android:topDark">@color/background</item> </style>
This code gives background color perfect. But since, dialog color and activity's background color is same. It appears like transparent with no border. I want some border as before.
This is a test engine application with 5 papers set by me..as 5 php pages
Flow of the application
Login.html
check.php // to check whether credentials r right
if correct then
main.php //user clicks on "take test" in this page which displays him 1 of the 5 papers...
but once i am logged in i can just change the url to the url of the test paper i want..the paper names r 1.php 2.php....
how do i stop this...??
if(!isset($_SESSION['page'])//Tp continue; //Tp else { header('Location:login.php'); exit; } //Tp $_SESSION['page']=$_SERVER['SCRIPT_NAME'];//tp
is this correct...as i said there are 5 pages....
in eac page i have this code....
i check whether the Session variable is set....if it is set...it means it already has visited the page.....but this code doesnt work...did i use the variable _SESSION['page'] before declaring it???
-40054572 0When you avoid of using the with_message
method on the matcher then it uses default message.
To make your test works you should override the matcher's default message:
it { should validate_uniqueness_of(:name).with_message("has already been taken") }
-13240740 0 Microsoft's documentation is of limited use, once you move off Windows. Their discussion of the ODBC APIs is fine -- but anything about Visual Studio or other Windows-specific components should generally be ignored.
iODBC.org can provide some pointers -- especially if you look into the source for iODBC Demo.app and/or iODBC Test.command, which ship with the free and open source iODBC SDK.
You may also benefit from developing and testing with a commercially-supported ODBC driver, such as my employer's offering.
-2206099 0I've found a solution.
I can apply system theme for that single element in the resource, something like this:
<ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="/PresentationFramework.Aero;V3.0.0.0;31bf3856ad364e35;component\themes/aero.normalcolor.xaml" /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary>
-28839744 1 Convert XML to string to find length I am trying to find the length of an XML document and would like to know how to convert an XML document into a string so that I can find its length.
-4804176 0You could use a not exists
clause to ensure the combination has not been voted on:
select a.itemId , b.itemId from Items a join Items b on a.ItemId < b.ItemId where not exists ( select * from Vote where userId = 42 and ((betterItemId = a.ItemId and worseItemId = b.ItemId) or (worseItemId = a.ItemId and betterItemId = b.ItemId)) ) order by rand() limit 2
-12284347 0 In the CMSButton you set base.BackColor, but in CMSLabel you set this.BackColor, which has no code in the setter.
-19137295 0Strictly by the standard type-punning expect in narrow circumstances is undefined behavior but in practice many compilers support it for example gcc manual points here for type-punning and under -fstrict-aliasing section is says:
The practice of reading from a different union member than the one most recently written to (called “type-punning”) is common. Even with -fstrict-aliasing, type-punning is allowed, provided the memory is accessed through the union type.
I would recommend reading Understanding Strict Aliasing if you plan on using type-punning a lot.
y.b
has the value b
since all the elements of the union share memory and you initialized y
with 100
which in ASCII is b
. This is the same reason why the other fields of x
change when you modify one including the case of strcpy
and depending on your compiler this may be undefined or well defined(in the case of gcc it is defined).
For completeness sake the C++ draft standard section 9.5
Unions paragraph 1 says(emphasis mine):
-29624392 0In a union, at most one of the non-static data members can be active at any time, that is, the value of at most one of the non-static data members can be stored in a union at any time. [ Note: One special guarantee is made in order to simplify the use of unions: If a standard-layout union contains several standard-layout structs that share a common initial sequence (9.2), and if an object of this standard-layout union type contains one of the standard-layout structs, it is permitted to inspect the common initial sequence of any of standard-layout struct members; see 9.2. —end note ] The size of a union is sufficient to contain the largest of its non-static data members. Each non-static data member is allocated as if it were the sole member of a struct.
What you could do is, use the Coding4Fun Toolkit and use the control to display the current memory use and peak memory while developing your app. So download the Toolkit and add the correct dlls to your project. You can also use NuGet.
Now you can add this to your layout:
<coding4fun:MemoryCounter xmlns:coding4fun="clr-namespace:Coding4Fun.Phone.Controls;assembly=Coding4Fun.Phone.Controls"/>
Or declare it in C#:
public MainPage() { InitializeComponent(); MemoryCounter counter = new MemoryCounter(); this.ContentPanel.Children.Add(counter); }
Now you should see two numbers on the top of your screen when you launch it.
You can see the MemoryCounter results only in DEBUG mode!
Otherwise check the DeviceStatus class out, it has some useful things in it:
namespace Microsoft.Phone.Info { public static class DeviceStatus { public static long ApplicationCurrentMemoryUsage { get; } public static long ApplicationPeakMemoryUsage { get; } public static long ApplicationMemoryUsageLimit { get; } public static long DeviceTotalMemory { get; } } }
To see how to use it check this out!
Hope it helps!
-7753989 0Yes, you have to create the product id for every product you wish to put on the app store. Apple checks each and every purchase made by the user on the basis of the product id you create on iTunes Connect.
-18155087 0 intellij Debugger is not able to connect with Remote VMI am working on a JNLP based application which is hosted on JBOSS server. My IDE is intellij . When I tried to do the remote debug on the port defined for that the on Debug console of intellij this message is written
Connected to the target VM, address: 'camelot-dev.kwcorp.com:8787', transport: 'socket'
from this message, I thought that I am connected with the Remote VM and I jumped into the workspace for debugging but nothing seems to be working for me. When I clicked on F6 and respective buttons for debugging nothing seems to working (no debug happened). I checked the debug port and it is correct. I am not sure that whether I am doing the correct thing or not.
-37712436 0Your plunkr wasn't working because your script tag was pointing to a not existing app.js
in index.html
after re-naming script.js
to app.js
the plunkr is working.
Your JSON mock seems a bit complicated. You can easily add a json file to the plunkr and load it with a $http.get()
request.
Please have a look at the demo below and this updated plunkr.
// Code goes here /* var mockDataForThisTest = "json=" + encodeURI( JSON.stringify([ { name: "Dave", email: "dave@gmail.com", option: "Home", number: "1234567890" }, { name: "John", email: "jon@gmail.com", option: "Home", number: "1234567890" } ]));*/ var app = angular.module('angularApp', []); app.controller('MainCtrl', function($scope, $http) { $scope.choices = []; loadChoices(); function loadChoices() { var httpRequest = $http({ method: 'GET', url: 'https://www.mocky.io/v2/5758817a130000f82d896c76' //url: './example.json' //data: mockDataForThisTest }).then(function(response) { //success(function(data, status) { // use then --> newer syntax console.log(response.data); $scope.choices = response.data; }); }; $scope.addNewChoice = function() { var newItemNo = $scope.choices.length + 1; $scope.choices.push({ 'id': 'choice' + newItemNo }); }; $scope.removeChoice = function(index) { //var lastItem = $scope.choices.length - 1; $scope.choices.splice(index, 1); //lastItem); }; });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/> <div ng-app="angularApp" ng-controller="MainCtrl"> <fieldset data-ng-repeat="choice in choices"> <input type="text" ng-model="choice.name" name="" placeholder="Enter name"> <input type="text" ng-model="choice.email" name="" placeholder="Enter email"> <input type="text" ng-model="choice.number" name="" placeholder="Enter mobile number"> <select ng-model="choice.option"> <option value>Select</option> <option value="Mobile">Mobile</option> <option value="Office">Office</option> <option value="Home">Home</option> </select> <button class="remove" ng-click="removeChoice($index)">-</button> </fieldset> <button class="addfields" ng-click="addNewChoice()">Add fields</button> <div id="choicesDisplay"> {{ choices }} </div> </div>
The problem is that the browser is downloading the image when you first reference it, and not before.
I'd simply have two image elements and hide/show them instead of changing the src
attribute of a single element.
The documentation is pretty clear. You cannot use this property on characteristics you publish. The purpose of this value is to enable you to interpret the properties of characteristics that are discovered from other peripherals.
If you want to advise centralised that your value has changed then notify
is the appropriate method.
Note: This method is automatically called by JavaScript whenever a Date object needs to be displayed as a string.
So d+''
is the same as d.toString()
.
In the context of a click-once application that is being debugged locally with exception breaking on "Thrown" turned on in VS2010, I am experiencing the following error:
Deployment Exception: "Store metadata "CurrentBind" is not valid." at System.Deployment.Application.ComponentStore.GetPropertyString(DefinitionAppId appId, String propName)
when I execute the following line of code:
if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed)
This exception is being caught and handled by .net code, and the application will not crash after experiencing this error. Unfortunately, this error is followed up by:
InvalidDeploymentException: "Application is not installed" at System.Deployment.Application.ApplicationDeployment..ctor(String fullAppId)
If I continue to wade through the exceptions, I get another error:
SynchronizationLockException: "Object synchronization method was called from an unsynchronized block of code" at Microsoft.Practices.Unity.SynchronizedLifetimeManager.TryExit() @ ProvidedContainer.RegisterInstance(LoggerFacade);
and finally:
ConfigurationErrorsException: "This element is not currently associated with any context" at System.Configuration.ConfigurationElement.get_EvaluationContext()
in the constructor of
[System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] public partial class InfrastructureDataServiceClient : System.ServiceModel.ClientBase<Infrastructure.DataServices.IInfrastructureDataService>, Infrastructure.DataServices.IInfrastructureDataService { public InfrastructureDataServiceClient() { } }
These errors are all handled by the .net framework code and don't ripple into the application, but as long as I have the option to break on exception "Thrown" I continue to go through these errors until I lose patience and choose to break only on unhandled exceptions, at which point the app fully loads.
This has happened to me in the past, and at that time I had to completely re-install visual studio, but it worked fine after that. I'd rather not do that, as it is time consuming and my VS installation is pretty customized. Also, my co-workers are not experiencing the same error, so that tells me that there is something unique about my environment.
I experienced a visual studio hang recently when debugging, and had to kill the devenv process, that might play a role, but it's hard to say because I recently turned on the break on thrown option. I've already tried to delete the suo files, but that had no effect.
I have the following addons installed: Resharper, .Net Reflector, Team Explorer, TFS Power Tools, Theme Manager
-5684415 0(1) The stack is actually only local to expressionParser so I KNOW I can remove the new keyword
correct
(2) Do I HAVE To create a pointer to the queue in this case. If I need to create the pointer, then I should call a delete output in my query function to properly get rid of the queue?
correct. Here, "creating pointer" doesn't mean again using new
and copy all contents. Just assign a pointer to the already created queue<string>
. Simply delete output;
when you are done with it in your query()
.
(3) vector being returned by query. Should that be left as I have it or should it be a pointer and what's the difference between them?
I would suggest either you pass the vector<Line*>
by non-const reference to your query()
and use it or return a vector<Line*>*
from your function. Because difference is, if the vector is huge and return by value then it might copy all its content (considering the worst case without optimization)
(4) Once I consume that vector (display the information in it) I need it to be removed from memory, however, the pointers contained in the vector are still good and the items being pointed to by them should not be deleted. What's the best approach in this case?
Pass the vector<Line*>
into the function by reference. And retain it in scope until you need it. Once you are done with pointer members 'Line*inside it, just
delete` them
(5) What happens to the contents of containers when you call delete on the container? If the container held pointers?
Nothing happens to the pointer members of the container when it's deleted. You have to explicitly call delete
on every member. By the way in your case, you can't delete
your vector<Line*>
because it's an object not a pointer & when you delete output;
, you don't have to worry about contents of queue<>
because they are not pointers.
(6) Those pointers are deleted won't that affect other areas of my program?
Deleting a valid pointer (i.e. allocated on heap) doesn't affect your program in any way.
-8588334 0The center
of a view is expressed in it's superview's coordinate system. So you are centering your image view in the wrong coordinate system. (dynamic view's superview as opposed to dynamic view)
To centre view A within view B, the centre point of view A has to be the centre of the bounds
rectangle of view B. You can get this using (from memory!) CGRectGetMidX
and CGRectGetMidY
.
You are trying to do too much in the main method. You need to break this up into more manageable parts. Write a method boolean isPrime(int n)
that returns true if a number is prime, and false otherwise. Then modify the main method to use isPrime.
I'm having problems when trying to build a proyect on Intellij Idea. There are 2 problems:
When creating a gradle project on Intellij Idea, and I select "Use default gradle wrapper (recommended)", Intellij Idea can't let me set the Gradle Home. Then, when I go to Build -> Make project, Intellij Idea tells me that is downloading Gradle, when actually I have already downloaded Gradle 2.12 (I'm using gradle in another projects).
The second thing I'm doing is to create a project and when setting gradle (in the New Project Wizard) and set "Use local gradle distribution". When doing this, and building the project, Intellij Idea tells me that is refreshing gradle project and stays there(I have been waiting 1 hour and nothing..)
So, which is the best way to create a gradle project, or, how can I solve this problems?
Thanks
-30769109 0If using uWSGI, there is a command line option which allows you to say you are providing it with a module path instead of a file path. For standard Apache with mod_wsgi, or with uWSGI defaults, you can create a WSGI script file which imports the WSGI application from your module by its path into the WSGI script file and then refer to that WSGI script file. If using mod_wsgi-express, then it has an option like uWSGI which allows you to say you are providing it with a module path instead.
-38539650 0 Google map not load completely and rending errorI have one problem with google map, I used https://ngmap.github.io/#/!places-auto-complete.html.
I split my web app into multiple tabs and turn catch it by ng-if
.
Currently in the main tab, I can google map fully loaded, but in others, it fails tab as shown below. The first image is the main tab, it's okay. But the 2nd picture is faulty, somebody please tell me why and how to fix me, please In tab Dashboard, google map is okay, but in tab Manage it does not load completely.
-30409981 0 How to allow access to a file for a specific domain and block for other domain in Apache2.conf?I have blocked the access to a file in apache configuration by editing the .conf file. For now, only localhost can access the files. Is there a way where i can access the files if it requested from a specific domain name or if requested by query string parameters.
Apache.conf -
-13279307 0Order allow,deny Allow from 127.0.0.1
Cast the obj
to type of the return.
For example if your expected return type is PdsLongAttrImpl
Then, it would be:
PdsLongAttrImpl pdsObj = (PdsLongAttrImpl)obj;
//Then perform operation on pdsObj
.
NOTE: If obj is not of the type you are casting to, you will end up with ClassCastException
.
This is suppose to store the chosen answer for multiple questions. When I use this code, it only checks the first question and disregards the other questions.
for(i = 0; i < questions.length-1; i++){ radios = document.getElementsByName(questions[i]); for (var t = 0; length < radios.length; t++) { if (radios[t].checked) { var qResults = JSON.parse(localStorage["qResults"]); num = radios[t].value; checked = num.toString(); var temp = (id[0] + ";" + questions[i] + ";" + checked); alert(temp); qResults.push(temp); localStorage["qResults"] = JSON.stringify(qResults); } } alert("question finished"); }
-13264230 0 What is the difference between named and optional parameters in Dart? Dart supports both named optional parameters and positional optional parameters. What are the differences between the two?
Also, how can you tell if an optional parameter was actually specified?
-25979649 0 dgrid editor with a dijit.form.SelectI have a column in my dgrid that uses a digit.form.Select.
var gl = {}; gl.coverTypeEditorData = [{label: "C", value: "C"}, {label: "F", value: "F"}, {label: "G", value: "G"}, {label: "S", value: "S"}, {label: "P", value: "P"}]; ... ,editor({ 'label': 'Type', 'field': 'TYPE', 'editor': Select, 'editorArgs': { options: gl.coverTypeEditorData } } )
The select drop down displays the correct value, but when it closes the value in the cell gets changed to whatever value was last chosen.
Row 1: Change the value to S.
Row 2: Has value C. I select the dd but do not change the value. Display changes to S. Change row event does not fire. The cell has a S displaying but its actual value is C, which will be the selected value if I open the drop down again.
What do I need to add to get the cell to display the correct value?
-36282002 0 Handling option groups in Access form- runtime error 2427I have an option group on a form. I want the form to process code based on which button is selected. The snippet I have for now is:
If Me.Option18.Value = True Then DoCmd.OpenQuery "Logbook Query all available" End If
Option 18 is the radio button on the form.
On the If line, I get 'run time error 2427: You entered an expression that has no value'
I tried different uses of me.option 18, and get the same error. I also tried replacing 'true' with 1, same result.
Is there a better way to execute code based on an option group selection. or is this simply a syntax error?
-19122892 0If you want to know if an object property exists, regardless of its value, you can use property_exists
.
if (property_exists($model, $column) { ... }
-36524426 0 I think that the best way to do it is to overriding the default ExceptionController. Just extend it, and override the findTemplate
method. Check from the request's attribute if there's _route
or _controller
set, and do something with it.
namespace AppBundle\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Bundle\TwigBundle\Controller\ExceptionController as BaseExceptionController; class ExceptionController extends BaseExceptionController { protected function findTemplate(Request $request, $format, $code, $showException) { $routeName = $request->attributes->get('_route'); // You can inject these routes in the construct of the controller // so that you can manage them from the configuration file instead of hardcode them here $routesAdminSection = ['admin', 'admin_ban', 'admin_list']; // This is a poor implementation with in_array. // You can implement more advanced options using regex // so that if you pass "^admin" you can match all the routes that starts with admin. // If the route name match, then we want use a different template: admin_error_CODE.FORMAT.twig // example: admin_error_404.html.twig if (!$showException && in_array($routeName, $routesAdminSection, true)) { $template = sprintf('@AppBundle/Exception/admin_error_%s.%s.twig', $code, format); if ($this->templateExists($template)) { return $template; } // What you want to do if the template doesn't exist? // Just use a generic HTML template: admin_error.html.twig $request->setRequestFormat('html'); return sprintf('@AppBundle/Exception/admin_error.html.twig'); } // Use the default findTemplate method return parent::findTemplate($request, $format, $code, $showException); } }
Then configure twig.exception_controller
:
# app/config/services.yml services: app.exception_controller: class: AppBundle\Controller\ExceptionController arguments: ['@twig', '%kernel.debug%']
# app/config/config.yml twig: exception_controller: app.exception_controller:showAction
You can then override the template in the same way:
A simpler way to do this is to specify the section of the website inside the defaults
collection of your routes. Example:
# app/config/routing.yml home: path: / defaults: _controller: AppBundle:Main:index section: web blog: path: /blog/{page} defaults: _controller: AppBundle:Main:blog section: web dashboard: path: /admin defaults: _controller: AppBundle:Admin:dashboard section: admin stats: path: /admin/stats defaults: _controller: AppBundle:Admin:stats section: admin
then your controller become something like this:
namespace AppBundle\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Bundle\TwigBundle\Controller\ExceptionController as BaseExceptionController; class ExceptionController extends BaseExceptionController { protected function findTemplate(Request $request, $format, $code, $showException) { $section = $request->attributes->get('section'); $template = sprintf('@AppBundle/Exception/%s_error_%s.%s.twig', $section, $code, format); if ($this->templateExists($template)) { return $template; } return parent::findTemplate($request, $format, $code, $showException); } }
And configure twig.exception_controller
in the same way as described above. Now you just need to define a template for each section, code and format.
I am writing code for a windows application using vb.net. I want to open a text file under c:\
. If the file already exists I want to delete that file.
my code ------- Dim file As String = "C:\test.txt" If System.IO.File.Exists(file) Then file.Remove(file) Else System.Diagnostics.Process.Start(file) End If
I am getting the following error when I try to open that file.
error ----- The system cannot find the file specified
-34577849 1 Getting value of an HiddenField inserting it from template - Flask I'm a newbie in Python/Flask programmation and I'm having some problems to return the value of my HiddenField inserting it from my template.
This my Form Class:
class DownloadForm(Form): link = HiddenField() download = SubmitField('Download')
And this is my template "Material" with a table in which I put my materials from DB and where I'm trying to put the value of the HiddenField:
<tbody> {% for mat in materials %} <tr> <td>{{ mat.author }}</td> <td>{{ mat.title }}</td> <td>{{ mat.subject }}</td> <td>{{ mat.description }}</td> <td>{{ mat.faculty }}</td> <td>{{ mat.professor }}</td> <td> <select class="form-control"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select> </td> <form method="POST" enctype="multipart/form-data" action={{url_for('download')}}> {{ formDownload.link(value = '{{mat.link}}')}} <td>{{ formDownload.download }}</td> </form> <td>{{ formDelete.delete }}</td> </tr> {% endfor %} </tbody> </table>
The problem is in this line of code where I would like to insert the HiddenField value.
{{ formDownload.link(value = '{{mat.link}}')}}
I want to insert the value here because every SubmitField is linked with a specific row of the table. The variable mat.link contains the url of the material that users want to download but I can't get this value with the function form.request['link'].
Here there's my function download when form is submitted:
@app.route('/download', methods=['GET', 'POST']) def download(): form = DownloadForm(csrf_enabled=False) if form.validate_on_submit(): link = request.form['link'] return redirect(url_for('download', filename=link))
I've tried to debug my application and the variable link results equal to "mat.link" as a string . Can someone help me please ? Thanks
-31093166 0 Polymer 1.0 Dom-Repeat Bind ArrayIn my try to update to Polymer 1.0 I got the following problem with Data-Binding:
My Polymer 0.5 Webapp uses a Repeat-Template to generate Checkboxes for some Categories. All checked
values are bound to an array (sortedCatsArray
) with the category-ids as key. Here is my first attempt to update that part to Polymer 1.0, but it doesn't work...
<template is="dom-repeat" items="{{sortedCatsArray}}" as="category"> <paper-checkbox for category$="{{category.id}}" checked="{{filterChkboxes[category.id]}}"></paper-checkbox> </template>
As you may read in the docs, it is no longer possible to bind to Array-Properties with square-brackets (now that way: object.property
). May anybody tell me if it's still possible to bind all generated checkbox-values in one array?
Update #1
As you may read in the docs, Array-Binding by index is not supported. So I tried to use that example from the docs for my case and wrote the following code. If I run this code, it seems to work as expected: the first and third checkbox is checked. But I also want the array to be changed if I manual check/uncheck a checkbox. That does not happen, only if I change the array (in the ready
-function) the checkbox gets checked...
<dom-module id="my-index"> <link rel="import" type="css" href="/css/index.css"> <template> <template is="dom-repeat" items="{{sortedCatsArray}}" as="category"> <paper-checkbox for category$="{{category.id}}" checked="{{arrayItem(filterChkboxes.*,category.id)}}" on-change="test"></paper-checkbox> </template> </template> </dom-module> <script> Polymer({ is: "my-index", properties: { filterChkboxes: { type: Array, notify: true, observer: "filterChkboxesChanged", value: function(){return[true,false,true,false];} }, sortedCatsArray: { type: Array, value: function(){return[{id: 0}, {id: 1},{id: 2},{id: 3}]}, notify: true }, }, ready: function(){ this.set('filterChkboxes.1',true); }, test: function(){ console.log(this.filterChkboxes); }, observers: [ 'filterChkboxesChanged(filterChkboxes.*)' ], arrayItem: function(array, key){ return this.get(key, array.base); }, filterChkboxesChanged: function(changes){ console.log(changes); }, }); </script>
-31041329 0 Kendo combobox not show the Text corresponding to value from modal I have a partial view with a combobox. When try to render partial view with modal(contains data from database), it shows only the value field. i want to show the text field of that value field. Help me please.
@(Html.Kendo().ComboBoxFor(m => m.divCode) .DataTextField("Name") .DataValueField("ID") .HtmlAttributes(new { style = "width:160px" }) .SelectedIndex(0) .AutoBind(false) .Placeholder("Select Div Code") .Filter(FilterType.Contains) .DataSource(source => { source.Read(read => { read.Action("GetDivision", "AssetTransaction"); }); }) )
-36286882 0 need to create one sample app using google app engine I need to integrate Google app engine to use as back end for iOS app .
I have tried following the Link But I wasnt able to complete it .
Can AnyOne Please guide me the step to convert the Parse database back end to Google App Engine as back end .
Kindly guide the proper way .
Thanks
-38872477 0Then you can't use a form-level setting.
If this is constant (the fields are always locked), simply set all other controls to Locked = True
.
If it's dynamic, use a procedure like this:
Private Sub SetEditable(EnableEdit As Boolean) Dim ctl As Control For Each ctl In Me.Controls ' The main editable control types (add more if they occur on your form) If ctl.ControlType = acTextBox Or ctl.ControlType = acComboBox Or _ ctl.ControlType = acCheckBox Or ctl.ControlType = acSubform Then If ctl.Name = "MySpecialDateField" Then ' Always editable ctl.Locked = False Else ctl.Locked = Not EnableEdit ' If you want to provide a visual feedback: ' 0 = Flat (locked), 2 = Sunken (editable) ctl.SpecialEffect = IIf(EnableEdit, 2, 0) End If End If End If Next ctl End Sub
-22534739 0 The panel's update function expects a HTML string instead of a DOM object:
// using a HTML string Ext.getCmp('treeContainer').update("<div class='NodeContent'>" + node.displayText + "</div>"); // using a DOM object Ext.getCmp('treeContainer').update(nodeDiv.outerHTML);
Note, that using this function will always replace all existing HTML content in the panel.
If you really want to append HTML (i.e. preserve existing HTML content), you need to get a target element to append your HTML/DOM node to.
This could be the panel's default render target element:
var panel = Ext.getCmp('treeContainer'), renderEl = panel.isContainer ? panel.layout.getRenderTarget() : panel.getTargetEl(); // using a DOM node renderEl.appendChild(nodeDiv); // using a HTML string renderEl.insertHtml('beforeEnd', "<div class='NodeContent'>" + node.displayText + "</div>");
Or - as this may change depending on your panel's layout - you just create a containg element in your initial html config:
{ xtype: 'panel', id: 'treeContainer', html: '<div class="html-content"></div>' }
and append your content there:
Ext.getCmp('treeContainer').getEl().down('.html-content').appendChild(nodeDiv);
In any of the latter two cases, you should update the panel's layout afterwards, as you changed it's content manually:
Ext.getCmp('treeContainer').updateLayout();
-23576794 0 When pasting into the console, spaces after command are causing issue I have a simple line of code, with multiple readline commands that works just fine if I type it into the console directly, or paste it in from an existing R document without any excess spaces after the last bracket.
{ v1 <- readline("Choose 1: "); v2 <- readline("Choose 2: "); v3<- readline("Choose 2: ")}
If I run the above line I will be asked to Choose 1, then Choose 2, then Choose 3. This example is simple, but it is how I like to enter a lot of my data.
But if I inadvertently copy some empty spacing after the line of code when copying from an R document, or the above line is included with other code like so:
X<-c(1,2,3,4,5) { v1 <- readline("Choose 1: "); v2 <- readline("Choose 2: "); v3<- readline("Choose 2: ")} Y<-c(1,2,3,4)
All three readline commands will be printed at once, so that I can't enter my data in.
I've tried including the readline statements in a function, but I run into the same kind of problem with pasting spaces after the function call, causing the readline statements to all be printed out at once.
fun<-function(){ v1 <- readline("Choose 1: "); v2 <- readline("Choose 2: "); v3<- readline("Choose 2: ") } fun() Y<-c(1,2,3,4)
The only luck I've had is to use source() to call a function from a separate R document, but I'm trying to avoid using source and keep everything in one R document. Ideally I'd like to be able to run multiple readline (or some other way to be asked to enter data), from a piece of code sandwiched in other code.
-3123951 0 SQLite: How to calculate age from birth dateWhat is the best way to calculate the age in years from a birth date in sqlite3?
-10693076 0It is possible to "Publish" the results of the job. The response from the HTTP request can be written to the file server, and that will have the values of the last run job.
<cfschedule action = "update" task = "TaskName" operation = "HTTPRequest" url = "/index.cfm?action=task" startDate = "#STARTDATE#" startTime = "12:00:00 AM" interval = "Daily" resolveURL = "NO" requestTimeOut = "600" publish = "yes" path = "#PATH#" file = "log_file.log">
Then you can verify the log against the database if you wanted. Since it is the response from the page, you can get and store errors and warnings here as well.
-6183877 0Javascript Patterns is a good book to learn object oriented programming and advanced concepts in javascript.
-4981227 0This is on mac, I'm guessing? I'm not very familiar with compiling on mac.
Can you tell us how you're compiling (i.e. what compile flags, etc). And perhaps add an example which is compilable).
Also, can you compile this code using your environment?
#include "CLucene.h" int main(){ lucene::analysis::SimpleAnalyzer *sanalyzer = new lucene::analysis::SimpleAnalyzer(); }
I compiled the above code with the following command with no problems. (-fPIC because i'm on an 64 bit machine).
-38905683 0 JSON DECODE using PHPg++ test.cpp -lclucene -I/usr/lib -fPIC
I am doing some JSON decodes - I followed this tutorial well explained - How To Parse JSON With PHP
and the PHP code, I used
<?php $string='{"person":[ { "name":{"first":"John","last":"Adams"}, "age":"40" }, { "name":{"first":"Thomas","last":"Jefferson"}, "age":"35" } ]}'; $json_a=json_decode($string,true); $json_o=json_decode($string); // array method foreach($json_a[person] as $p) { echo ' Name: '.$p[name][first].' '.$p[name][last].' Age: '.$p[age].' '; } // object method foreach($json_o->person as $p) { echo ' <br/> Name: '.$p->name->first.' '.$p->name->last.' Age: '.$p->age.' '; } ?>
It is working correctly... But my concern I need only details of Thomas' last name and age. I need to handle this to extract only certain features, not all the objects.
-38442568 0 Problems with NSTokenView (again) - using objectvalueIn my Swift Application for Mac OS X, I'm using a NSTokenField. I'm using, among others, the delegate methods tokenField(tokenField: NSTokenField, representedObjectForEditingString editingString: String) -> AnyObject
and tokenField(tokenField: NSTokenField, displayStringForRepresentedObject representedObject: AnyObject) -> String?
to work with represented objects. My represented objects are instances of a custom class.
From the Apple Documentation, I know that objectValue
can be used to access the represented objects of a NSTokenView
as a NSArray
:
To retrieve the objects represented by the tokens in a token field, send the token field an
objectValue
message. Although this method is declared byNSControl
,NSTokenField
implements it to return an array of represented objects. If the token field simply contains a series of strings,objectValue
returns an array of strings. To set the represented objects of a token field, use thesetObjectValue
: method, passing in an array of represented objects. If these objects aren’t strings,NSTokenField
then queries its delegate for the display strings to use for each token.
However, this doesn't seem to work for me. let tokenArray = self.tokenField.objectValue! as! NSArray
does return a NSArray, but it is empty, even though the delegate method required to return a represented object has been called the appropriate amount of times before.
NSTokenView
doesn't seem like a particularly strong tool to work with tokenization, but, lacking an alternative, I hope that you guys can help me making my implementation work.
Thanks in advance!
-21929870 0 Error 410:gone (codenameone)So I tried the tutorial Codenameone provided on JSON parsing, but now when i try it out it gives me a 410:gone error.
I did google the error but didn't find anything in combination with java or codenameone and i don't really understand the meaning of this error.
This error is not only in netbeans as i expected but even the on android it gives this error.
Code below is the action performed after clicking the "get twitter"-button:
public void actionPerformed(ActionEvent evt) { ConnectionRequest request = new ConnectionRequest() { @Override protected void readResponse(InputStream input) throws IOException { JSONParser parser = new JSONParser(); System.out.println(parser.parse(new InputStreamReader(input))); } }; request.setUrl("http://search.twitter.com/search.json"); request.setPost(false); request.addArgument("q", "@codenameone"); NetworkManager manager = NetworkManager.getInstance(); manager.start(); manager.addToQueue(request); } });
-33373890 0 MySQLi is not a driver for PDO. It is a standalone class. PDO has the following drivers:
More information you can find here: http://php.net/manual/de/pdo.drivers.php
You have to remove the i
from the dsn: mysql:host=127.0.0.1;dbname=app
You will need to identify what makes that data unique in the table. If it's a customer table, then it's probably the customerid of 13029. However if it's a customer order table, then maybe it's the combination of CustomerId and OrderDate (and maybe not, I have placed two unique orders on the same date). You will know the answer to that based on your table's design.
Armed with that knowledge, you will want to write a query to pull back the keys from the target table SELECT CO.CustomerId, CO.OrderId FROM dbo.CustomerOrder CO
If you know the process only transfers data from the current year, add a filter to the above query to restrict the number of rows returned. The reason for this is memory conservation-you want SSIS to run fast, don't bring back extraneous columns or rows it will never need.
Inside your dataflow, add a Lookup Transformation with that query. You don't specify 2005, 2008 or 2012 as your SSIS version and they have different behaviours associated with the Lookup Transformation. Generally speaking, what you are looking to do is identify the unmatched rows. By definition, unmatched means they don't exist in the target database so those are the rows that are new. 2005 assumes every row is going to match or it errors. You will need to click the Configure Error Output... button and select "Redirect Rows". 2008+ has an option under "Specify how to handle rows with no matching entries" and there you'll want "Redirect rows to no match output."
Now take the No match output branch (2008+) or the error output branch (2005) and plumb that into your destination.
What this approach doesn't cover is detecting and handling when the source system reports $56.82 and the target system has $22.38 (updates). If you need to handle that, then you need to look at some change detection system. Look at Andy Leonard's Stairway to Integration Services series of articles to learn about options for detecting and handling changes.
-38004053 0function dividedByArray(data,low,high) { for (i=low; i<=high; i++) { var passed = 0; for(var curr in data) { if(i % data[curr] === 0) { passed++; } } switch(passed) { case data.length : console.log(i + 'all_match'); break; case 0 : console.log(i) break; default: console.log(i + " one_match"); } } }
-29969185 0 Found the solution. The problem was the labelunderscore
div that was created in the page. This "confuses" the jquery library as whilst it applying the slide in effect, it has to apply the slide out effect on the same div.
The problem has been sorted by creating the labelunderscore
div in the function at runtime and assigning it a unique id based on the id of the hovered element. Code as follows:
// Slide in effect for hover on class=head labels $(".head").hover(function () { //alert($(this).attr('id')) $('#main').append('<div id="labelunderscore_' + $(this).attr("id") + '" class="labelunderscore"></div>'); // Set width to hovering element width: $('#labelunderscore_' + $(this).attr("id")).css("width", $(this).width() + 20); // Set position on labelunderscore to current element left value $('#labelunderscore_' + $(this).attr("id")).css("left", $(this).offset().left); // Check where are we hovering. Left side slide from left right from right if ($(this).offset().left > $(window).width()/2) { // We are on the right side $('#labelunderscore_' + $(this).attr("id")).show('slide', {direction: 'right'}, 200); } else { // Left side $('#labelunderscore_' + $(this).attr("id") ).show('slide', {direction: 'left'}, 200); } }, function () { $('#labelunderscore_' + $(this).attr("id")).hide('slide', {direction: 'left'}, 200); })
-1680067 0 I would recommend that you create another column in the database for arranging your items instead of using the OrderID - which is, I'm assuming here, may be used as a row identifier/ primary key for your database.
I'll give you a scenario.
Say you have the following items:
And you have added another item:
What if the user deletes Order ID 2 - Banana, and would want Order ID 4- Grapes to replace the deleted item in your list, how are you going to sort it by then? At least if you add another column, then you can preserve the sorting order for your items without touching your Order ID.
On the other hand, if the Order ID is not the primary key for your table and you have a different primary key, then by all means use the Order ID as your sorting column. Make sure that you implement unique index for the sorting column so that it could enhance your db as well as application performance.
To make your sorting a lot easier in .NET, you can use the classes in System.Collections.Specialized Namespace to sort your lists and want it for strongly-typed collections, i.e. Dictionary, OrderedDictionary, etc. because you will be using a key/value pair if you are implementing a sort order column.
Hope this helps!
-26231138 0 Error in update ADT in Eclipse and IBM Worklight StudioAfter update Android SDK I found this error message in Eclipse:
This Android SDK requires Android Developer Toolkit version 23.0.0 or above. Current version is 22.6.3.v201404151837-1123206. Please update ADT to the latest version.
In Stackoverflow are several very complete answer to this problem like here and here.
But I'm Working with Eclipse Kepler because is a requirement of IBM Worklight Studio.
Have I to update ADT to the latest version?
IBM Worklight still working afterwards?
I have this code so far...
function sendData() { // this work out where I am and construct the 'cmi.core.lesson.location' variable computeTime(); var a = "" + (course.length - 1) + "|"; for (i = 1; i < course.length; i++) { a = a + qbin2hex(course[i].pages).join("") + "|"; if (iLP == 1) { a = a + course[i].duration + "|"; a = a + course[i].timecompleted + "|" } } SetQuizDetails(); a = a + course[0].quiz_score_running + "|0|0|0|0|0|0|"; objAPI.LMSSetValue("cmi.core.lesson_location", "LP_AT7|" + a); bFinishDone = (objAPI.LMSCommit("") == "true"); objAPI.LMSCommit(""); console.log("Data Sent!"); } setTimeout(sendData(), 1000);
However, it doesn't seem to work as intented. Data should be sent off to the server every 1000ms, but that's not happening. What am I missing here?
As I side note, this is SCORM 1.2.
-6673450 0This is an example of an object literal.
It creates a normal object with two properties.
-5411974 0Check if the proc belongs to a different schema than expexted.
Something like myaccount.MyProc if it is expected to be dbo.MyProc
-25664859 0Do not do that: new FormInt64Control()
. Just don't. Only create form controls using addControl
.
To answer your question you need access to the C++ source code implementing the control. I do not have that access, nor do you.
-12479124 0No, there aren't any changes in respect to custom action filters. Assuming you have controller/actions decorated with this attribute the OnAuthorization
will always be called.
You might be able to implement a DeviceAdminReceiver
From it's description it should be notified of failed password attempts but it's not really clear from the description if that includes lock screen attempts.
If that did work from a service or something you might be able to launch a toast though.
[Edit] Found a better resource
-27854464 0 Unable to change label text after presenting the view controller programmatically in swiftI am presenting the a view programmatically in if else statement using this code:
if (Condition) { ..... } else { var vc = self.storyboard?.instantiateViewControllerWithIdentifier("gameover") as UIViewController self.presentViewController(vc, animated: true, completion: nil) finalMsg.text="Thank you" }
So the view is getting changed but I am not able to change the text of label finalMsg which belongs to the view that I changed programmatically (gameover).
I am getting error "fatal error: unexpectedly found nil while unwrapping an Optional value"
Can someone help me on this?
-19797247 0Have a look at this article: HOW TO: Control Authorization Permissions in an ASP.NET Application
In short you can set folder permissions like this:
<configuration> <location path="images"> <system.web> <authorization> <deny users ="?" /> </authorization> </system.web> </location> </configuration>
-24999421 0 You can find source code in Appendix E of this paper explaining how to proceed for a variety of problems.
The code is reproduced below in case the paper becomes lost to the Internet:
function result = acorPTcg() %Archive table is initialized by uniform random % clear all nVar = 10; nSize = 50; %size nAnts = 2; fopt = 0; %Apriori optimal q=0.1; qk=q*nSize; xi = 0.85; maxiter = 25000; errormin = 1e-04; %Stopping criteria %Paramaeter range Up = 0.5*ones(1,nVar); %range for dp function Lo = 1.5*ones(1,nVar); %Initialize archive table with uniform random and sort the result from %the lowest objective function to largest one. S = zeros(nSize,nVar+1,1); Solution = zeros(nSize,nVar+2,1); for k=1:nSize Srand = zeros(nVar); for j = 1:nAnts for i=1:nVar Srand(j,i) = (Up(i) - Lo(i))* rand(1) + Lo(i); %uniform distribution end ffbest(j)=dp(Srand(j,:)); %dp test function end [fbest kbest] = min(ffbest); S(k,:)=[Srand(kbest,:) fbest]; end %Rank the archive table from the best (the lowest) S = sortrows(S,nVar+1); %Select the best one as the best %Calculate the weight,w %the parameter q determine which solution will be chosen as a guide to %the next solution, if q is small, we prefer the higher rank %qk is the standard deviation % mean = 1, the best on w = zeros(1,nSize); for i=1:nSize w(i) = pdf('Normal',i,1.0,qk); end Solution=S; %end of archive table initialization stag = 0; % Iterative process for iteration = 1: maxiter %phase one is to choose the candidate base one probability %the higher the weight the larger probable to be chosen %value of function of each pheromone p=w/sum(w); ref_point = mean(Solution(:,nVar+1)); for i=1:nSize pw(i) = weight_prob(p(i),0.6); objv(i)= valuefunction(0.8,0.8, 2.25, ref_point-Solution(i, nVar+1)); prospect(i) = pw(i)*objv(i); end [max_prospect ix_prospect]=max(prospect); selection = ix_prospect; %phase two, calculate Gi %first calculate standard deviation delta_sum =zeros(1,nVar); for i=1:nVar for j=1:nSize delta_sum(i) = delta_sum(i) + abs(Solution(j,i)- ... Solution(selection,i)); %selection end delta(i)=xi /(nSize - 1) * delta_sum(i); end % xi has the same as pheromone evaporation rate. Higher xi, the lower % convergence speed of algorithm % do sampling from PDF continuous with mean chosen from phase one and % standard deviation calculated above % standard devation * randn(1,) + mean , randn = random normal generator Stemp = zeros(nAnts,nVar); for k=1:nAnts for i=1:nVar Stemp(k,i) = delta(i) * randn(1) + Solution(selection,i); %selection if Stemp(k,i)> Up(i) Stemp(k,i) = Up(i); elseif Stemp(k,i) < Lo(i); Stemp(k,i) = Lo(i); end end ffeval(k) =dp(Stemp(k,:)); %dp test function end Ssample = [Stemp ffeval']; %put weight zero %insert this solution to archive, all solution from ants Solution_temp = [Solution; Ssample]; %sort the solution Solution_temp = sortrows(Solution_temp,nVar+1); %remove the worst Solution_temp(nSize+1:nSize+nAnts,:)=[]; Solution = Solution_temp; best_par(iteration,:) = Solution(1,1:nVar); best_obj(iteration) = Solution(1,nVar+1); %check stopping criteria if iteration > 1 dis = best_obj(iteration-1) - best_obj(iteration); if dis <=1e-04 stag = stag + 1; else stag = 0; end end ftest = Solution(1,nVar+1); if abs(ftest - fopt) < errormin || stag >=5000 break end end plot(1:iteration,best_obj); clc title (['ACOR6 ','best obj = ', num2str(best_obj(iteration))]); disp('number of function eveluation') result = nAnts*iteration; %%------------------------------------------------------------- function value = valuefunction(alpha, beta, lambda, xinput) value =[]; n = length(xinput); for i=1:n if xinput(1,i) >= 0 value(1,i) = xinput(1,i) ^ alpha; else value(1,i) = -lambda * (-xinput(1,i))^ beta; end end function prob = weight_prob(x, gamma) % weighted the probability % gamma is weighted parameter prob=[]; for i=1:length(x) if x(i) < 1 prob(i) = (x(i)^(gamma))/((x(i)^(gamma) + (1-x(i))^(gamma))^(1/gamma)); %prob(i) = (x(i)^(1/gamma))/((x(i)^(1/gamma) + (1-x(i))^(1/gamma))^(1/gamma)); else prob(i) = 1.0; end end function y = dp(x) % Diagonal plane % n is the number of parameter n = length(x); s = 0; for j = 1: n s = s + x(j); end y = 1/n * s;
-24336551 0 Charts in zend framework2 I am working with zend framework 2 and i want to display charts in some views but it doesn't work!! This is my Action:
public function statvehAction(){ $data = [ 'labels' => ["January","February","March","April","May","June","July"], 'data' => [18,99,30,81,28,55,30] ]; json_encode($data); $viewModel = new ViewModel(array('data' => $data)); return $viewModel; }
this is my view:
<script src="../../../../jquery.min.js"></script> <script src="../../../../chart.min.js"></script> <script> (function($){ var ctx = document.getElementById("chart").getContext("2d"); $.ajax({ type: "POST", url: "VehiculesController.php", dataType: "json" }) .success(function(data) { var d = { labels: $data.labels, datasets : [ { fillColor: "rgba(220,220,220,0.5)", strokeColor: "rgba(220,220,220,1)", data: data.data }] }; var barChart = new Chart(ctx).Bar(d); }); })(jQuery); </script>
But when i want to diplay my chart i got a white page whith no error !! Please can you help me to solve this problem.
-22814123 0 How to correctly affect multiple css properties in jqueryBelow is an example of how I currently would affect two css properties for the same div in jquery:
$('#mydiv').css("width",myvar+"px"); $('#mydiv').css("margin-left",myvar+"px");
I don't believe this to be the most efficient method as it requires two lines of code for one div, can somebody please show me a more susinct (tidier) method of writing the same thing?
-38263641 0It may be model update problem try this.
$scope.$apply();
-900136 0 One way is to just have a copy of your database file (mdf) available for pushing onto a new server. This similiar to what microsoft does with it's Model database. Whenever you create a new database it starts by making a copy of that one.
Your button click could copy the database file to the desired location, rename it as appropriate, then attach it to the running sql server instance. Whenever you need to update the database with a new schema, just copy the mdf to your deployment directory.
-17935206 0 How to layout correctlyI just try to create my own layout. I used UITableView
for my UIViewController
. I have some JSON response from server. This is like detailed publication. Also i calculate my UITableViewCell
height because my publication contain mix of images and text. I wrote own layout and recalculate when device in rotation.
for (UIView * sub in contentSubviews) { if([sub isKindOfClass:[PaddingLabel class]]) { PaddingLabel *textPart = (PaddingLabel *)sub; reusableFrame = textPart.frame; reusableFrame.origin.y = partHeight; partHeight += textPart.frame.size.height; [textPart setFrame:reusableFrame]; } else if([sub isKindOfClass:[UIImageView class]]) { UIImageView * imagePart = (UIImageView *)sub; reusableFrame = imagePart.frame; reusableFrame.origin.y = partHeight; reusableFrame.origin.x = screenWidth/2 - imageSize.width/2; reusableFrame.size.width = imageSize.width; reusableFrame.size.height = imageSize.height; [imagePart setFrame:reusableFrame]; partHeight += imagePart.frame.size.height; } }
But I have some issue. When device change orientation state UIScrollView
offset is same as was. I don't know how to change it. Before rotation:
After rotation:
I want to save visible elements in rect. Suggest pls.
-7389510 0I also started to look at the MVC Music Store example.
-40953020 0You don't have an instance of elasticsearch running failing to get to server at localhost:9200 indicates that.
-16297052 0 Replace a text with a variable (sed)How can I do this?
sed -i 's/wiki_host/$host_name/g' /root/bin/sync
It will replace wiki_host with the text $host_name. But i want to replace it with the content of the variable..
I tried it with
sed -i 's/wiki_host/${host_name}/g' /root/bin/sync
It doesnt work too..
-30050115 0Use word boundaries:
Pattern p=Pattern.compile("\\b(1[0-9]|[0-9])\\b");
-14768853 0 If you take a look into the Android.mk file of OpenSSH you'll find the following line:
LOCAL_MODULE_TAGS := optional
This means that the module will be include into a build if the module name is listed in the appropriate make file (for instance, in a build/target/product/core.mk
)
If you want to use just 1 transaction and more then one EJB method call, then 1., use the session facade design pattern. Create a facae bean with CMT (Container Managed Transaction) to call the other beans within its own transaction. 2., Use BMT (Bean Managed Transaction)
-18281403 0Try to use the "new" keyword instead of "override" and remove the "virtual" keyword from methods;)
-2512863 0 Have you been in cases where TDD increased development time?I was reading TDD - How to start really thinking TDD? and I noticed many of the answers indicate that tests + application should take less time than just writing the application. In my experience, this is not true. My problem though is that some 90% of the code I write has a TON of operating system calls. The time spent to actually mock these up takes much longer than just writing the code in the first place. Sometimes 4 or 5 times as long to write the test as to write the actual code.
I'm curious if there are other developers in this kind of a scenario.
-34537143 0 SharedPreferences variable always returns falseI am using a Preference Fragments following the step by step guide on Android guide.
I am trying to set some preferences using this fragment, so later on the code I can check the value of each variable to perform actions accordingle.
Mi Preference fragment is working fine. However, when I try to recover the value of a CheckedBoxPreference somewhere else on the code, it always returns false.
This is the preference xml file :
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" android:persistent="true" > <PreferenceCategory android:title="NOTIFICACIONES" android:key="pref_key_storage_settings"> <CheckBoxPreference android:key="sendMail" android:defaultValue="false" android:persistent="true" android:summary="Send emails to contacts" android:title="E-mail"/> </PreferenceCategory> </PreferenceScreen>
This is the class I've done to use SharedPReferences
public class Prefs{ private static Prefs myPreference; private SharedPreferences sharedPreferences; private static final String NOMBRE_PREFERENCIAS = "MisPreferencias"; public static Prefs getInstance(Context context) { if (myPreference == null) { myPreference = new Prefs(context); } return myPreference; } private Prefs(Context context) { sharedPreferences = context.getSharedPreferences(NOMBRE_PREFERENCIAS,context.MODE_PRIVATE); } public Boolean getBoolean(String key) { boolean returned = false; if (sharedPreferences!= null) { returned = sharedPreferences.getBoolean(key,false); } return returned; } }
And this is how I check if the options is selected, so I can send/or not emails to clients
Prefs preferences = Prefs.getInstance(getApplicationContext()); if(preferences.getBoolean("sendMail") { // .... send email }
As I said, what is strange is that It is persistent on the settings fragment ( if I select the option sendEmmail, it is selected even if I close the app and reopen it. However, when I check the value using my method, it always returns false.
What am I doing wrong?
Thank you
-14857267 0 VS regex search: Find Try..Finally with no CatchI want to use the Regular Expression search in Visual Studio to find all instances of a Try/Finally block without a Catch.
After reading the help file, I started with this which returns a match of Try without matching End Try.
~(End )Try\n
Then, I wanted to get a match where there was Finally:
~(End )Try\n*Finally\n
This actually doesn't work.
The full, working Regex, I assume would look something like this:
~(End )(Sub|Function)*~(End )Try\n*~(Catch*\n)*Finally\n*End (Sub|Function)
That's try trying to say, within a Sub Or Function, return matches that have Try/Finally but no Catch.
Am I in the ballpark for accomplishing this search?
-3998271 0There is no difference in reading standard input from threads except if more than one thread is trying to read it at the same time. Most likely your threads are not all calling functions to read standard input all the time, though.
If you regularly need to read input from the user you might want to have one thread that just reads this input and then sets flags or posts events to other threads based on this input.
If the kill character is the only thing you want or if this is just going to be used for debugging then what you probably want to do is occasionally poll for new data on standard input. You can do this either by setting up standard input as non-blocking and try to read from it occasionally. If reads return 0 characters read then no keys were pressed. This method has some problems, though. I've never used stdio.h functions on a FILE *
after having set the underlying file descriptor (an int) to non-blocking, but suspect that they may act odd. You could avoid the use of the stdio functions and use read
to avoid this. There is still an issue I read about once where the block/non-block flag could be changed by another process if you forked and exec-ed a new program that had access to a version of that file descriptor. I'm not sure if this is a problem on all systems. Nonblocking mode can be set or cleared with a 'fcntl' call.
But you could use one of the polling functions with a very small (0) timeout to see if there is data ready. The poll
system call is probably the simplest, but there is also select
. Various operating systems have other polling functions.
#include <poll.h> ... /* return 0 if no data is available on stdin. > 0 if there is data ready < 0 if there is an error */ int poll_stdin(void) { struct pollfd pfd = { .fd = 0, .events = POLLIN }; /* Since we only ask for POLLIN we assume that that was the only thing that * the kernel would have put in pfd.revents */ return = poll(&pfd, 1, 0); }
You can call this function within one of your threads until and as long as it retuns 0 you just keep on going. When it returns a positive number then you need to read a character from stdin to see what that was. Note that if you are using the stdio functions on stdin
elsewhere there could actually be other characters already buffered up in front of the new character. poll
tells you that the operating system has something new for you, not what C's stdio has.
If you are regularly reading from standard input in other threads then things just get messy. I'm assuming you aren't doing that (because if you are and it works correctly you probably wouldn't be asking this question).
-6659250 0protobuf.net has to maintain compatibility with the protobuf binary format, which is designed for the Java date/time datatypes. No Kind
field in Java -> No Kind
support in the protobuf binary format -> Kind
not transferred across the network. Or something along those lines.
As it turns out, protobuf.net encodes the Ticks
field (only), you'll find the code in BclHelpers.cs
.
But feel free to add another field in your protobuf message definition for this value.
-9369592 0Given that a family tree application has more to do with relationships between entities than the entities themselves, modeling this in a relational database would be the better fit.
I release this does not answer your question, but at the end of the day we need to choose the most appropriate tool for the task.
-32066748 0The statement $scope.messages = messageOptions.slice(0, messageOptions.length);
create a clone/copy of array and assigning it to $scope.messages
You can also achieve same using
$scope.messages = messageOptions.slice();
Code to demonstrate
var messageOptions = [1, 2]; var messages = messageOptions.slice(0, messageOptions.length); //Update messageOptions[0] = 100; snippet.log("messages: " + JSON.stringify(messages)); snippet.log("messageOptions: " + JSON.stringify(messageOptions));
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Here's what I would do, making use of a Person
class. It may not seem necessary right now given the scope of your project, but if the scope ever grows, using classes and instances will pay off. Plus, this way, you have the names to match the ages you're seeking which is probably going to be necessary at some point anyway.
public static List<Person> GetResults(string[] text) { var results = new List<Person>(); foreach(var line in text) { results.Add(Person.Parse(line)); } return results; } public class Person { public string Name { get; private set; } public int Age { get; private set; } public Person(string name, int age) { Name = name; Age = age; } public static Person Parse(string fromInputLine) { ValidateInput(fromInputLine); var delimPosition = fromInputLine.LastIndexOf(' '); var name = fromInputLine.Substring(0, delimPosition); var age = Convert.ToInt32(fromInputLine.Substring(delimPosition + 1)); return new Person(name, age); } private static void ValidateInput(string toValidate) { if (!System.Text.RegularExpressions.Regex.IsMatch(toValidate, @"^.+\s+\d+$")) throw new ArgumentException(string.Format(@"The provided input ""{0}"" is not valid.", toValidate)); } }
-10090013 0 This is a relly good tutorial about UIScrollView&IPageControl combination. But I my self look for a tutorail for more dynamic designs(like main page of ios applications-i increments-decrements automatically)
-4108113 0 php fopen: failed to open stream: HTTP request failed! HTTP/1.0 403I am receiving an error message in PHP 5 when I try to open a file of a different website. So the line
fopen("http://www.domain.com/somefile.php", r)
returns an error
-30911184 0 Running use ant in javaWarning: fopen(www.domain.com/somefile.php) [function.fopen]: failed to open stream: HTTP request failed! HTTP/1.1 403 Forbidden in D:\xampp\htdocs\destroyfiles\index.php on line 2
Both compilation and JAR file creation is sucessful.
Running java file through ant file is producing error.
<project> <target name="clean"> <delete dir="build"/> </target> <target name="compile"> <mkdir dir="build/classes"/> <javac srcdir="src" destdir="build/classes"/> </target> <target name="jar"> <mkdir dir="build/jar"/> <jar destfile="build/jar/Helloworld" basedir="build/classes"> <manifest> <attribute name="Main-Class" value="Helloworld"/> </manifest> </jar> </target> <target name="run"> <java jar="build/jar/Helloworld" fork="true"/> </target> </project>
Buildfile: C:\Workspace\anttest\build.xml
run: [java] java.lang.NoClassDefFoundError: Helloworld [java] Caused by: java.lang.ClassNotFoundException: Helloworld [java] at java.net.URLClassLoader$1.run(URLClassLoader.java:202) [java] at java.security.AccessController.doPrivileged(Native Method) [java] at java.net.URLClassLoader.findClass(URLClassLoader.java:190) [java] at java.lang.ClassLoader.loadClass(ClassLoader.java:306) [java] at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) [java] at java.lang.ClassLoader.loadClass(ClassLoader.java:247) [java] Could not find the main class: Helloworld. Program will exit. [java] Exception in thread "main" [java] Java Result: 1
BUILD SUCCESSFUL
-4645070 0This is happening because the user 'sarin' is the actual owner of the database "dbemployee" - as such, they can only have db_owner, and cannot be assigned any further database roles.
Nor do they need to be. If they're the DB owner, they already have permission to do anything they want to within this database.
(To see the owner of the database, open the properties of the database. The Owner is listed on the general tab).
To change the owner of the database, you can use sp_changedbowner or ALTER AUTHORIZATION (the latter being apparently the preferred way for future development, but since this kind of thing tends to be a one off...)
-17732610 0This is just the way it is. first
and last
are not a complementary pair of operations. last
is more closely related to rest
and nthcdr
. There is also butlast
which constructs a new list that omits the last item from the given list.
first
versus last
is nothing compared to how get
and getf
have nothing to do with set
and setf
.
You can overcome this easily by using the ChoiceMode
option CHOICE_MODE_MULTIPLE
for the ListView
as used in the API Demo -
public class List11 extends ListActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, GENRES)); final ListView listView = getListView(); listView.setItemsCanFocus(false); listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); } private static final String[] GENRES = new String[] { "Action", "Adventure", "Animation", "Children", "Comedy", "Documentary", "Drama", "Foreign", "History", "Independent", "Romance", "Sci-Fi", "Television", "Thriller" }; }
EDIT Alternate for your context- Have an extra boolean object with your HashMap<String, Object>
isChecked
and initialize it to false when you populate your list
.
Set your CheckBox
in getView()
method as-
check.setChecked(Boolean.parseBoolean(dataMap.get("isChecked"));
Now in the listener OnCheckedChangeListener()
set the value of your dataMap
true or false accordingly.
JSON string values should be quoted and so should parameter expansions. You can achieve this by using double quotes around the entire JSON string and escaping the inner double quotes, like this:
curl -i -H "Content-Type: application/json" -X POST -d "{\"mountpoint\":\"$final\"}" http://127.0.0.1:5000/connect
-1784093 0 Get Application Pool Uptime in c# Is there a way I can determine how long an application pool (in IIS7) has been up (time since started, or last restart) in c#?
-7790366 0If you run your regex snippet in a C# program, I have the solution for you:
Regex regex = new Regex(@"(?<=\{{1}[\s\r\n]*)((?<Attribute>[^}:\n\r\s]+):\s+(?<Value>[^;]*);[\s\r\n]*)*(?=\})"); regex.Replace(input, match => { var replacement = string.Empty; for (var i = 0; i < match.Groups["Attribute"].Captures.Count; i++) { replacement += string.Format(CultureInfo.InvariantCulture, "{0}: {1}\r\n", match.Groups["Attibute"].Captures[i], match.Groups["Value"].Captures[i]); } return replacement; });
-39913248 0 OpenCV uses by default the now very uncommon BGR (blue, green, red) ordering of the color channels. Normal is RGB.
Why OpenCV Using BGR Colour Space Instead of RGB
This could explain the bad performance of the model.
-29143825 0 No SCM URL was provided to perform the release fromI am trying to use maven release plugin and after that automate this using nexus.
Here is my pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.ozge.net</groupId> <artifactId>com.ozge.net</artifactId> <version>1.1- snapshot</version> <build> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-release-plugin</artifactId> <version>2.5.1</version> <configuration> <tagBase>svn://local/exekuce/com.ozge.net</tagBase> </configuration> </plugin> </plugins> </pluginManagement> </build> <scm> <tag>HEAD</tag> <connection>scm:svn:svn://[svnusername]:[svn password]@local/exekuce/com.ozge.net</connection> <developerConnection>scm:svn:svn://[svnusername]:[svn password]@local/exekuce/com.ozge.net</developerConnection> <url>scm:svn:svn://[svnusername]:[svn password]@local/exekuce/com.ozge.net</url> </scm> <distributionManagement> <repository> <id>OzgeRelease</id> <url>http://localhost:8081/nexus/content/repositories/OzgeRelease</url> </repository> </distributionManagement> </project>
after I ran the command mvn release:perform
on command prompt
it says
No SCM URL was provided to perform the release from
I believe I provided.
Anybody here tried to maven-subversion-nexus-hudson for automating builds?
-8087446 0here you are
$("#bxs").on('click', 'li',function() { var exists = false for(var i=0;i<result.length;i++) { var item = result[i]; if(item.id == $(this).prop("id")) { exists = true; break; } } if(exists) { alert("exists"); } else { alert("doesn't exists"); } });
-22901149 0 if ($contract['Contract']['contract_maandag'] = 1){ if ($contract['Contract']['contract_dinsdag'] = 1){
This won't work. You're doing an assignment (=), so it's always true. But you want a comparison (===). It is recommended to do always (except required otherwise) to use strict (===) comparison.
-48508 0I can only once again point to Stroustrup and preach: Don't teach the C subset! It's important, but not for beginners! C++ is complex enough as it is and the standard library classes, especially the STL, is much more important and (at least superficially) easier to understand than the C subset of C++.
Same goes for pointers and heap memory allocation, incidentally. Of course they're important but only after having taught the STL containers.
Another important concept that new students have to get their head around is the concept of different compilation units, the One Definition Rule (because if you don't know it you won't be able to decypher error messages) and headers. This is actually quite a barrier and one that has to be breached early on.
Apart from the language features the most important thing to be taught is how to understand the C++ compiler and how to get help. Getting help (i.e. knowing how to search for the right information) in my experience is the single most important thing that has to be taught about C++.
I've had quite good experiences with this order of teaching in the past.
/EDIT: If you happen to know any German, take a look at http://madrat.net/coding/cpp/skript, part of a very short introduction used in one of my courses.
-6675225 0 Advantages of using Passenger + Apache over WebrickI want to convince my management that using Apache + passenger setup is way to go on production rather than having webrick or mongrel
I have found some points from the net.
It would be great help if you could add your thoughts as that will defiantly help me to present my points. (technical details are welcome)
and It will great if you could send some links if you have any
thanks in advance
cheers
sameera
-36609262 0You have two class attributes on each of your menu items. The second one is being ignored by jQuery.
<a class="list-group-item allnotif" href="#allnotif"><strong>Alle Notificaties</strong></a>
-33999562 0 You should use ArrayList
rather than Vector
. There is no simple way to convert though. One way is
ArrayList<String> list = new ArrayList<String>(); for (char a : x) list.add(String.valueOf(a));
Arrays.asList
works for arrays of object references, not arrays of primitives like char
.
If you are using Java 8, another way is
List<String> list = IntStream.range(0, x.length) .mapToObj(i -> String.valueOf(x[i])) .collect(Collectors.toList());
-5093338 0 Thinking in high level, this is what I'd do:
Develop a decorator function, with which I'd decorate every event-handling functions.
This decorator functions would take note of thee function called, and its parameters (and possibly returning values) in a unified data-structure - taking care, on this data structure, to mark Widget and Control instances as a special type of object. That is because in other runs these widgets won't be the same instances - ah, you can't even serialize a toolkit widget instances, be it Qt or otherwise.
When the time comes to play a macro, you fill-in the gaps replacing the widget-representating object with the instances of the actually running objects, and simply call the original functions with the remaining parameters.
In toolkits that have an specialized "event" parameter that is passed down to event-handling functions, you will have to take care of serializing and de-serializing this event as well.
I hope this can help. I could come up with some proof of concept code for that (although I am in a mood to use tkinter today - would have to read a lot to come up with a Qt4 example).
-15875144 0use
$this->m_user->delete($user_id);
Instead
$this->m_user->delete_user($user_id);
-9779994 0 I just need someone to help me with a tiny actionscript error I've made the hourly wages calculator, but there is one problem: I can't get it to calculate anything, so if you were to use this program; you would add your name, hours worked and wages. once you click the button, at the bottom with have your results.
i'm trying to get it to say hi, "the person's name" you have this much... something like that.
can anyone help me?
thanks
here is my code:
button.mouseChildren = false button.addEventListener(MouseEvent.CLICK, onClick); } private function onClick(event:MouseEvent):void { this.results.text = "Hi, " } } }
-9628155 0 What i would do is look at it in an Object Oriented Perspective, which is what Java is all about. When i get stuck on a piece of code then i write it down. Think of what the objective of the code is.
You probably have a class called Level. In this level class you could have a property called "unlocked" or the opposite "locked". Then when the user goes to your "play a level" screen or what have you, then only allow the user to see the levels that are unlocked.
You also probably have a Player class of some sort so you could have a property called "unlockedLevels" which is of the type Level[]. So then all of the unlocked levels would be in this array of Levels.
It is all about how your code is structured, structure and true Object Orientation are the most important things in Java. When you stray from Object Oriented Design then you can run into problems that should never have existed.
-978043 0A module in the Python natural language toolkit (nltk) does naïve Bayesian classification: nltk.classify.naivebayes
.
Disclaimer: I know crap all about Bayesian classification, naïve or worldly.
-20799086 0I finally chose to use websockets to solve my problem (with Ratchet). Like this, I can invoke my script from my browser passing the arguments I need to the executable file.
PHP in CLI doesn't seem to have any problem with exec() on .exe files.
-32746403 0 Groovy script to transform xml to jsonI have the following groovy script that transforms an xml into json.
http://stackoverflow.com/a/24647389/2165673
Here is my xml
<?xml version="1.0" encoding="utf-8"?> <Response xmlns=""> <ProgressResult xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <ErrorMessage>error </ErrorMessage> <IsSuccessful>false</IsSuccessful> </ProgressResult> </ProgressResponse>
The JSON result i need is
{ "IsSuccessful" : "false", "ErrorMessage" : "Something Happened" }
but i am getting the following http://www.tiikoni.com/tis/view/?id=b4ce664
I am trying to improve my groovy script but i just started using it and it has a steep learning curve. Can someone help direct me to the right direction?
Thanks!!
-20498360 0 Android logcat errors on projectI'm trying to run a project in Android but it crashes upon trying to execute it: I don't really understand the logCat messages I get so I wanted to see if someone could help me out in understanding them.
Here are some of my errors:
FATAL EXCEPTION: MAIN java.lang.RunTimeException: Unable to start activity componentInfo (com.example.logger/com.example.logger.ThirdActivity):java.lang.RuntimeException: your content must have a ListView whose id attribe is 'android.R.id.list'; Caused by: java.lang.RuntimeException: your content must have a ListView whose id attribute is 'android.R.id.list'; at.com.example.logger.ThirdActivity.onCreate (ThirdActivity:java:18)
Android Manifest
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.logger" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="18" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.logger.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.example.logger.SecondActivity" android:label="@string/title_activity_second" ></activity> <activity android:name="com.example.logger.ThirdActivity" android:label="@string/title_activity_third" > </activity> </application> </manifest>
End manifest
Main Activity
package com.example.logger; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; public class MainActivity extends Activity implements OnClickListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); attachHandlers(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } private void attachHandlers() { findViewById(R.id.login).setOnClickListener(this); } @Override public void onClick(View arg0) { if(arg0.getId() == R.id.login) { Intent i = new Intent(this, SecondActivity.class); startActivity(i); } }
}
End Main Activity
SecondActivity
package com.example.logger; import android.os.Bundle; import android.annotation.SuppressLint; import android.app.Activity; import android.app.Fragment; import android.app.FragmentManager; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.widget.ImageView; import android.view.ViewGroup; public class SecondActivity extends Activity { private static final int NUM_PAGES = 10; private ViewPager mpager; private MyPagerAdapter mPagerAdapter; private int [] pics = {R.drawable.android_interfaz_layout_estructura_final, R.drawable.baixa, R.drawable.baixada, R.drawable.greenprogressbar, R.drawable.layout_keyboard, R.drawable.linerlay, R.drawable.merge1, R.drawable.o2zds, R.drawable.regbd, R.drawable.s7qrs}; @SuppressLint("NewApi") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); mPagerAdapter = new MyPagerAdapter(null); mpager = (ViewPager) findViewById(R.id.viewer); mpager.setAdapter (mPagerAdapter); } public void showImage (int position, View view) { //View is your view that you returned from instantiateItem //and position is it's position in array you can get the image resource id //using this position and set it to the ImageView } private class MyPagerAdapter extends PagerAdapter { SecondActivity activity; public MyPagerAdapter (SecondActivity activity){ this.activity=activity; } @Override public int getCount() { // TODO Auto-generated method stub return pics.length; } @Override public boolean isViewFromObject(View arg0, Object arg1) { // TODO Auto-generated method stub return false; } @Override public Object instantiateItem(View collection, int position) { ImageView view = new ImageView (SecondActivity.this); view.setImageResource (pics[position]); ((ViewPager) collection).addView(view, 0); return view; } @Override public void setPrimaryItem (ViewGroup container, int position, Object object) { super.setPrimaryItem (container, position, object); activity.showImage(position,(View)object); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.second, menu); return true; } private OnClickListener mPageClickListener = new OnClickListener() { public void onClick (View v) { // TODO Auto-generated method stub //aquí anirà la funció per traslladar la image de la gallery a la pantalla Integer picId = (Integer) v.getTag(); mpager.setVisibility(View.VISIBLE); mpager.setCurrentItem(v.getId()); } @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub } };
}
End Second Activity
Third Activity
package com.example.logger; import android.os.Bundle; import android.app.Activity; import android.app.ListActivity; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; public class ThirdActivity extends ListActivity implements OnClickListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_third); final ListView listview = (ListView) findViewById(android.R.id.list); String[] values = new String[] {"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen", "Twenty"}; ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.activity_third, android.R.id.list, values); setListAdapter(adapter); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.third, menu); return true; } public void attachButton() { findViewById(R.id.add).setOnClickListener(this); } @Override public void onClick(View v) { // TODO Auto-generated method stub }
}
End Third Activity
Activity_Main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:orientation="vertical" tools:context=".MainActivity" > <Button android:id="@+id/login" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/Login" android:layout_alignParentBottom="true" android:background="@drawable/shapes" android:textColor="@color/text" /> <EditText android:id="@+id/username" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/input_u" android:layout_marginTop="10dp" android:textColor="@color/text" /> <EditText android:id="@+id/password" android:layout_below="@+id/username" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/input_p" android:layout_marginTop="10dp" android:textColor="@color/text" /> </RelativeLayout>
End Activity_Main.xml
Activity_Second.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".SecondActivity" > <android.support.v4.view.ViewPager android:padding="16dp" android:id="@+id/viewer" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:layout_weight="0.70" /> <ImageView android:id="@+id/big_image" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:layout_below="@+id/viewer" android:layout_weight="0.30" /> </RelativeLayout>
End Activity_Second.xml
**Activity_Third.xml** <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".ThirdActivity" > <Button android:id="@+id/add" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:text="@string/add" /> <ListView android:id="@+id/list" android:layout_width="match_parent" android:layout_below="@+id/add" android:layout_height="wrap_content" ></ListView> </RelativeLayout>
End Activity_Third.xml
I'd very grateful if someone could help me figure out what I'm doing wrong on this project.
Yours sincerely,
Mauro.
-5198155 0 Not all tiles redrawn after CATiledLayer -setNeedsDisplayMy view has a CATiledLayer
. The view controller has custom zooming behavior, so on -scrollViewDidEndZooming
every tile needs to be redrawn. But, even though -setNeedsDisplay
is being called on the layer after every zoom, not all tiles are being redrawn. This is causing the view to sometimes look wrong after a zoom. (Things that should appear in just 1 tile are appearing in multiple places). It often corrects itself after another zoom.
Here's the relevant code. updatedRects
is for testing -- it stores the unique rectangles requested to be drawn by -drawLayer
.
CanvasView.h:
@interface CanvasView : UIView @property (nonatomic, retain) NSMutableSet *updatedRects; @end
CanvasView.m:
@implementation CanvasView @synthesize updatedRects; + (Class)layerClass { return [CATiledLayer class]; } - (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)context { CGRect rect = CGContextGetClipBoundingBox(context); [updatedRects addObject:[NSValue valueWithCGRect:rect]]; CGContextSaveGState(context); CGContextTranslateCTM(context, rect.origin.x, rect.origin.y); // ...draw into context... CGContextRestoreGState(context); } @end
MyViewController.m:
@implementation MyViewController - (void)viewDidLoad { [super viewDidLoad]; canvasView.updatedRects = [NSMutableSet set]; } - (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)scale { canvasView.transform = CGAffineTransformIdentity; canvasView.frame = CGRectMake(0, 0, canvasView.frame.size.width * scale, canvasView.frame.size.height); [self updateCanvas]; } - (void)updateCanvas { NSLog(@"# rects updated: %d", [canvasView.updatedRects count]); [canvasView.updatedRects removeAllObjects]; canvasView.frame = CGRectMake(canvasView.frame.origin.x, canvasView.frame.origin.y, canvasView.frame.size.width, myHeight); CGFloat tileSize = 256; NSLog(@"next # rects updated will be: %f", [canvasView.layer bounds].size.width / tileSize); [canvasView.layer setNeedsDisplay]; } @end
When testing this, I always scrolled all the way across the view after zooming to make sure every tile was seen. Whenever the view looked wrong, the predicted "next # of rects updated" was greater than the actual "# of rects updated" on the next call to -updateCanvas
. What would cause this?
Edit:
Here's a better way to visualize the problem. Each time updateCanvas
is called, I've made it change the background color for drawing tiles and record the time it was called -- the color and time are stored in canvasView
. On each tile is drawn the tile's rectangle, the tile's index along the x axis, the time (sec.) when the background color was set, and the time (sec.) when the tile was drawn. If everything is working correctly, all tiles should be the same color. Instead, here's what I'm sometimes seeing:
I only seem to see wrong results after zooming out. The problem might be related to the fact that (Edit: No-- not called multiple times.) scrollViewDidEndZooming
, and therefore updateCanvas
, can get called multiple times per zoom-out.
If you are running Time Machine on Leopard (OS X 10.5) then you have a chance that the files are in the backup. By default Time Machine backs up every hour so unless the files were created and deleted between backups then you should have something.
-28711174 0 Showing message after customer is redirected to logout page magentoI have a problem here. I want to show a message to the customer after his/her session is out. Let me explain in detail. I have a case, at first the customer is logged in when the customer clicks the "My Account" he/she is redirected to customer login page.Here i want to show the message that "your session is out please log in again".
One method i tried is to check the customer session in indexAction() in AcountController.php but this redirection is not taking place from this indexAction().
I am guessing that this redirection is taking somewhere from the block because "My Account" link is added through the xml file using "addLink" method.But i couldn't figure it out.
Has anyone faced such problem and has solved it. Can anyone provide me with some insights so i can fix it.
-20752692 0HTML
<div id='mydiv'>Lorem<span> ipsum</span> dolor amet</div>
JS/Jquery
var elm = $('#mydiv'); highlite(elm, 2, 28); //specify the start and end position // if you know the word you can find the index of word using indexOf/lastIndexOf function highlite(element, startpos, endpos) { var rgxp = elm.html().substr(startpos,endpos) var repl = '<span class="myClass">' + rgxp + '</span>'; elm.html(elm.html().replace(rgxp, repl)); }
Demo
http://jsfiddle.net/raunakkathuria/sD2pX/
-22358491 0HANDLE_MSG macro is defined in Windowsx.h header.
Note: To use message cracker for WM_NOTIFY you must use HANDLE_WM_NOTIFY macro defined in commctrl.h header.
-32731041 0You should create a variable containing the \n:
(bind ?newline " ")
and then use it in str-cat or sym-car or other places.
(bind ?a (sym-cat ?a ?newline))
-32560451 0 Maybe what you want is like this :
public void startApp(){ primaryStage.show(); new Thread(new Runnable(){ @Override public void run() { try { Thread.sleep(20000);//2 seconds } catch (InterruptedException e) { e.printStackTrace(); } //do something......... System.out.println("all things done"); } }).run(); }
You need to implement the method run()
of Runnable
I am trying to make an API call to the address: apps.smilemachine.com/smilefactory/api/v1.0/speedup. I just want to execute the url (above) so that it increments the machine and changes the speed value stored at Smilemachine.com? Nothing special I just need to execute the url as if you were typing it into the address bar in any browser?
Has anyone got any advice for this or code snippets?
My current code just opens the browser, please find below:
increasespeed.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Intent increasespeed = new Intent(null, Uri.parse("http://apps.smilemachine.com/smilefactory/api/v1.0/speedup")); startActivity(increasespeed); } });
-2935604 0 Qt cross thread call I have a Qt/C++ application, with the usual GUI thread, and a network thread. The network thread is using an external library, which has its own select() based event loop... so the network thread isn't using Qt's event system.
At the moment, the network thread just emit()s signals when various events occur, such as a successful connection. I think this works okay, as the signals/slots mechanism posts the signals correctly for the GUI thread.
Now, I need for the network thread to be able to call the GUI thread to ask questions. For example, the network thread may require the GUI thread to request put up a dialog, to request a password.
Does anyone know a suitable mechanism for doing this?
My current best idea is to have the network thread wait using a QWaitCondition, after emitting an object (emit passwordRequestedEvent(passwordRequest);
. The passwordRequest object would have a handle on the particular QWaitCondition, and so can signal it when a decision has been made..
Is this sort of thing sensible? or is there another option?
-6362068 0This website is answer to my question: http://embed.ly/ :)
-15532242 0 error while installing WindowBuilder Pro Update Site - http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7I faced this error while installing http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7 on eclipse Juno Service Release 1
An error occurred while collecting items to be installed session context was:(profile=epp.package.jee, phase=org.eclipse.equinox.internal.p2.engine.phases.Collect, operand=, action=). Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer_2.6.0.r37x201206111227.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.GWTExt_2.6.0.r37x201206111253.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.GXT_2.6.0.r37x201206111253.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.GXT.databinding_2.6.0.r37x201206111253.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.SmartGWT_2.6.0.r37x201206111253.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.UiBinder_2.6.0.r37x201206111227.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.UiBinder.wizards_2.6.0.r37x201206111253.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.doc.user_2.6.0.r37x201206111253.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/features/com.google.gdt.eclipse.designer.editor.feature_2.6.0.r37x201206111227.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/features/com.google.gdt.eclipse.designer.feature_2.6.0.r37x201206111253.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.hosted_2.6.0.r37x201206111222.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.hosted.2_0_2.6.0.r37x201206111222.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.hosted.2_0.super_2.6.0.r37x201206111222.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.hosted.2_0.webkit_2.6.0.r37x201206111222.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.hosted.2_0.webkit_win32x64_2.6.0.r37x201206111222.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.hosted.2_2_2.6.0.r37x201206111222.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.hosted.2_2.webkit_2.6.0.r37x201206111222.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/features/com.google.gdt.eclipse.designer.hosted.feature_2.6.0.r37x201206111222.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.hosted.lib_2.6.0.r37x201206111222.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.launch_2.6.0.r37x201206111253.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.preferences_2.6.0.r37x201206111253.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.wizards_2.6.0.r37x201206111253.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/org.eclipse.wb.rcp_1.5.0.r37x201206111317.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/org.eclipse.wb.rcp.GroupLayout_1.5.0.r37x201206111330.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/features/org.eclipse.wb.rcp.GroupLayout_support.feature_1.5.0.r37x201206111330.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/org.eclipse.wb.rcp.SWT_AWT_1.5.0.r37x201206111333.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/features/org.eclipse.wb.rcp.SWT_AWT_support_1.5.0.r37x201206111333.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/org.eclipse.wb.rcp.databinding_1.5.0.r37x201206111317.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/org.eclipse.wb.rcp.databinding.emf_1.5.0.r37x201206111317.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/org.eclipse.wb.rcp.databinding.xwt_1.5.0.r37x201206111323.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/org.eclipse.wb.rcp.doc.user_1.5.0.r37x201206111236.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/features/org.eclipse.wb.rcp.doc.user.feature_1.5.0.r37x201206111236.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/features/org.eclipse.wb.rcp.feature_1.5.0.r37x201206111317.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/org.eclipse.wb.rcp.nebula_1.5.0.r37x201206111317.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/org.eclipse.wb.rcp.swing2swt_1.5.0.r37x201206111317.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/org.eclipse.wb.swt_1.5.0.r37x201206111304.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/features/org.eclipse.wb.swt.feature_1.5.0.r37x201206111304.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/org.eclipse.wb.swt.layout.grouplayout_1.5.0.r37x201206111330.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/org.eclipse.wb.swt.widgets.baseline_1.5.0.r37x201206111317.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/org.eclipse.wb.xwt_1.5.0.r37x201206111323.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/features/org.eclipse.wb.xwt.feature_1.5.0.r37x201206111323.jar dl.google.com
-37482250 0 Dropdown menu isn't working I'm doing a Menu where it has four dropdown buttons that aren't working. The following image shows how it is supposed to work: "Bijutaria=(perfumes+fios)"
"Inserir=(Perfumes=homem+mulher)+Bijutaria=fios+pulseiras)"
I think the problem is located in my CSS code, but I'm not being able to figure out what the problem is.
ul { margin: 0; padding: 0; list-style: none; width: 150px; } ul li { position: relative; } li ul { position: absolute; left: 120px; top: 0; display: none; } ul li a { display: block; text-decoration: none; color: #E2144A; background: #fff; padding: 5px; border: 1px solid #ccc; } li:hover ul { display: block; }
<ul id="left" class='column'> <li><a href="ver.php">Home</a></li> <li><a href="#">Bijutaria</a></li> <ul> <li><a href="pulseiras.php">Pulseiras</a> </li> <li><a href="fios.php">Fios</a> </li> </ul> <li><a href="#">Perfumes</a> <ul> <li><a href="prfh.php">Homem</a></li> <li><a href="prfm.php">Mulher</a></li> </ul> <li><a href="#">Inserir</a></li> <ul> <li><a href="#">Perfumes</a></li> <ul> <li><a href="insrph.php">Homem</a></li> <li><a href="insrpm.php">Mulher</a></li> </ul> <li><a href="#">Bijutaria</a></li> <ul> <li><a href="insrp.php">Pulseiras</a></li> <li><a href="insrf.php">Fios</a></li> </ul> </ul> </li> </ul>
Where you will have a problem is when find descends into subdirectories, and it tries to exec something like cp ./foo/bar.txt /new/path/./foo/bar.txt
and "/new/path" has no subdirectory "foo" -- you might want to:
specify -maxdepth 1
so you do not descend into subdirs
find . -maxdepth 1 -type f -exec cp {} /new/path/{} \;
just use a directory destination for cp
, so the files end up in a single dir (will suffer from collisions if you have "./foo/bar.txt" and "./qux/bar.txt")
find . -type f -exec cp -t /new/path {} +
use tar
to copy the whole tree: this will preserve directory structure
tar cf - . | ( cd /new/path && tar xvf - )
Have you tried FQL? Using this I was able to get users display pictures on any site I wanted by simply constructing a simple SQL like query.
-2228489 0 image thumb list with opacity changes and add class/remove class on clickI got the script from another post on here, but for some reason it isn't working quite correctly on my implementation of it. Everything works fine except for stripping of the "selected" class, therefore the thumbnails all stay highlighted after being clicked. Easiest way is to show in context:
http://www.studioimbrue.com/beta
I changed it around a bit trying to figure out the problem but I couldn't find anything.
-663380 0This is going to sound strange, but does the view/table have a column named "1"?
-12896034 0LESS provides the ability to use previously defined classes as mixins in other contexts. Try this:
.theme-dark { .navbar { .navbar-inverse; } }
-26383784 0 View not refreshing following post in Razor MVC using datatable As per subject. The view looks like this.
@using System.Globalization @model IEnumerable<TaskEngine.WebUI.Models.TaskViewModel> <script src="../../Scripts/progress-task.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function () { $.ajax({ url: '@Url.Action("Index", "Home")', data: { from: "10/01/2014", to: "10/14/2014" }, dataType: "html", success: function () { alert('Success'); }, error: function (request) { alert(request.responseText); } }); }); </script> <div class="container"> <div class="row"> <div class="span16"> <div id="sitename"> <a href="/" id="logo">xxxxxxxx</a> <span class="name">Workbasket</span> </div> <div class="row"> <div class="span16"> <table class="table table-striped table-condensed" id="task-table"> <thead> <tr> <th class="left">Client</th> <th class="left">Task</th> <th class="left">State</th> <th class="left">Assigned By</th> <th class="left">Assigned To</th> <th class="left">Date Opened</th> <th class="left">Date Due</th> @* <th class="left">Date Closed</th>*@ <th class="left">Outcomes</th> </tr> </thead> <tbody> @foreach (var task in Model) { <tr> <td><span>@task.ClientId</span></td> <td><span class="nowrap">@task.TaskDescription</span></td> <td><span class="nowrap">@task.CurrentState</span></td> <td><span >@task.AssignedBy.Replace("CORPORATE\\", "").Replace(@".", " ")</span></td> <td><span>@task.AssignedTo.Replace("CORPORATE\\", "").Replace(@".", " ")</span></td> <td><span>@task.DateOpened.ToString("dd/MM/yyyy HH:mm")</span></td> <td><span>@task.DateDue.ToString("dd/MM/yyyy HH:mm")</span></td> @* <td><span>@(task.DateClosed.HasValue ? task.DateClosed.Value.ToShortDateString() : " - ")</span></td>*@ <td> <span class="nowrap"> @Html.DropDownList( "Outcomes", new SelectList(task.Outcomes, "Id", "Name"), "---Please Select ---", new Dictionary<string, object> { {"data-case-id", @task.CaseId }, {"data-task-log-id", @task.TaskLogId}, {"data-client-id", @task.ClientId} }) </span> </td> </tr> } </tbody> </table> </div> </div> </div> </div> <div class="modal hide span8" id="complete-task-modal" tabindex="-1" role="dialog" aria-labelledby="complete-task-header" aria-hidden="true"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h3 id="complete-task-header">Complete Task</h3> </div> <div class="modal-body"> <div class="row"> <div class="span8"> <div class="alert alert-info"> <label id="CurrentState"></label> <label id="NewState"></label> <label>Generated Tasks</label> <ul id="task-list"> </ul> </div> </div> </div> <form id="form"> <input type="hidden" id="task-log-id" name="taskLogId" /> <input type="hidden" id="case-id" name="caseId" /> <input type="hidden" id="outcome-id" name="triggerId" /> <input type="hidden" id="client-id" name="clientId" /> <div id="popup"> </div> </form> </div> <div class="modal-footer"> <button class="btn" id="close" data-dismiss="modal" aria-hidden="true">Go Back</button> <button class="btn btn-primary" id="confirm-task">Confirm</button> </div> </div> </div>
This is the controller method.
public ActionResult Index(DateTime? from, DateTime? to) { var usergroups = GetGroups(HttpContext.User.Identity.Name); var model = _taskLogger.GetTasks(from, to) .Select(task => new TaskViewModel { TaskLogId = task.TaskLogId, CaseId = task.CaseId, ClientId = task.ClientId, TaskDescription = task.Description, AssignedBy = task.AssignedBy, AssignedTo = task.AssignedTo.Trim(), DateOpened = task.DateCreated, DateClosed = task.DateClosed, DateDue = task.DateDue }).ToList() .Where(x => IsAvailableToUser(x.AssignedTo, usergroups)) .OrderBy(x => x.DateDue); foreach (var task in model) { var workflow = _workflowEngine.GetCase(task.CaseId); task.CurrentState = workflow.State.ToNonPascalString(); task.Outcomes = workflow.GetPermittedTriggers().OrderBy(x => x.Name).ToList(); } ModelState.Clear(); return View(model); }
When the model is returned following the ajax post, the dataset is different, as expected, however, within the datatable in the view it still displays the old data.
Having done some googling on this issue, I've tried clearing the modelstate but that makes no difference and from what I've read, it only seems to affect HTMLHelpers anyway.
I'm not sure if this is an issue with the datatable or just a refresh issue with the view itself. Any input would be appreciated.
-1328836 0 How can I include line numbers in a stack trace without a pdb?We are currently distributing a WinForms app without .pdb files to conserve space on client machines and download bandwidth. When we get stack traces, we are getting method names but not line numbers. Is there any way to get the line numbers without resorting to distributing the .pdb files?
-21550489 0Does it read the file while omitting the format argument?
x=read('g:\Work\WD\Debug\wd.txt',100,4)
I am suspecting it has something to do with your formatting string.
(5x,a2,3(5x,e12.4))
Maybe have a look here to learn more about Fortran format edit descriptors.
-29986258 0 How to render QuickBlox VideoStream into opponentVideoView and ownVideoView?I have to accept video call(QuickBlox) anywhere from the application. for this I have create a singleton class in which I have implemented few Quick Blox delegate method for receiving call. after receiving call i present user to VideoCallController. But I am unable to render VideoStream into opponanenVideoView and myVideoView. Can anyone suggest me where I have to set VideoChat Property either in Singleton or VideoCallController.
self.videoChat.viewToRenderOpponentVideoStream = opponentVideoView; self.videoChat.viewToRenderOwnVideoStream = myVideoView;
-28283134 0 Sounds easy enough. You just need to use jquery selectors to slice and dice to get the li into the correct position.
Take a look at nth-child() selector.
-40950774 0Remedy User Tool macro language is proprietary.
Since Remedy User Tool is not supported anymore, I'd encourage you to use updated technologies, like SOAP or REST (for everything back-end), or AngularJS (for everything front-end)
Another solution would be to use tools created by the Remedy Community, like the one appearing on https://communities.bmc.com/message/437693#437693
-31361842 0 Why layoutIfNeeded() allows to perform animation when updating constraints?I have two states of UIView
:
I have animation between them using @IBaction
for button
:
@IBAction func tapped(sender: UIButton) { flag = !flag UIView.animateWithDuration(1.0) { if self.flag { NSLayoutConstraint.activateConstraints([self.myConstraint]) } else { NSLayoutConstraint.deactivateConstraints([self.myConstraint]) } self.view.layoutIfNeeded() //additional line } }
Animation is working only when I add additional line:
But when I remove that line, then my UIView
is updated but without any animation, it happens immediately.
Why this line makes such difference? How is it working?
-10864824 0 Organizing my papers in org-modeI've just started using org-mode, and so far find it quite useful. I have a very large collection of technical papers in a directory tree, and I'd like to go through them and index them through org-mode. What I'd like is to have a way of going through them and look at the unannotated ones, and annotate them one by one. I imagine doing this by first making up a file of links like [[xxx.pdf][not done yet]], and then being presented with the not done ones, glancing at them and deciding how what annotations to put in. In addition I'd like to add tags. What I'd really like is to be able to make up new tags on the fly. Has anyone done anything like this in org-mode?
Victor
-24588828 0request.update("growl");
This is the wrong part.
Put an id to your form, then reference it like
i.e
request.update("your_for_mid:growl");
Alternatively you could activate the auto-update feature of the growl with the attribute autoUpdate="true"
of the growl component, and remove the request.update()
method call in your backing bean.
I am using excel 2013. I do not get any debug option when there is a runtime error. How can I get a debug option during runtime errors?
Edit - I have realized that I have this problem only in the following instance. Normally I am getting the debug option (except for this case). What is especially painful is that it doesn't even tell me which line the error is on.
screenshot of error -
Code is as follows -
Option Explicit Option Base 1 Sub doit() Dim intRowCounter As Long Dim intColCounter As Long Dim parentFormula As String Dim resultantFormulas As String For intRowCounter = 1 To 100 For intColCounter = 1 To 200 'This is the line giving the error parentFormula = Right(parentFormula, Len(parentFormula) - 1) Next intColCounter Next intRowCounter End Sub
Screenshot of the error http://imgur.com/gC32z74
well, you want to hide the fields in the gridfield detail form? that cannot be done in your pages getCMSFields()
, as the grid is responsible for generating the detail form. Two possible solutions:
1) tell the grid to hide that fields with a custom component. I dunno how to do it
2) tell your Rotator class to show the fields ONLY if the related page is a homepage:
public function getCMSFields() { $fields = parent::getCMSFields(); //...other stuff.... $isOnHomePage = ($this->Page() && $this->Page()->ClassName == 'HomePage'); //put in your own classname or conditions if(!$isOnHomePage) { //remove the fields if you're not on the HomePage $fields->removeByName('Body'); //we need to suffix with "ID" when we have a has_one relation! $fields->removeByName('BackGroundImageID'); } return $fields; }
-31238631 0 Refreshing html table using Jquery Java built on Codeigniter Guys I have a data coming from an outsource table which I'm presenting in table. The original data coming in Json which I'm decoding using PHP function and displaying.
I have been googling for auto refreshing that data and found this Auto refresh table without refreshing page PHP MySQL
I have managed to built what is suggested in the Ticked answers and seems like working for the first time but it doesn't refresh. So when page is loaded
I'm calling this
$(document).ready (function () { var updater = setTimeout (function () { $('div#user_table').load ('get_new_data', 'update=true'); /* location.reload(); */ }, 1000); });
Which loads a function named get_new_data from controller file and loads on to
<div class="container-fluid" id="user_table"> </div>
Codeigniter controller function is
public function get_new_data(){ $url = 'https://gocleanlaundry.herokuapp.com/api/users/'; $result = $this->scripts->get_data_api($url); $data_row = $result; $tbl = ''; $tbl .= '<table class="table table-striped table-responsive" id="tableSortableRes"> <thead> <tr> <th>Name</th> <th>Email Address</th> <th>Role</th> <th>Status</th> <th>Action</th> </tr> </thead> <tbody>'; foreach($data_row as $row){ $tbl .= '<tr class="gradeX"> <td>' . $row->name . '</td> <td>' . $row->email . '</td> <td>' . $row->role . '</td> <td><p id="' . $row->_id. '_status">'.( $row->alive == true ? 'Active' : 'Banned').' </p></td> <input id="' . $row->_id . 'status_val" value="' . $row->alive . '" type="hidden"> <td class="center"> <a href="#" id="' . $row->_id . '_rec" onclick="UpdateStatus(' . $row->_id . ')" class="btn btn-mini ">' . ($row->alive == '1' ? '<i class="fa fa-thumbs-o-up fa-fw"></i>' : '<i class="fa fa-thumbs-o-down fa-fw"></i>' ) . '</a> </td> </tr> '; } $tbl .= '</tbody> </table>'; echo $tbl; }
As I said when page loads is showing data so something is working but when I add new data to the database is doesn't automatically show up. I want function to call and refresh the data. Sorry I'm very new to javascript and jQuery so please go easy on me :)
Thank you guys
-9816460 0 Loop Design: Counting & Subsequent Code DuplicationExercise 3-3 in Accelerated C++ has led me to two broader questions about loop design. The exercise's challenge is to read an arbitrary number of words into a vector, then output the number of times a given word appears in that input. I've included my relevant code below:
string currentWord = words[0]; words_sz currentWordCount = 1; // invariant: we have counted i of the current words in the vector for (words_sz i = 1; i < size; ++i) { if (currentWord != words[i]) { cout << currentWord << ": " << currentWordCount << endl; currentWord = words[i]; currentWordCount = 0; } ++currentWordCount; } cout << currentWord << ": " << currentWordCount << endl;
Note that the output code has to occur again outside the loop to deal with the last word. I realize I could move it to a function and simply call the function twice if I was worried about the complexity of duplicated code.
Question 1: Is this sort of workaround is common? Is there a typical way to refactor the loop to avoid such duplication?
Question 2: While my solution is straightforward, I'm used to counting from zero. Is there a more-acceptable way to write the loop respecting that? Or is this the optimal implementation?
-13754000 0Is there a reason you were using Request.Form
? You should use
Guid myGuid = Guid.Parse(GuidToken.Value);
If you still want to use Request.Form which I would not recommend, the name of the hidden field control has been changed by asp.net so the collection does not contain exactly what you specified because it has some autogenerated naming convention added to it. It now looks like this
Request.Form["ctl00$MainContent$GuidToken"]
Debug mode
As a workaround, download data per day and define weeks in alignment with your measurements from the other dataset. Now Aggregate the Trends data. In case you are dealing with more than 3 months worth of data, consider to rescale your segments beforehand as described here: http://erikjohansson.blogspot.de/2014/12/creating-daily-search-volume-data-from.html http://erikjohansson.blogspot.de/2014/05/daily-google-trends-data-using-r.html
-13914974 0I recommend you read about CSS a little, here is a good example of centering anything.
http://www.w3.org/Style/Examples/007/center.en.html
-36159118 0 Guava EventBus - FIFO or LIFO?This is a very generic question on EventBus. Does the EventBus exhibit a FIFO or LIFO behavior? I am using the EventBus as a Java event "queuing" mechanism and seeing LIFO behavior when a single publisher publishes events to the EventBus faster than the Subscriber can handle.
-34755958 0The difference is caused by doSomeY
yielding a number in the first case vs. yielding a function in the second case when applied to one argument.
Given
doSomeX x = if x==7 then True else False doSomeY x y = x+y+1
we can infer the types (these aren't the most generic types possible, but they'll do for our purposes):
doSomeX :: Int -> Bool doSomeY :: Int -> Int -> Int
Remember that ->
in type signature associates to the right, so the type of doSomeY
is equivalent to
doSomeY :: Int -> (Int -> Int)
With this in mind, consider the type of (.)
:
(.) :: (b -> c) -> (a -> b) -> a -> c
If you define
doSomeXY = doSomeX.doSomeY
...which is equivalent to (.) doSomeX doSomeY
, it means that the first argument to (.)
is doSomeX
and the second argument is doSomeY
. Hence, the type b -> c
(the first argument to (.)
) must match the type Int -> Bool
(the type of doSomeX
). So
b ~ Int c ~ Bool
Hence,
(.) doSomeX :: (a -> Int) -> a -> Bool
Now, applying this to doSomeY
causes a type error. As mentioned above,
doSomeY :: Int -> (Int -> Int)
So when inferring a type for (.) doSomeX doSomeY
the compiler has to unify a -> Int
(the first argument of (.) doSomeX
) with Int -> (Int -> Int)
(the type of doSomeY
). a
can be unified with Int
, but the second half won't work. Hence the compiler barfs.
I'm adding to the adobe aem archetype https://github.com/Adobe-Marketing-Cloud/aem-project-archetype . I'm trying to have the archetype create a directory directory call ui.resources with a Gruntfile and package.json in it. I place those files in a ui.resources directory in src/main/archetype. When I run mvn archetype:generate and point to it, there's a gruntfile placed under ui.resource/{packageName} . What am I missing in the archetype-metadata?
-27370203 0You need be superuser for the Process in Java, see my example: https://github.com/adouggy/MyRecorder
-14778756 0There are several ways to achieve that, see Ant FAQ
One possible solution via macrodef simulates the antcontrib / propertycopy task but doesn't need any external library.
What version of Django are you using?
Can you post the generated HTML code? if the URL works when you copy and paste in the browser, it might be an html issue as well.
Have you looked at this page yet?
http://docs.djangoproject.com/en/dev/howto/static-files/
Update:
Can you post the model for a? is a.picture an image field? If so, then you don't need to put the MEDIA_URL in your img src, since it is already an absolute url and it should include the MEDIA_URL already. try removing that and see if it works.
<img src='{{a.picture.url}}' />
For more info see this page.
http://docs.djangoproject.com/en/1.3/ref/models/fields/#django.db.models.FileField.storage
-4442587 0 Simple jQuery problemThis one should be easy
I've got this HTML
<table class="PageNumbers"> <tr> <td colspan="3">text3 </td> </tr> <tr> <td colspan="2">text </td> <td>text2 </td> </tr> <tr> <td>moretext </td> <td>moretext2 </td> <td>moretext3 </td> </tr> </table>
I need to change the colspan of the first rows first column to one
This is what i've got
$('.PageNumbers tr:first td:first').attr('colspan') = '1'
Doesn't seem to work though
Any ideas?
Thanks
-9780858 0 Understanding the MVC design pattern in Cocoa TouchUsually I just put together an app in any random way, as long as it works, but this means I don't pay any attention to any design patterns. My application currently makes extensive use of global variables (I carry an instance of my AppDelegate
in every view controller to access properties I declared in my AppDelegate.h
). Although it does what I want it to do, I've read this is not a good design practice.
So I want to start making my code "legit". However, I can't imagine my app right now without global variables. They are so important to the well-being of the app, but this must mean I'm doing something wrong, right? I just can't imagine how else I'd do some things. Take for example this:
You have two view controllers here, a SideViewController
and a MainViewController
. Using global variables, such as say if the entire application had one shared instance of SideViewController
and MainViewController
(appDelegate.sideViewController
and appDelegate.mainViewController
), I can easily communicate between the two view controllers, so that if I press "News Feed" in my SideViewController
, I can tell my MainViewController
to reload it's view.
I can't imagine, however, how this would be done if these were not global variables? If an event occurs in my SideViewController
, how would I notify my MainViewController
, in a way that is in accordance with design standards?
in libconfig
- is it possible to dymanically enumerate keys?
As an example, in this example config file from their repo - if someone invented more days in the hours
section, could the code dynamically enumerate them and print them out?
Looking at the docs, I see lots of code to get a specific string, or list out an array, but I can't find an example where it enumerates the keys of a config section.
Edit
Received some downvotes, so thought I'd have another crack at being more specific.
I'd like to use libconfig to track some state in my application, read in the last known state when the app starts, and write it out again when it exits. My app stores things in a tree (of depth 2) - so this could be niceley represented as an associative array in a libconfig compatible file as below. The point is that the list of Ids (1234/4567
) can change. I could track them in another array, but if I could just enumerate the 'keys' in the ids
array below - that would be neater.
so
ids = { "1234" = [1,2,3] "4567" = [9,10,11,23] }
e.g (psuedocode)
foreach $key(config_get_keys_under(&configroot)){ config_get_String($key) }
I can't see anything obvious in the header file.
-2663579 0You probably have an ancient version of xerces on the classpath. Definitely check xerces versions.
-32054793 0 Are there other means of obtaining the properties of a target in cmake?I have created a C++ static library, and in order to make it searchable easily, I create the following cmake files:
lib.cmake
# The installation prefix configured by this project. set(_IMPORT_PREFIX "C:/------/install/win32") # Create imported target boost add_library(lib STATIC IMPORTED) set_target_properties(lib PROPERTIES INTERFACE_COMPILE_DEFINITIONS "lib_define1;lib_define2" INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/../include" ) # Load information for each installed configuration. get_filename_component(_DIR "${CMAKE_CURRENT_LIST_FILE}" PATH) file(GLOB CONFIG_FILES "${_DIR}/lib-*.cmake") foreach(f ${CONFIG_FILES}) include(${f}) endforeach()
lib-debug.cmake
# Import target "boost" for configuration "Debug" set_property(TARGET lib APPEND PROPERTY IMPORTED_CONFIGURATIONS DEBUG) set_target_properties(boost PROPERTIES IMPORTED_LINK_INTERFACE_LANGUAGES_DEBUG "CXX" IMPORTED_LOCATION_DEBUG "${_IMPORT_PREFIX}/Debug/staticlib/lib.lib" )
When I want to use this library in an executable, I can simply invoke it by calling find_package command:
find_package(lib REQUIRED) if(lib_FOUND) message("lib has been found") else() message("lib cannot be found") endif(boost_FOUND)
It works and if I want to know the head file directory of the library, I will have to call it this way:
get_target_property(lib_dir lib INTERFACE_INCLUDE_DIRECTORIES)
I was just wondering whether there are other ways of obtaining the properties of an target. In this case I expect some variable like lib_INCLUDE_DIRECTORIES
will exist.
I need to know a strategy to overwrite the log level server side by a unique client session. I mean, I don't want to let all client to write more than needed in order to debug errors only for a specific client. So I'm trying to drive the log level client side instead of server side.
-1651061 0You might want to set these session options in your vimrc. Especially options is annoying when you've changed your vimrc after you've saved the session.
set ssop-=options " do not store global and local values in a session set ssop-=folds " do not store folds
-40768802 0 Reload linechart only I have this chart element
<canvas class="main-chart" id="line-chart" height="200" width="600"></canvas>
and i have this script to insert the data
<script> function hour(){ return a=["00:00","01:00","02:00","03:00","04:00","05:00","06:00","07:00","08:00","09:00","10:00", "11:00","12:00","13:00","14:00","15:00","16:00","17:00","18:00", "19:00","20:00","21:00","22:00","23:00"]; }; var data_visitors_present=<?php echo json_encode(visitorsPresentDay()[0]);?>; var data_visitors_previous=<?php echo json_encode(visitorPreviousDay()[0]);?>; var lineChartData = { labels : hour(), datasets : [ { label: "My First dataset", fillColor : "rgba(220,220,220,0.2)", strokeColor : "rgba(220,220,220,1)", pointColor : "rgba(220,220,220,1)", pointStrokeColor : "#fff", pointHighlightFill : "#fff", pointHighlightStroke : "rgba(220,220,220,1)", data : data_visitors_previous }, { label: "My Second dataset", fillColor : "rgba(48, 164, 255, 0.2)", strokeColor : "rgba(48, 164, 255, 1)", pointColor : "rgba(48, 164, 255, 1)", pointStrokeColor : "#fff", pointHighlightFill : "#fff", pointHighlightStroke : "rgba(48, 164, 255, 1)", data : data_visitors_present } ] } </script>
The final result is this enter image description here
I want every 10 seconds to reload only the chart element; I wrote this without effect..
<script> var chart=document.getElementById('#line-chart'); setInterval(chart){( function hour(){ return a=["00:00","01:00","02:00","03:00","04:00","05:00","06:00","07:00","08:00","09:00","10:00", "11:00","12:00","13:00","14:00","15:00","16:00","17:00","18:00", "19:00","20:00","21:00","22:00","23:00"]; }; var data_visitors_present=<?php echo json_encode(visitorsPresentDay()[0]);?>; var data_visitors_previous=<?php echo json_encode(visitorPreviousDay()[0]);?>; var lineChartData = { labels : hour(), datasets : [ { label: "My First dataset", fillColor : "rgba(220,220,220,0.2)", strokeColor : "rgba(220,220,220,1)", pointColor : "rgba(220,220,220,1)", pointStrokeColor : "#fff", pointHighlightFill : "#fff", pointHighlightStroke : "rgba(220,220,220,1)", data : data_visitors_previous }, { label: "My Second dataset", fillColor : "rgba(48, 164, 255, 0.2)", strokeColor : "rgba(48, 164, 255, 1)", pointColor : "rgba(48, 164, 255, 1)", pointStrokeColor : "#fff", pointHighlightFill : "#fff", pointHighlightStroke : "rgba(48, 164, 255, 1)", data : data_visitors_present } ] } }1000); </script>
how i can fix it?
-26956433 1 Python - non-English characters don't work in one caseDespite the fact I tried to find a solution to my problem both on english and my native-language sites I was unable to find a solution. I'm querying an online dictionary to get translated words, however non-English characters are displayed as e.g. x86
or x84
. However, if I just do print(the_same_non-english_character)
the letter is displayed in a proper form. I use Python 3.3.2 and the HTML source of the site I extract the words from has charset=UTF-8
set. Morever, if I use e.g. replace("x86", "non-english_character")
, I don't get anything replaced, but replacing of normal characters works.
I manage web application which is made by Symfony2(PHP). I measure some value in Database (for example, register User per a day) on management screen made by myself.
But I want to compare this value with data on Google analytics. so I want to know how to send a value in database to Google analytics.
-14089825 0I usually select a base color and change the hue in 5-6 step (=changing main color) If I need more colors, I'd change saturation (strength or grayish) or luminosity.
The problem here is that you should avoid two adjacent colors (on your drawing) to be close together in terms of 'distance' of the three values H,S,L.
This is quite easy to implement and gives acceptable results.
e.g. (use the windows color editor)
(S=140, L=160): H=0,40,80,120,160,200
(S=90 , L=180); H=20,60,100,140, 180
Please don't use too many colors. Play with fill patterns as well.
-23295562 0el = document.getElementsByName("invoice_line[0][vat]") el.options[[el.selectedIndex]].attributes["data-id"].value
-37505779 0 I use following code fix:
require 'nokogiri' d = Nokogiri::HTML(%Q(<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> </head> <body> </body> </html> )) d.css('body')[0].add_child(Nokogiri::XML::Comment.new(d, "doc")) puts d.to_s
-40195101 0 To store inside your program multiple instances of the same class you need an object called List (here the MSDN reference and here a fast tutorial). To store the List you have multiple choice: serialize and deserialize using xml, json, protobuf protocol and much more, it's you choice.
-8075116 0 Database Login Failed, Mysql, html, and phpI am trying to work on getting better at making HTML forms using PHP and Mysql databases so I decided to make a little mock-up website to do some experiments and things like that.
I decided that the first thing I would need to do was to create a login and register page for users who want to sign on to the website. I had no idea how to do this so I did a little research online and I found some pre-built scripts that would do exactly what I wanted to do. In the end I decided to go with this script: http://www.html-form-guide.com/php-form/php-registration-form.html
On my website (hosted with hostgator using cPanel) I set up a Mysql database called ljbaumer_gifts (website is a gift website) and I added a table with 2 columns. The first one a login column which was set to int with auto increment and 25 characters. The second one is a password one which was set to var_char and 25 characters.
I filled in all of the information on the setup scripts from the website I linked to earlier completely correctly but every single time I try to register I get this error code:
Database Login failed! Please make sure that the DB login credentials provided are correct mysqlerror:Access denied for user 'ljbamer_root'@'my_server_adress' (using password: YES) Database login failed!
I used an account that has complete privileges on my server but it still doesn't work!
-31562696 0It appears that in case of using impersonated async http calls via httpWebRequest
HttpWebResponse webResponse; using (identity.Impersonate()) { var webRequest = (HttpWebRequest)WebRequest.Create(url); webResponse = (HttpWebResponse)(await webRequest.GetResponseAsync()); }
the setting <legacyImpersonationPolicy enabled="false"/>
needs also be set in aspnet.config. Otherwise the HttpWebRequest will send on behalf of app pool user and not impersonated user.
Try doing
GridView1.DataSource = users.ToList();
or
GridView1.DataSource = users.ToArray();
Is possibly that the query isn't executing at all, because of deferred execution.
-31651332 0 Google+ Sign In Button not functioning Android StudioHi so I am currently integrating a Google Sign In into my app. Lately this has been my only concern that for some reason Android Studio not recognizing the Plus_Login scope (which is necessary for the app to access basic profile info, etc). My current error is this
Error:(40, 17) error: method addScope in class Builder cannot be applied to given types; required: Scope found: String reason: actual argument String cannot be converted to Scope by method invocation conversion
and here is my onCreate file where the Error is found
EDIT 1 - Added import statement and variable declarations
package com.instigate.aggregator06; import android.content.Intent; import android.content.IntentSender; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks; import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener; import com.google.android.gms.common.Scopes; import com.google.android.gms.common.api.Scope; import com.google.android.gms.plus.Plus; public class SocialNetworkActivity extends AppCompatActivity implements ConnectionCallbacks, OnConnectionFailedListener, View.OnClickListener { private static final String TAG = "Social Network Activity"; /* Request code used to invoke sign in user interactions. */ private static final int RC_SIGN_IN = 0; /* Client used to interact with Google APIs. */ private GoogleApiClient mGoogleApiClient; /* A flag indicating that a PendingIntent is in progress and prevents * us from starting further intents. */ private boolean mIntentInProgress; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(Plus.API) .addScope(Scopes.PLUS_LOGIN) // <----- This is where the error is found .addScope(Scopes.PLUS_ME) .build(); findViewById(R.id.sign_in_button).setOnClickListener(this); }
I have searched a while to find a solution for this error (seeing as the Plus_Login scope should be functioning) yet have found no solution.
EDIT 2 - Errors after solving I found the answer to this. Apparently instead of:
.addScope(Scopes.PLUS_LOGIN) .addScope(Scopes.PLUS_ME)
we write this
.addScope(new Scope(Scopes.PLUS_LOGIN)) .addScope(new Scope(Scopes.PLUS_ME))
which solved my problem.
However, it revealed a new problem:
findViewById(R.id.sign_in_button).setOnClickListener(this);
where logcat points out that there is a NullPointerException at that point.
EDIT 3 - Solved NullPointerException I have solved the NullPointer Exception Problem, however my Google+ Sign In Button will still not function.
here is the overall class (continuation of the code snippet mentioned above)
package com.instigate.aggregator06; import android.content.Intent; import android.content.IntentSender; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks; import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener; import com.google.android.gms.common.Scopes; import com.google.android.gms.common.api.Scope; import com.google.android.gms.plus.Plus; public class SocialNetworkActivity extends AppCompatActivity implements ConnectionCallbacks, OnConnectionFailedListener, View.OnClickListener { private static final String TAG = "Social Network Activity"; /* Request code used to invoke sign in user interactions. */ private static final int RC_SIGN_IN = 0; /* Client used to interact with Google APIs. */ private GoogleApiClient mGoogleApiClient; /* A flag indicating that a PendingIntent is in progress and prevents * us from starting further intents. */ private boolean mIntentInProgress; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_social_network); mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(Plus.API) //.addScope(Scopes.PLUS_LOGIN) //.addScope(Scopes.PLUS_ME) .addScope(new Scope(Scopes.PLUS_ME)) .addScope(new Scope(Scopes.PLUS_LOGIN)) .build(); this.findViewById(R.id.sign_in_button).setOnClickListener(this); } protected void onStart() { super.onStart(); mGoogleApiClient.connect(); } protected void onStop() { super.onStop(); if (mGoogleApiClient.isConnected()) { mGoogleApiClient.disconnect(); } } /* Code in case second one doesn't work @Override public void onConnectionFailed(ConnectionResult connectionResult) { // Could not connect to Google Play Services. The user needs to select an account, // grant permissions or resolve an error in order to sign in. Refer to the javadoc for // ConnectionResult to see possible error codes. Log.d(TAG, "onConnectionFailed:" + connectionResult); if (!mIsResolving && mShouldResolve) { if (connectionResult.hasResolution()) { try { connectionResult.startResolutionForResult(this, RC_SIGN_IN); mIsResolving = true; } catch (IntentSender.SendIntentException e) { Log.e(TAG, "Could not resolve ConnectionResult.", e); mIsResolving = false; mGoogleApiClient.connect(); } } else { // Could not resolve the connection result, show the user an // error dialog. showErrorDialog(connectionResult); } } }*/ public void onConnectionFailed(ConnectionResult result) { if (!mIntentInProgress && result.hasResolution()) { try { mIntentInProgress = true; startIntentSenderForResult(result.getResolution().getIntentSender(), RC_SIGN_IN, null, 0, 0, 0); } catch (IntentSender.SendIntentException e) { // The intent was canceled before it was sent. Return to the default // state and attempt to connect to get an updated ConnectionResult. mIntentInProgress = false; mGoogleApiClient.connect(); } } } public void onConnected(Bundle connectionHint) { // We've resolved any connection errors. mGoogleApiClient can be used to // access Google APIs on behalf of the user. Log.d(TAG, "onConnected:" + connectionHint); Intent j = new Intent(SocialNetworkActivity.this, AccountPageActivity.class); startActivity(j); } protected void onActivityResult(int requestCode, int responseCode, Intent intent) { if (requestCode == RC_SIGN_IN) { mIntentInProgress = false; if (!mGoogleApiClient.isConnecting()) { mGoogleApiClient.connect(); } } } public void onConnectionSuspended(int cause) { mGoogleApiClient.connect(); } @Override public void onClick(View v) { if (v.getId() == R.id.sign_in_button) { //onSignInClicked(); mGoogleApiClient.connect(); } // ... } /* I find this unnecesary private void onSignInClicked() { // User clicked the sign-in button, so begin the sign-in process and automatically // attempt to resolve any errors that occur. //mShouldResolve = true; mGoogleApiClient.connect(); // Show a message to the user that we are signing in. //mStatusTextView.setText(R.string.signing_in); }*/ public void backToMainPage(View view) { Intent j = new Intent(SocialNetworkActivity.this, MainActivity.class); startActivity(j); } }
and here is my xml for that class file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context="com.instigate.aggregator06.SelectSNActivity" android:orientation="vertical" android:id="@+id/SelectSNActivity" android:weightSum="1"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/backbtn2" android:id="@+id/backbtntest" android:layout_gravity="right" android:layout_alignParentBottom="true" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" android:layout_marginBottom="43dp" android:onClick="backToMainPage"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:text="@string/selectSocialNetwork" android:id="@+id/selectSocialNetworkHeader" android:textStyle="bold" android:textSize="36sp" android:layout_gravity="center_horizontal" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" /> <com.google.android.gms.common.SignInButton android:id="@+id/sign_in_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/selectSocialNetworkHeader" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_marginTop="52dp" /> </RelativeLayout>
Any help is much appreciated, thank you.
-14212199 0The other answers seem to have missed the source-control history side of things.
From http://forums.perforce.com/index.php?/topic/359-how-many-lines-of-code-have-i-written/
Calculate the answer in multiple steps:
1) Added files:
p4 filelog ... | grep ' add on .* by <username>' p4 print -q foo#1 | wc -l
2) Changed files:
p4 describe <changelist> | grep "^>" | wc -l
Combine all the counts together (scripting...), and you'll have a total.
You might also want to get rid of whitespace lines, or lines without alphanumeric chars, with a grep?
Also if you are doing it regularly, it would be more efficient to code the thing in P4Python and do it incrementally - keeping history and looking at only new commits.
-35512272 0It looks like your datanodes are full. Could you please check disk space?
-34677900 0That's because getPerson()
returns nothing. You are missing a return
keyword.
Correct structure is:
getPerson() { return addressService.get() .then(...) .then(...); }
Side note: There are also several other typos/minor errors to fix:
class PersonService { getPerson() { return addressService.get().then(({address}) => { // <== Added return at beginning of line return `http://localhost/${address}`; // <== Use ` (backtick), not ', for template strings }).then(url => { // <== Fixed typo return new es6Promise.Promise(function(resolve, reject) { ApiUtils.get(url, {}, {}, { success: resolve, error: reject }); }); }); // <== Fixed typo } }
-8394380 0 If the parent has display:none;
then you'll need to show it before trying to slideUp the child. You can do this with the show
function.
$(divToSlide).parent().show(); $(divToSlide).slideUp();
Per the comment, you could alternatively, you could just set the display property to 'block'
$(divToSlide).parent().css("display", "block"); $(divToSlide).slideUp();
-37023081 0 The Recycle View supports AutofitRecycleView.
You need to add android:numColumns="auto_fit"
in your xml file.
You can refer to this AutofitRecycleViewLink
-15723806 0Basic mechanics for this is very simple. Just toggle a class on list container. In CSS set a set of rules for items that are descendent of that class to change floats or columns or css table properties . Also use that main list class to determine what you want displayed within the items, or how you want them displayed
Once class is removed they go back to block elements and default css
Simple example:
HTML:
<ul id="itemList"> <li> <h3 class="title">Item # 1</h3> <div class="details">Detals # 1</div> </li> </ul>
CSS:
.grid li{ float:left; width:30%;margin-right:5px} .grid .details{display:none}
JS:
$('button').click(function(){ var txt=$(this).text(); txt= txt=='Grid view'? 'List view' : 'Grid view'; $(this).text( txt); $('#itemList').toggleClass('grid') });
DEMO: http://jsfiddle.net/kzDNe/
-15341673 0DataStax provides a Community Edition AMI for Amazon EC2, detailed instructions here.
-9253056 0Yes. It's possible. Use plpython for example. Use this in trigger.
CREATE OR REPLACE FUNCTION move_file(old_path text, new_path text) RETURNS boolean AS $$ import shutil try: shutil.move(old_path, new_path) return True except: return False $$ LANGUAGE 'plpythonu' VOLATILE;
-24402847 0 non-static variable s cannot be referenced from a static context I'm trying to write a piece of code that when I check one of the two checkboxes, it will change the message that appears when I then select the button.
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class FirstWindow extends JFrame{ String message; public static void main(String[] args){ //the string to show the message for button 1 message = "goodjob \n"; //all of the main window JFrame frame = new JFrame("heading"); frame.setVisible(true); frame.setSize(600,400); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); //makes seperate panels JPanel panel1 = new JPanel(); JPanel panel2 = new JPanel(); JPanel panel3 = new JPanel(new GridBagLayout()); //set of buttons JButton button1 = new JButton("Button 1"); JButton button2 = new JButton("Button 2"); //makes an ACTION LISTENER, which tells the button what to do when //it is pressed. button1.addActionListener(new ActionListener(){ //the command to button @Override public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, message); } }); //for panel adds buttons panel1.add(button1); panel1.add(button2); //set of checkboxes JCheckBox checkBox = new JCheckBox("Option1"); JCheckBox checkBox2 = new JCheckBox("Option2"); //adds text if the box is checked if (checkBox.isSelected()) { message += "you picked option 1"; } if (checkBox2.isSelected()) { message += "you picked option 2"; } //for panel2 adds checkboxes panel2.add(checkBox); panel2.add(checkBox2); //makes a new label, text area and field JLabel label = new JLabel("This is a label"); JTextArea textArea = new JTextArea("this is a text area"); JTextField textField = new JTextField("text field"); //makes an invisible grid GridBagConstraints grid = new GridBagConstraints(); grid.insets = new Insets(15, 15, 15, 15); //sets the the coordinates 0,0. adds the label, and sets position grid.gridx = 0; grid.gridy = 0; panel3.add(label, grid); //sets the the coordinates 0,1. adds the textArea, and sets position grid.gridx = 0; grid.gridy = 1; panel3.add(textArea, grid); //sets the the coordinates 0,2. adds the text field, and sets position grid.gridx = 0; grid.gridy = 2; panel3.add(textField, grid); //adds each PANEL to the FRAME and positions it frame.add(panel1, BorderLayout.SOUTH); frame.add(panel3, BorderLayout.CENTER); frame.add(panel2, BorderLayout.NORTH); } }
The error message I'm receiving is:
"FirstWindow.java:12: error: non-static variable message cannot be referenced from a static context message = "goodjob \n";"
for lines 12, 37, 53, 57. I've tried declaring the String variable in the main but then I will just receive the error:
"FirstWindow.java:38: error: local variables referenced from an inner class must be final or effectively final JOptionPane.showMessageDialog(null, message);"
How to solve this problem?
-16481898 0From here:
When you open catalina.sh / catalina.bat, you can see :
Environment Variable Prequisites JAVA_HOME Must point at your Java Development Kit installation.
So, set your environment variable JAVA_HOME to point to Java 7. Also make sure JRE_HOME is pointing to the same target, if it is set.
You may not have this same issue, but if you do, it could be helpful to know ; )
-37791208 0 Knockout JS - How to initialize a complex object as observable?I have a ViewModel and have an observable property that will have a complex object after an edit link is clicked. This is a basic example of managing a set of Groups. User can click on the 'edit' link and I want to capture that Group in SelectedGroup property.
But I'm not sure how should I initialize the SelectedGroup and make every peoperty in this object as observable to begin with.
function ManageGroupsViewModel() { var self = this; self.Groups = ko.observableArray(); self.IsLoading = ko.observable(false); self.SelectedGroup = ko.observable(); }
-4431992 0 as3: Error: Implicit coercion of a value of type void to an unrelated type I'm attempting to set up a Metadata object like so:
public function myFunction(event:MediaFactoryEvent):void { var resource:URLResource = new URLResource("http://mediapm.edgesuite.net/osmf/content/test/logo_animated.flv"); var media:MediaElement = factory.createMediaElement(resource); // Add Metadata for the URLResource var MediaParams:Object = { mfg:"Ford", year:"2008", model:"F150", } media.addMetadata("MediaParams", (new Metadata()).addValue("MediaParams", MediaParams) );
When I attempt this, I get:
Implicit coercion of a value of type void to an unrelated type org.osmf.metadata:Metadata. (new Metadata()).addValue("MediaParams", MediaParams) ); I actually need the metadata at a couple of levels of depth there, because the metadata gets passed and another function expects the Metadata that way.
How do I get the Metadata added to my URLResource the way I want? Thanks!
-20895184 0 Identical template for many functionsI'm writing a (not really) simple project in C++ (my first, coming from plain C). I was wondering if there is a way to simplify the definition for multiple functions having the same template pattern. I think an example would be better to explain the problem.
Let's assume I have a "Set" class which represents a list of numbers, defined as
template <class T> class Set { static_assert(std::is_arithmetic<T>(), "Template argument must be an arithmetic type."); T *_address; ... }
So if I have an instance (say Set<double>
) and an array U array[N]
, where U
is another arithmetic type and N
is an integer, I would like to be able to perform some operations such as assigning the values of the array to those of the Set
. Thus I create the function template inside the class
template <class U, int N> void assign(U (&s)[N]) { static_assert(std::is_arithmetic<U>(), "Template argument must be an arithmetic type."); errlog(E_BAD_ARRAY_SIZE, N == _size); idx_t i = 0; do { _address[i] = value[i]; } while (++i < size); }
As far as my tests went the code above works perfectly fine. However I find it REALLY REALLY ugly to see since I need the static_assert
to ensure that only arithmetic types are taken as arguments (parameter U
) and I need a way to be sure about the array size (parameter N
). Also, I'm not done with the assign
function but I need so many other functions such as add
, multiply
, scalar_product
etc. etc.!
I was wondering then if there is a prettier way to write this kind of class. After some work I've come up with a preprocessor directive:
#define arithmetic_v(_U_, _N_, _DECL_, ...) \ template <class U, idx_t N> _DECL_ \ { \ static_assert(std::is_arithmetic<U>(),"Rvalue is not an arithmetic type."); \ errlog(E_BAD_ARRAY_SIZE, N == _size); \ __VA_ARGS__ \ }
thus defining my function as
arithmetic_v(U, N, void assign(U (&value)[N]), idx_t i = 0; do { _address[i] = value[i]; } while (++i < _size); )
This is somehow cleaner but still isn't the best since I'm forced to lose the brackets wrapping the function's body (having to include the static_assert
INSIDE the function itself for the template parameter U
to be in scope).
The solution I've found seems to work pretty well and the code is much more readable than before, but... Can't I use another construct allowing me to build an even cleaner definition of all the functions and still preserving the static_assert
piece and the info about the array size? It would be really ugly to repeat the template code once for each function I need...
I'm just trying to learn about the language, thus ANY additional information about this argument will be really appreciated. I've searched as much as I could stand but couldn't find anything (maybe I just couldn't think of the appropriate keywords to ask Google in order to find something relevant). Thanks in advance for your help, and happy new year to you all!
Gianluca
-26027094 0Use this:
(?s)<Device(?:(?!<\/Device).)*<Block[^>]+Name="ZG123CZ123".*?<\/Device>
Explanation:
(?s)
is the single-line modifier, which makes .
include newline characters.<Device
looks for the beginning of a Device
element.(?:(?!<\/Device).)*
is essentially .*
, but each time we try to match a character we make sure we aren't matching the end of a Device
element (<\/Device
) by using a negative lookahead. Note that you can't just make this a lazy match, since it would continue until if found the <Block Name="ZG123CZ123">
(that is the next chunk).<Block[^>]+Name="ZG123CZ123"
will look for the beginning of a Block
element, followed by non >
character(s), followed by the Name
attribute equaling ZG123CZ123
..*?
is a lazy match to eat up the rest of the Device
element.<\/Device>
we've made it to the end!Yeah there's a matches pseudo class, but if you're hoping it will save you some typing it still needs vendor prefixes you'd have to duplicate and the support isn't great.
:matches(#header, #footer) button active:hover { color: purple; } :-webkit-any(#header, #footer) button active:hover { color: purple; } :-moz-any(#header, #footer) button active:hover { color: purple; }
So as you can see it ends up being more verbose than just adding the comma and another selector at the moment.
-27665172 0list_a = list_b = [0 for k in range(10)]
Because list_a equal to list_b. So if list_b is changed, then list_a will change.
-34990373 0You could use ngModel
to do this automatically
<li *ngFor="#hero of heroes"> <input type="text" [(ngModel)]="hero.name"/> </li>
-22297215 0 don't look for bug free query here because you haven' provided enough info and sample data. So start pointing out one be one,
Declare @i varchar='Jan-13' declare @upto int=11 Declare @FromDate date=convert(varchar(12),'1-'+'Jan-13',120) Declare @Todate date =dateadd(month,@upto,@FromDate) select convert(char(6),@FromDate,107) ,@ToDate Declare @StringDate varchar(2000)='' select @StringDate= stuff((select ','+'['+convert(char(6),ODLN.DocDate ,107)DocDate+']' from ODLN inner join DLN1 on odln.DocEntry = ODLN.DocEntry where ODLN.DocDate between between @FromDate and @Todate for xml path('')),1,1,'') --@StringDate will have value like [Jan-13],[Dec-12] and so on Declare @qry varchar(max)='' set @qry='select CardName,'+@StringDate+' from (select CardName,CardCode ,DLN1.Quantity,convert(char(6),ODLN.DocDate ,107)DocDate from ODLN inner join DLN1 on odln.DocEntry = ODLN.DocEntry where ODLN.DocDate between between '+@FromDate+' and '+@Todate+')tbl pivot( max(Quantity) for DocDate in('+@StringDate+'))pvt' exec @qry
-32282831 1 Unable to log Flask exceptions with SMTP handler I am attempting to get an email sent to me any time an error occurs in my Flask application. The email is not being sent despite the handler being registered. I used smtplib
to verify that my SMTP login details are correct. The error is displayed in Werkzeug's debugger, but no emails are sent. How do I log exceptions that occur in my app?
import logging from logging.handlers import SMTPHandler from flask import Flask app = Flask(__name__) app.debug = True app.config['PROPAGATE_EXCEPTIONS'] = True if app.debug: logging.basicConfig(level=logging.INFO) # all of the $ names have actual values handler = SMTPHandler( mailhost = 'smtp.mailgun.org', fromaddr = 'Application Bug Reporter <$mailgun_email_here>', toaddrs = ['$personal_email_here'], subject = 'Test Application Logging Email', credentials = ('$mailgun_email_here', '$mailgun_password_here') ) handler.setLevel(logging.ERROR) app.logger.addHandler(handler) @app.route('/') def index(): raise Exception('Hello, World!') # should trigger an email app.run()
-32090894 0 Maven - Debug - Can not find symbol During using mvn install or mvn compile i got error that maven can not find symbol with different methods and variables in mozilla rhino classes. I made exclusions everywhere where it is possible and said to use 7r5 build for rhino. Also i decompiled jar and got sure that mentioned classes and methods in maven were in that classes. I had pom deps and i couldnt exclude all 3d libraries. So in classpath i saw also path to rhino 6r5 library. I thought that problem was there. So i also decompiled that jar but i saw that methods in the error were also there. My question is how i can debug maven and see what library or class it is using for compiling class. All mozilla rhino libraries which are set in classpath have that methods. PS: I wanted to mention that mvn eclipse:eclipse works fine and i have no errors in eclipse.
[ERROR] ...path_to_class...:[264,65] cannot find symbol [ERROR] symbol: method getLength() [ERROR] location: class org.mozilla.javascript.NativeArray [ERROR] ...path_to_class...:[288,18] cannot find symbol [ERROR] symbol: method getWrapFactory() [ERROR] location: variable cx of type org.mozilla.javascript.Context [ERROR] ...path_to_class...:[322,49] cannot find symbol [ERROR] symbol: method getLength() [ERROR] location: variable array of type org.mozilla.javascript.NativeArray
-38124350 0 Does Setting Session in Model is bad practice? I do some database transaction and the set $new_user = TRUE like this
Model Code:
$data_insert = array ( 'username' => $username_post, 'password'=>$username_post, ); $this->db->insert('Tenant', $data_insert); $new_tenant_id = $this->db->insert_id(); //CREATE TABLE FOR THAT DISTRIBUTOR $this->dbforge->add_field( array( 'id' => array( 'type' => 'INT', 'constraint' => 10, 'unsigned' => TRUE, 'auto_increment' => TRUE ), 'site_key' => array( 'type' => 'VARCHAR', 'constraint' => '100', ), 'display_name' => array( 'type' => 'VARCHAR', 'constraint' => '100', 'null' => TRUE ), 'ext' => array( 'type' => 'VARCHAR', 'constraint' => '50', 'null' => TRUE ), 'auth_user' => array( 'type' => 'VARCHAR', 'constraint' => '100', 'null' => TRUE ), 'password' => array( 'type' => 'VARCHAR', 'constraint' => '128', 'null' => TRUE, ), 'base_ini_id' => array( 'type' => 'VARCHAR', 'constraint' => '50', 'null' => TRUE ), 'md_user' => array( 'type' => 'VARCHAR', 'constraint' => '128', 'null' => TRUE ), 'uc_user' => array( 'type' => 'VARCHAR', 'constraint' => '50', 'null' => TRUE ), 'uc_password' => array( 'type' => 'VARCHAR', 'constraint' => '100', 'null' => TRUE ), 'comments' => array( 'type' => 'VARCHAR', 'constraint' => '200', 'null' => TRUE ), 'custom_ini_filename' => array( 'type' => 'VARCHAR', 'constraint' => '100', 'null' => TRUE ), 'email' => array( 'type' => 'VARCHAR', 'constraint' => '100', 'null' => TRUE ), )); $this->dbforge->add_key('id', TRUE); if (!$this->db->table_exists('table_name')) { $this->dbforge->create_table($usertable); } //TABLE CREATED NOW ADD SOME DATA $insert_data = array ( 'site_key' =>$site_post, 'tenant_id'=>$new_tenant_id ); //TENANT CREATED AND THE SITE BY HIM IS ADDED TO DATABASE $query = $this->db->insert('MLCSites',$insert_data); $new_user = TRUE;
Now if i have the user in database then $validate is set to TRUE if not i check if $new_user == TRUE then I set loggedin = TRUE in my session like this:
if(!empty($validate)) { if ($validate == TRUE) { // Log in user $data = array( 'site' => $site->site_post, 'id' =>$tenant_id, 'username'=>$username_post, 'user_table'=>$usertable, 'nec_distributor'=>TRUE, 'loggedin' => TRUE, ); $this->session->set_userdata($data); return TRUE; } elseif ($new_user == TRUE) { // Log in user $data = array( 'site' => $site->site_post, 'id' =>$new_tenant_id, 'username'=>$username_post, 'user_table'=>$usertable, 'nec_distributor'=>TRUE, 'loggedin' => TRUE, ); $this->session->set_userdata($data); return TRUE; } return FALSE; }
Now in my controller i Check like this:
$dashboard ='customer/dashboard'; $rules = $this->distributor_m->rules; $this->form_validation->set_rules($rules); if ($this->distributor_m->login() == TRUE) { var_dump($this->session->all_userdata()); $this->distributor_m->loggedin() == FALSE || redirect($dashboard); redirect($dashboard); } else { $this->session->set_flashdata('error', 'That email/password combination does not exist'); //redirect('secure/login', 'refresh'); }
But when i submit username and key, all the database transaction are done as per the code successfully. But there is nothing in my session, if I resend the form information then i see the SESSION data. So where I am going wrong?
-26407526 0No answer yet has explained why NASM reports
Mach-O 64-bit format does not support 32-bit absolute addresses
The reason NASM won't do this is explained in Agner Fog's Optimizing Assembly manual in section 3.3 Addressing modes under the subsection titled 32-bit absolute addressing in 64 bit mode he writes
32-bit absolute addresses cannot be used in Mac OS X, where addresses are above 2^32 by default.
This is not a problem on Linux or Windows. In fact I already showed this works at static-linkage-with-glibc-without-calling-main. That hello world code uses 32-bit absolute addressing with elf64 and runs fine.
@HristoIliev suggested using rip relative addressing but did not explain that 32-bit absolute addressing in Linux would work as well. In fact if you change lea rdi, [rel msg]
to lea rdi, [msg]
it assembles and runs fine with nasm -efl64
but fails with nasm -macho64
Like this:
section .data msg db 'This is a test', 10, 0 ; something stupid here section .text global _main extern _printf _main: push rbp mov rbp, rsp xor al, al lea rdi, [msg] call _printf mov rsp, rbp pop rbp ret
You can check that this is an absolute 32-bit address and not rip relative with objdump
. However, it's important to point out that the preferred method is still rip relative addressing. Agner in the same manual writes:
There is absolutely no reason to use absolute addresses for simple memory operands. Rip- relative addresses make instructions shorter, they eliminate the need for relocation at load time, and they are safe to use in all systems.
So when would use use 32-bit absolute addresses in 64-bit mode? Static arrays is a good candidate. See the following subsection Addressing static arrays in 64 bit mode. The simple case would be e.g:
mov eax, [A+rcx*4]
where A is the absolute 32-bit address of the static array. This works fine with Linux but once again you can't do this with Mac OS X because the image base is larger than 2^32 by default. To to this on Mac OS X see example 3.11c and 3.11d in Agner's manual. In example 3.11c you could do
mov eax, [(imagerel A) + rbx + rcx*4]
Where you use the extern reference from Mach O __mh_execute_header
to get the image base. In example 3.11c you use rip relative addressing and load the address like this
lea rbx, [rel A]; rel tells nasm to do [rip + A] mov eax, [rbx + 4*rcx] ; A[i]
-1315826 0 Sharing objects between C# and C++ code Is it possible to share references to C# objects between C# and C++ code without massive complexity? Or is this generally considered a bad idea?
-16525056 0 remove multiple line using str_replaceI want to remove this multi line with str_replace
<div><i>Hello</i><br/> <!-- Begin: Hello.text --> <script src="http://site.com/hello.php?id=12345" type="text/javascript"> </script> <!-- End: Hello.text --></div>
12345 = random number
-37551018 0 how to check longitude latitude database sql serveri have longitude and latitude in geofence table how to check longitude and latitude in database level. if car longitude latitude are in Zone, update geofance column zones = 'car in zone area'
CREATE TRIGGER Tr_CheckGeoFance ON CheckGeoFance AFTER INSERT AS BEGIN Update tblgeofencing Set CarZone ='Car In Zone Area' END GO ShapesString ={"shapes":[{"type":"rectangle","color":"#1E90FF","bounds":{"northEast":{"lat":"32.379961464357315","lon":"70.99365234375"},"southWest":{"lat":"31.840232667909362","lon":"70.2685546875"}}}]}
-36487261 0 Instead of TStringGrid
use TGrid
with TColumn
columns. Then use the OnGetValue
event to fetch values for display in the grid. This is closest to the VCL
s TDrawGrid
.
procedure TForm1.Grid1GetValue(Sender: TObject; const Col, Row: Integer; var Value: TValue); begin Value := inttostr(col)+', '+inttostr(row); end;
Sample result of grid with 10 mio rows:
-14716668 0 quicker WiFi scan rate to obtain rssi changes androidI am trying to increase the wifi scan rate but with the method wifi.startscan and getting the info of the list result returned, i dont see that the rssi change each 2 seconds. My question is if it is possible to get a low rate scan of the rssi and if it is possible how could i do it.
-20710003 0You can use GridBagLayout in netBeans . this layout is stable way for complex form and panel .
-3519222 0>gawk -F"/" "{ split($5,a,\".\"); print a[1]}" 1.t PRX01 PRX02 PRX03 PRX04
-25004136 0 I got this after more trial and error: '/table/tbody/tr[preceding-sibling::tr[th/text()="First header"] = preceding-sibling::tr[th][1]]'
Which translates to English: get all rows preceded by the "First header" row where that row is also the first preceding row that contains a header.
According to documentation for CanvasRenderingContext2D.drawImage() function:
ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);
sx, sy, sWidth, sHeight are parameters of the sub-rectangle of the source image
In your case: parameters sx, sy, sWidth, sHeight should coincide with parameters dx, dy, dWidth, dHeight (in most simple case)
Change your imageObj.onload
handler as shown below:
... imageObj.onload = function() { context.drawImage(imageObj, x, y, width, height, x, y, width, height); callback(canvas.toDataURL()) }; ...
-15720869 0 Connect to database in android I used the login code to login through simple android application , I've created mydatabase also created the whole java classes needed and the xml files, the result always gives me "Invalid username or password" even though the username and the password are correct as inserted in the DB ,, the app runs with no errors
this is the MainActivity java class:
package com.logintest.fh; import java.io.IOException; public class MainActivity extends Activity { /** Called when the activity is first created. */ Button login; String name="",pass=""; EditText username,password; TextView tv; byte[] data; HttpPost httppost; StringBuffer buffer; HttpResponse response; HttpClient httpclient; InputStream inputStream; SharedPreferences app_preferences ; List<NameValuePair> nameValuePairs; CheckBox check; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); app_preferences = PreferenceManager.getDefaultSharedPreferences(this); username = (EditText) findViewById(R.id.username); password = (EditText) findViewById(R.id.password); login = (Button) findViewById(R.id.login); check = (CheckBox) findViewById(R.id.check); String Str_user = app_preferences.getString("username","0" ); String Str_pass = app_preferences.getString("password", "0"); String Str_check = app_preferences.getString("checked", "no"); if(Str_check.equals("yes")) { username.setText(Str_user); password.setText(Str_pass); check.setChecked(true); } login.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { name = username.getText().toString(); pass = password.getText().toString(); String Str_check2 = app_preferences.getString("checked", "no"); if(Str_check2.equals("yes")) { SharedPreferences.Editor editor = app_preferences.edit(); editor.putString("username", name); editor.putString("password", pass); editor.commit(); } if(name.equals("") || pass.equals("")) { Toast.makeText(MainActivity.this, "Blank Field..Please Enter", Toast.LENGTH_LONG).show(); } else { try { httpclient = new DefaultHttpClient(); httppost = new HttpPost("http://10.0.0.1/my_folder_inside_htdocs/check.php"); // Add your data nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("username", name.trim())); nameValuePairs.add(new BasicNameValuePair("password", pass.trim())); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Execute HTTP Post Request response=httpclient.execute(httppost); ResponseHandler<String> responseHandler = new BasicResponseHandler(); final String response = httpclient.execute(httppost, responseHandler); System.out.println("Response : " + response); if(response.equalsIgnoreCase("User Found")){ runOnUiThread(new Runnable() { public void run() { Toast.makeText(MainActivity.this,"Login Successfull", Toast.LENGTH_SHORT).show(); } }); //startActivity(new Intent(MainActivity.this, UserPage.class)); Move_to_next(); }else{ Toast.makeText(MainActivity.this, "Invalid Username or password", Toast.LENGTH_LONG).show(); } } catch (Exception e) { Toast.makeText(MainActivity.this, "error"+e.toString(), Toast.LENGTH_LONG).show(); } } } }); check.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Perform action on clicks, depending on whether it's now checked SharedPreferences.Editor editor = app_preferences.edit(); if (((CheckBox) v).isChecked()) { editor.putString("checked", "yes"); editor.commit(); } else { editor.putString("checked", "no"); editor.commit(); } } }); } public void Move_to_next() { startActivity(new Intent(MainActivity.this, UserPage.class)); } }
the UserPage an empty page I want the user to go to after logging in
this is my php file :
try { $db = new PDO("mysql:host=$hostname_localhost;dbname=mydatabase", $username_localhost, $password_localhost); echo "Connected to database"; // check for connection $username = $_POST['myusername']; $password = $_POST['mypassword']; $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); $sql = "select * from mydatabase.tbl_user where username = '".$username."' AND password = '".$password. "'"; $result = $db->query($sql); foreach ($result as $row) { echo "<br/> success"; } $db = null; // close the database connection } catch(PDOException $e) { echo $e->getMessage(); } ?>
any ideas of what the problem might be ?
-18988050 0If the form is posting a field with a parameter of name
, a 404 will result.
You can try this:judge the parameter wether is a file, then according to the type of parameter execute the operation respectively
-30322733 0try this, if Z axis is your forward direction:
for(var i=0;i<10;i++) { gun.transform.position += gun.transform.forward; yield return 0; } for(var i=0;i<10;i++) { gun.transform.position -= gun.transform.forward; yield return 0; }
this will move the gun in the forward direction of the gun
if you turn, the forward direction is not (0,0,1)
you can also use this if X axis is your forward direction:
for(var i=0;i<10;i++) { gun.transform.position += gun.transform.right; yield return 0; } for(var i=0;i<10;i++) { gun.transform.position -= gun.transform.right; yield return 0; }
-930920 0 If you are able to use LINQ,
void Main() { Dictionary d1 = new Dictionary<int, string>(); Dictionary d2 = new Dictionary<int, string>(); d1.Add(1, "1"); d1.Add(2, "2"); d1.Add(3, "3"); d2.Add(2, "2"); d2.Add(1, "1"); d2.Add(3, "3"); Console.WriteLine(d1.Keys.Except(d2.Keys).ToArray().Length); }
This prints 0 to the console. Except tries to find the difference between two lists in the above example.
You can compare this with 0 to find if there is any difference.
EDIT: You could add the check for comparing the length of 2 dictionaries before doing this.
i.e. You can use Except, only if the length differs.
Card Number (aka PAN, Primary Account Number)
Don't take any advice as gospel. The card number is comprised of a 6 digit Issuer Identification Number (IIN), an account number and a luhn check digit. The IIN ranges are constantly changing and industry sectors that rely on this information (such as Payment Processors) will generally be updated as changes occur. It's reasonably safe to assume that the card number should be between 16 and 19 digits, and start with 3, 4, 5 or 6. Beyond that trying to identify the card type from the IIN is prone to error unless you are frequently updated.
Luhn / Mod10 check digit.
The last digit of the card number is a check digit to pick up transposition errors which may have occured when an operator has keyed in the card number. The wikipedia article is a good source for more info and code samples.
Magnetic stripe
If you have physical access to the card, and a magstripe reader, then track 2 contains banking card info. Amongst the details are card number, expiry date, LRC (check digit) and a Service Code. The service code (only available on mag stripe) informs how the card may be used, eg only for national payments, only for use at an ATM (not as a payment card), whether cash back should be offered etc.
CCV / CSC / CV2
Security digits are never embossed onto the card, or recorded on the magstripe. Should be three digits on all except Amex (always 4 digits)
Issue date
Used for manual (sanity) check only. Not sent during the authorization request
Expiry date
A common misconception is that expired cards cannot be used. They frequently can, but they must go through online authorization first (so that the acquiring bank has final say on whether it is permitted or not). Expiry dates can be up to 20 years in the future (and even further in some rare cases)
Issue number
Only available on certain card types. Should be captured and used in the authorization request.
If you're using the standard Android binding, whose Javadoc is at http://developer.android.com/reference/android/database/sqlite/package-summary.html, then you can find the right code to call by looking at the Javadoc for an overload of execSQL
. See http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#execSQL(java.lang.String,%20java.lang.Object[]).
Now, the Javadoc says that execSQL
is not to be used for SELECT/INSERT/UPDATE/DELETE
. Instead, there are three insertXXX
methods, each of which takes additional data in a ContentValues
object. So, you construct that object, which looks like a Map
, with the new row's data.
i need in php a regular expression to remove from a string of telephone numbers the + or the 0 at the beginning of a number
i have this function to remove every not-number characters
ereg_replace("[^0-9]", "", $sPhoneNumber)
but i need something better, all these examples should be...
$sPhoneNumber = "+3999999999999" $sPhoneNumber = "003999999999999" $sPhoneNumber = "3999999999999" $sPhoneNumber = "39 99999999999" $sPhoneNumber = "+ 39 999 99999999" $sPhoneNumber = "0039 99999999999"
... like this
$sPhoneNumber = "3999999999999"
any suggestions, thank you very much!
-16218085 0Here, check this out! This is what you need!
This tut explains everything you need -> Slide Elements in Different Directions
-8307372 0 Diagnostics not available in InsightsI have a couple of apps on Facebook. I would like to be able to see how many wallposts per user I am allowed to make. I know I can see this on insights (http://www.facebook.com/insights) by opening an app and clicking on "diagnostics" in the left column under "App insights".
However: for a couple of my apps there is no "diagnostics" link under "App insights". There is only a button that says "Open graph".
I have no idea what the difference is between the apps that have and don't have the "diagnostics" button. Can anyone give me some insight (har har) on this?
-16822317 0 getText between tags with SeleniumI'm trying to parse the following XML file so that I can get some attributes. One thing I need to do is verify that the content between tags is not empty. To do this, I though I would be able to use the getText method provided for web elements.
The XML file:
<results> <result index="1"> <track> <creator>Cool</creator> <album>Amazing</album> <title>Awesome and Fun</title> </track> </result> </results>
My code for parsing through and getting what I want is as follows (keep in mind there is more than one result):
boolean result = false; driver.get(url); List<WebElement> result_list = driver.findElements(By.xpath(".//result")); if (result_list.size() == num_results) { try { for (int i = 0; i < result_list.size(); i++) { WebElement track = result_list.get(i).findElement(By.xpath(".//track")); WebElement creator = track.findElement(By.xpath(".//creator")); System.out.println(creator.getText()); track.findElement(By.xpath(".//album")); track.findElement(By.xpath(".//title")); } result = true; } catch (Exception e) { result = false; } } return result;
The problem is that the System.out.println call returns an empty string when there is clearly text between the creator tags. Any help would be greatly appreciated!
-18342913 0Make sure your zoom is at 100%. Also in Internet Options > security you need to make sure that 'Enable protected mode' is selected on all 4 zones.
-32863649 0 How to add an action to notifications in Swift 2 iOS 9I'm trying to get a button in my notifications send with PHP Apns http://immobiliare.github.io/ApnsPHP/html/
Following this documentation from Apple: https://developer.apple.com/library/ios/documentation/General/Conceptual/WatchKitProgrammingGuide/BasicSupport.html#//apple_ref/doc/uid/TP40014969-CH18-SW5
But the buttons never show..
My code:
var categories = NSMutableSet() var acceptAction = UIMutableUserNotificationAction() acceptAction.title = NSLocalizedString("Accept", comment: "Accept") acceptAction.identifier = "accept" acceptAction.activationMode = UIUserNotificationActivationMode.Background acceptAction.authenticationRequired = false var declineAction = UIMutableUserNotificationAction() declineAction.title = NSLocalizedString("Decline", comment: "Decline") declineAction.identifier = "decline" declineAction.activationMode = UIUserNotificationActivationMode.Background declineAction.authenticationRequired = false var inviteCategory = UIMutableUserNotificationCategory() inviteCategory.setActions([acceptAction, declineAction], forContext: UIUserNotificationActionContext.Default) inviteCategory.identifier = "cat1" categories.addObject(inviteCategory) let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: (NSSet(array: [categories])) as? Set<UIUserNotificationCategory>) UIApplication.sharedApplication().registerUserNotificationSettings(settings) UIApplication.sharedApplication().registerForRemoteNotifications()
My APNS code:
$push = new ApnsPHP_Push(ApnsPHP_Abstract::ENVIRONMENT_PRODUCTION, 'dict_prod.pem'); $push->setProviderCertificatePassphrase('XXXXXXX'); $push->setRootCertificationAuthority('entrust_root_certification_authority.pem'); $push->connect(); $message = new ApnsPHP_Message("THE TOKEN"); $message->setText("Test"); $message->setSound('default'); $message->setExpiry(30); $message->setCategory('cat1'); $push->add($message); $push->send(); $push->disconnect(); $aErrorQueue = $push->getErrors(); if (!empty($aErrorQueue)) { var_dump($aErrorQueue); }
-16229840 0 android - required layout_attribute is missing <shape xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" > <gradient android:layout_width="match_parent" android:angle="270" android:centerColor="#4ccbff" android:endColor="#24b2eb" android:startColor="#24b2eb" /> <corners android:radius="5dp" /> </shape>
The above code shows " required layout_height
attribute is missing" on the line no 4
&
"required layout_height
and layout_width
attribute is missing" on the line no 11.
I've used pMock in the past, and didn't mind it, it had pretty decent docs too. However, Foord's Mock as mentioned above is also nice.
-21023322 0try adding
div.myClass{ position: absolute; bottom:0; width:100%; }
to the div.
Example with the div positioned only on td bottom.
-10818756 0Your selectors are incorrect, you're using the hash to indicate and id. Also you're prefixing your classes with an element notation that is not correct.
This
if($('#tr').hasClass('tr_group'))
should be:
if($('tr').hasClass('group'))
-25618368 0 The "Micro" version of Cloud Foundry is not available for Cloud Foundry V2 users onward. Check those options to run Cloud Foundry V2 locally: http://docs.cloudfoundry.org/deploying/run-local.html
This currently includes bosh-lite and cf_nise_installer.
-24510945 0Save is meant to insert one document. Update can be used over several documents that match the criteria in the first parameter.
Under certain circumstances (specifying a unique id as the criteria, upsert:true, and not using multi: true) both can serve the same purpose.
-9400307 0Browser configuration settings are available in online documenation, I suggest adding as a "Trusted Site"
-28559864 0 Comparing values of two promisesI wish to achieve the following:
var textPromise1 = element(by.id('id1')).getText(); var textPromise2 = element(by.id('id2')).getText(); if(textPromise1.SOMELOGIC == textPromise2.SOMELOGIC ) console.log('These are equal')
I know the promise is resolved using .then(). However, I want to know if there exists some way with which above can be achieved!
Thanks,
-10692147 0 Error while installing caldecottI am getting this error while running this command on windows prompt> gem insatll caldecott
. I have downloaded the development kit but the error is still the same.
Please update your PATH to include build tools or download the DevKit from 'http://rubyinstaller.org/downloads' and follow the instructions at 'http://github.com/oneclick/rubyinstaller/wiki/Development-Kit'
-6300010 0All of your questions can be solved very easy if you use a DFS for each relationship and then use your function calculate() again if you want it more detailed.
-6487736 0Try:
$('.btn-reply').click(function(){ $(this).parents('.roar').siblings('.newreply').toggleClass('show'); return false; });
However, I agree with Francisc
that a better approach would be to modify the HTML
and assign a unique id
to each message set. That way you can grab the .newreply
to show based on a shared unique id
which would be agnostic regarding the positioning of the HTML
layout.
E.g.
<div class="roar" rel="msg0">...</div> ... <button class="btn-reply" rel="msg0"></button> ... <div class="newreply" rel="msg0">...</div> ...
Then your jQuery becomes:
$('.btn-reply').click(function(){ var id = $(this).attr('rel'); var selector = '.newreply[rel=' + id + ']'; $(selector).toggleClass('show'); return false; });
-23782945 0 Thanx cs 1088,
I basically used casting a List to an array List as you correctly proposed and I finally after much mucking about realised I needed to use this structure below to cast the IList back to a BIC after retrieving the array from the Schema.
userCheckedbuiltInCategory = retrievedData.Cast().ToList();
-16059073 1 How to change file_extension internally in Blender 2.65I am writing a python script for Blender and I am quite new. I want to change output file format in render option internally. For example, context.scene.render.file_extension = "PNG"
. But it is a read-only variable so I get an error. Is there a way to change it in code?
I am using Blender-2.65.
-36256047 0Your codeResult()
method throws Exception
public int coderesult (String urlstring) throws Exception {
Therefore, you must either catch it specifically catch(Exception ex)
, or declare that your throw it from your method.
When catching exceptions, you either catch a specific exception type, or a more generic parent exception type. You could combine all catches into one catch, because all built in java exceptions extend from Exception
catch(Exception ex){ ex.printStackTrace(); }
-28818282 0 You can make regular expression groups by using (
and )
and reference then in replace using $N
, which will access N-th
group.
So in your case, you can do this regex: ([^: ]+:[^:]+:([^:]+):[^:]+:[^:]+)(:[^: ]+)
replace: \1<\2>\3
or on some implementation $1<$2>$3
You can try it yourself here: https://www.regex101.com/r/hY8pY9/1
-32955667 0I think I have an answer for you. In this you do not have to flip the y-axis, and I can get the names in the x-axis, but I still use a hierarchy. I'm not sure it's more efficient, but here goes.
First, I created a Hierarchy defined as:
CREATE NESTED HIERARCHY [New hierarchy (2)] [yearsOfExp] AS [yearsOfExp], [name] AS [name]
This allowed me to order the category axis by years of experience.
Secondly, I created a calculated column defined as:
Sum([yearsOfExp]]) over (AllNext([yearsOfExp]]))
I then created a line chart. The hierarchy is the x axis and the calculated column is the y axis. When setting the x axis, be sure to "reverse scale".
I hope this does what you're looking for. Good luck. Any questions, just ask.
-38428541 0 How to erase rows in a data frame RI have a data frame that look like this:
Quality Data Name 1 667 green 3 647 white 1 626 Blue 2 345 yellow 1 550 Blue 5 730 green
i want a code that goes through a for loop and takes the one less the 600 and greater than 700 and delete the row && all the ones with the same name and saves the ones that were deleted in another data frame
example
for i in nrow(df){ if (df$Data[i]<=600 || df$Data[i]>=700){ Subset_by_name=subset(df,df$Name==df$Name[i]) (saves bad samples) (delete from data) Subset_by_name=data.frame(Subset_by_name) bad_sample=rbind(Subset_by_name) (saves all the bad data in a data frame) } }
result
bad_sample
Quality Data Name 1 667 green 1 626 Blue 2 345 yellow 1 550 Blue 5 730 green
data
Quality Data Name 3 647 white
help please????
-20856099 0 Meteor Js , Store images to mongoDBI want to store an image browsed by a file input to database. I am browing the image using redactor plugin using this code
$('.editor').redactor({ imageUpload:"/uploads" });
Using this when i select or browse an image i am directly sending that image to server using meteor HTTP-methods
HTTP.methods({ '/uploads': function(data) { console.log(data) Meteor.call("uploadImage",data) return JSON.stringify({'Hello':"hello"}); } });
Here when i am doing console.log data I am getting the 64bit binary code for the image. Now i want to save this data to the mongodb database.
I am using meteor-collection 2 for defining fields and their types. But i couldn't get which data type i have to use to store image to the mongo db.
I am trying to use mongodb gridfs to store the image. Tell me how can i store image in mongodb ? Thanx
Use $user->profile() ->save(new UserProfile($params));
-37706079 0 Prevent HTML Removing Successive spacesI have an issue in a JSP page where I have to display a generated message onscreen based on a string. It all works fine until one of the account numbers contains two spaces.
So, I have this HTML:
<logic:notEqual name="migrationsMessage" value=""> <div style="color:Red;font-weight:bold"> <bean:write name="solasDetailsForm" property="migrationsMessage"/> </div> </logic:notEqual>
When the field migrationsMessage contains this:
<input type="hidden" name="migrationsMessage" value="A 123456W has migrated to A 123456.">
The output on the screen is this:
“A 123456W has migrated to A 123456.”
The second space after the first A is removed. I tried to alter the style to be this but it didn't help:
<logic:notEqual name="migrationsMessage" value=""> <div style="color:Red;font-weight:bold;white-space:pre"> <bean:write name="solasDetailsForm" property="migrationsMessage"/> </div> </logic:notEqual>
Any ideas what is going wrong?
-8018632 0It is not possible to reliably get sorted results without explicitly using ORDER BY
.
Sources:
Without ORDER BY, there is no default sort order
-40370122 0 Best way to index a SQL table to find best matching stringLet's say I have a SQL table with an int
PK column and an nvarchar(max)
. In the the nvarchar(max)
column, I have a bunch of table entries that are all like this:
SOME_PEOPLE_LIKE_APPLES SOME_PEOPLE_LIKE_APPLES_ON_TUESDAY SOME_PEOPLE_LIKE_APPLES_ON_THE_MOON SOME_PEOPLE_LIKE_APPLES_ON_THE_MOON_CAFE SOME_PEOPLE_LIKE_APPLES_ON_THE_RIVER . . . SOME_ANTS_HATE_SYRUP SOME_ANTS_HATE_SYRUP_WITH_STRAWBERRIES
There's millions of these rows - Then let's say my goal is to find the row with the most overlap for an input searchTerm
- So in this case, if I input SOME PEOPLE_LIKE_APPLES_ON_THE_MOON_MOUNTAIN
, the returned entry would be the third entry from the table above, SOME_PEOPLE_LIKE_APPLES_ON_THE_MOON
I have a SPROC that does this very naively, it goes through the entire table as follows:
SELECT DISTINCT phrase, len(phrase) l, [id] FROM X WHERE searchTerm LIKE phrase + '%' -- phrase is the row entry being searched against -- searchTerm is the phrase we're searching for
I then ORDER BY
length and pick the TOP
only
Would there be a way to speed this up, perhaps by doing some indexing?
If this is confusing, think of it as tableRowEntry + wildcard = searchTerm
I'm on MSSQL 2008 if that makes any difference
-29924627 0You could look into Application.registerActivityLifecycleCallbacks()
&c.
As mentioned in the comments by HK1, here's what can be done (although it's workaround):
Use a continuous form instead of the datasheet.
-29392005 0 Generate a unique number that is formed from 2 numbers and vice versa?I am not sure if this is possible but,
I have 2 numbers, a 32-bit int x and a 64-bit long y.
Given that 'y' is ALWAYS unique.
Given these numbers, I want to generate a unique identifier which is a 32-bit int. I should also be able to construct the individual numbers back from the unique identifier. Is this possible? I apologize if this is the wrong forum to ask, but this is related to C# programming on a project i am working on.
Basically, 'x' refers to a categoryID and 'y' refers to a unique 'categoryItemId' in my database, a single category can have a million of catalogItems.
Thanks!
-20207798 0Your using WriteString
to display a string. WriteString
uses edx
to hold the address of the string to print.
You call DisplayPrompt
and move the address of vHexPrompt
into edx
, then you call DisplayString
and in that function, you call WriteString
. edx
still contains the address of vHexPrompt
which is why you are getting a double prompt.
Until you write more code to utilize DisplayString
, either comment out the call to writestring in that function, or just add xor edx, edx
right before your call to WriteString
in DisplayString
You don't need to use Regex, you can just use .length to search for the longest string.
i.e.
function longestWord(string) { var str = string.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()]/g,"").split(" "); longest = str[0].length; longestWord = str[0]; for (var i = 1; i < str.length; i++) { if (longest < str[i].length) { longest = str[i].length; longestWord= str[i]; } } return longestWord; }
EDIT: You do have to use some Regex...
-4382442 0(Before the longer discussion: it looks like you're typing myButton
one line 2, and eventButton
on line 3. Make sure these match!)
You're correct in thinking that you're creating a new instance of mainViewController
. To get at the one you want, You'll either need to pass a reference to mainViewController
into the new view controller when you create it, writing a method like:
@synthesize mainViewController; -(void) initWithMainVC:(MainViewController *)mainVC { if ((self = [super init])) { self.mainViewController = mainVC; } return self; }
to override init
, or, if you've got a reference to mainViewController
in your App Delegate, you can get it using:
MainViewController *mainVC = [(YourAppDelegate *)[[UIApplication sharedApplication] delegate] mainViewController];
Either way you choose, you'll want to read up on object oriented programming and pointers in objective C. When you call alloc
, you're manufacturing a new copy of that class. All copies sit in different chunks of memory, so any new one you make (as in your code above) is actually a totally different entity, like two Priuses, or something like that.
A pointer is like a nametag that identifies, or points the way, to that block of memory. In my init
code example above, we're attaching a new nametag to a mainViewController
instance with the same guts. Same thing with the second line -- we make a new pointer (see the star?) tell it it's going to be pointing to a MainViewController
instance, and slap that nametag, or pointer, on to an instance.
(The second one is a little more complicated, as you're plucking mainViewController
from an object called a singleton, or an object that you can get at from anywhere... read more about those and the App Delegate at this post from Cocoa with Love.)
Anyway, I get nervous expounding on this stuff on Stack! Check out Apple's Objective C reference for some more of the basics. The sample code on the iOS Dev Center is really, really good to check out. Download a project that looks nice, or, better yet, just create a project from an Xcode template, and go try to figure out how it's stitched together. Good luck!
-10514710 0If you want anything starting with page1 to be rewritten, this will work:
RewriteRule ^page1.* http://www.example.com/newpage.htm [R=301,L]
If you want only page1 and page1.htm to be rewritten, but not e.g. page1whatever, this should work:
RewriteRule ^page1(.htm)? http://www.example.com/newpage.htm [R=301,L]
-12911179 0 You must specify the following property
sonar.host.url=http://localhost:9100
, if you want Sonar batch to connect to the correct URL.
You can set it either as a property in your Ant script or a JVM parameter.
-4666017 0You can access faster to local vars, also you can shorten the variable name "window" (and even "document") with something like:
(function(w, d)(){ // use w and d var })(window, document)
-32518542 0 How to set up dc.js x axis for dates I have a CSV file with 2 columns, in the first I have got some dates, in the second there are some values.
How do I initialize the x axis to show dates?
-21929808 0c_str
is a method on a string, so you need to call it like cell.c_str()
to tell the compiler is a method, not a class member
My opinion is that you can remove the george_holiday_passengers
and add the type,age,gender
columns to the george_holiday_users
as looking to it; its only a extended data of the holiday_users
table and build query with your new database tables.
$query = $this->db->select('u.*, p.package_name, p.description') ->from('george_holiday_users u') ->join('george_packges p', 'u.package_id = p.id', 'left') ->get(); return $query->result();
anyway, you can achieved the result using this query.
$query = $this->db->select('u.*, hp.type, hp.name AS passengers_name, hp.age, hp.gender, p.package_name, p.description') ->from('george_holiday_users u') ->join('george_holiday_passengers hp', 'hp.user_id = u.id', 'left') ->join('george_packges p', 'u.package_id = p.id', 'left') ->get(); return $query->result();
you should be careful about the column names because on your database there are a lot of columns with the same names, It might affect your query when your using joins, etc.
Hope that helps.
-23446458 0Do you really use command dir
in your batch file or another command, a command which itself is enclosed in double quotes because of a space in path or has a parameter in double quotes?
If the output of a command should be processed within the loop and the command itself must be specified in double quotes or at least one of its parameters, the following syntax using back quotes is required:
for /f "usebackq delims=" %%a in (`"command to run" "command parameter"`) do echo %%a
An example:
for /f "usebackq delims=" %%a in (`dir "%CommonProgramFiles%"`) do echo %%a
%CommonProgramFiles%
references the value of environment variable CommonProgramFiles which is a directory path containing usually spaces. Therefore it is necessary to enclose the parameter of command dir
in double quotes which requires the usage of usebackq
and back quotes after the opening and before the closing round bracket.
Further I suggest to look on value of environment variable PATH. There are applications which add their program files directory to PATH during installation, but not by appending the directory to end of the list of directories, but by inserting them at beginning. That is of course a bad behavior of the installer of those applications.
If you call in your batch file standard Windows commands not located in cmd.exe, but in Windows system directory which is usually the first directory in PATH, like the command find
, and the installed application by chance has also an executable with same name in the program files directory of the application, the batch file might not work on this computer because of running the wrong command.
It is safer to use instead of just find
in a batch file %SystemRoot%\system32\find.exe
to avoid problems caused by bad written installer scripts of applications modifying the PATH
list on wrong end.
I have three System.Array where I store basically phone numbers with 10 characters. The definition is this:
private static System.Array objRowAValues; private static System.Array objRowBValues; private static System.Array objRowCValues;
I do this because I read a huge Excel file with many cells (around 1 000 000) and process with List<string>
is a bit slow. Later in my code I change the System.Array to a List<string>
mainly because I fill a ListBox elements. These are the definition for the List
private List<string> bd = new List<string>(); private List<string> bl = new List<string>(); private List<string> cm = new List<string>();
I want to check if any values in objRowAValues exists in objRowBValues or in objRowCValues and if exists then remove the existent value, how can I do this? I'm newbiew with C# and this is my first steps.
EDIT: here is the code (relevant parts only) of what I'm doing:
private List<string> bd = new List<string>(); private static System.Array objRowAValues; private List<string> bl = new List<string>(); private static System.Array objRowBValues; private List<string> cm = new List<string>(); private static System.Array objRowCValues; private List<string> pl = new List<string>(); private static Microsoft.Office.Interop.Excel.Application appExcel; Excel.Application xlApp; Excel.Workbook xlWorkBook; Excel.Worksheet xlWorkSheet; Excel.Range rngARowLast, rngBRowLast, rngCRowLast; long lastACell, lastBCell, lastCCell, fullRow; // this is the main method I use to load all three Excel files and fill System.Array and then convert to List<string> private void btnCargarExcel_Click(object sender, EventArgs e) { if (this.openFileDialog1.ShowDialog() == DialogResult.OK) { if (System.IO.File.Exists(openFileDialog1.FileName)) { Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); Thread.Sleep(10000); filePath.Text = openFileDialog1.FileName.ToString(); xlApp = new Microsoft.Office.Interop.Excel.Application(); xlWorkBook = xlApp.Workbooks.Open(openFileDialog1.FileName, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0); xlWorkSheet = (Excel.Worksheet) xlWorkBook.Worksheets.get_Item(1); fullRow = xlWorkSheet.Rows.Count; lastACell = xlWorkSheet.Cells[fullRow, 1].End(Excel.XlDirection.xlUp).Row; rngARowLast = xlWorkSheet.get_Range("A1", "A" + lastACell); objRowAValues = (System.Array) rngARowLast.Cells.Value; foreach (object elem in objRowAValues) { bd.Add(cleanString(elem.ToString(), 10)); } nrosProcesados.Text = bd.Count().ToString(); listBox1.DataSource = bd; xlWorkBook.Close(true, null, null); xlApp.Quit(); releaseObject(xlWorkSheet); releaseObject(xlWorkBook); releaseObject(xlApp); stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; executiontime.Text = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds/10).ToString(); } else { MessageBox.Show("No se pudo abrir el fichero!"); System.Runtime.InteropServices.Marshal.ReleaseComObject(appExcel); appExcel = null; System.Windows.Forms.Application.Exit(); } } } // This is the method where I clean the existent values from bd (the List where I should remove existent values on bl and existent values on cm private void btnClean_Click(object sender, EventArgs e) { pl = bd; Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); Thread.Sleep(10000); pl.RemoveAll(element => bl.Contains((element))); pl.RemoveAll(element => cm.Contains((element))); textBox2.Text = pl.Count.ToString(); listBox4.DataSource = pl; stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; textBox6.Text = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10).ToString(); }
-29205252 0 Android: java.lang.StringIndexOutOfBoundsException: on copy to clipboard selected text on long press event In my app I would like to give copy to clipboard selected text functionality on long press event.foo is a text view foo = (TextView) findViewById(R.id.single_string);. I am using the below code to implement this functionality.
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); activateToolbar(); text = parseSourceCode(text); foo = (TextView) findViewById(R.id.single_string); foo.setTextSize(mRatio + 14); foo.setText(Html.fromHtml(text,imgGetter, null)); foo.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { String stringYouExtracted = foo.getText().toString(); int startIndex = foo.getSelectionStart(); int endIndex = foo.getSelectionEnd(); stringYouExtracted = stringYouExtracted.substring(startIndex, endIndex); if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) { android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); clipboard.setText(stringYouExtracted); } else { android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); android.content.ClipData clip = android.content.ClipData.newPlainText("Copied Text", stringYouExtracted); clipboard.setPrimaryClip(clip); } // TODO Auto-generated method stub return false; } });
I am able to set the text but my code is getting crashed when I press long on the screen to copy the selected text. Error I am getting is :
java.lang.StringIndexOutOfBoundsException: length=3704; regionStart=-1; regionLength=0 at java.lang.String.startEndAndLength(String.java:504) at java.lang.String.substring(String.java:1333) at java.lang.String.subSequence(String.java:1671) –
-21501160 0 addGestureRecognizer is a method on UIView, not UIViewController.
Try
[self.view addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(isTapped:)]];
-35397885 0 I encountered this issue as you did. I got an error that's something like "couldn't find package Emacs-24.4". This inspired me to install Emacs-24.4
on my Ubuntu, instead of older version 24.3
which is the newest I can get from apt-get
. (A convincing fact is that the newer version 24.5
provided by Homebrew
works well with Purcell's package on my Mac.)
Under Emacs 24.4
, slime
proved to run well with Purcell's .emacs.d/
. But it really costs me a lot of time to install Emacs-24.4
on my Ubuntu. First, I had to solve the problems of dependencies. Using aptitude
, I get rid of the problem which apt-get
failed to solve:
sudo apt-get install aptitude sudo aptitude install build-essential sudo aptitude build-dep emacs24
When the dependency issue pops out, aptitude
will give you some suggestions including downgrading your current packages. I chose solutions of downgrade without leaving over any unsolved dependency problem (select 'no' until you find an acceptable one). During reinstalling build packages, Ubuntu iso cdrom may be required.
Then install Emacs 24.4
:
wget http://open-source-box.org/emacs/emacs-24.4.tar.xz tar xvf emacs-24.4.tar.xz cd emacs-24.4 ./configure --prefix=$HOME/.local LDFLAGS=-L$HOME/.local/lib --without-pop --without-kerberos --without-mmdf --without-sound --without-wide-int --without-xpm --without-jpeg --without-tiff --without-gif --without-png --without-rsvg --without-xml2 --without-imagemagick --without-xft --without-libotf --without-m17n-flt --without-xaw3d --without-xim --without-ns --without-gpm --without-dbus --without-gconf --without-gsettings --without-selinux --without-gnutls --without-x make && make install
References:
https://gist.github.com/tnarihi/6054dfa7b4ad2564819b
http://linuxg.net/how-to-install-emacs-24-4-on-ubuntu-14-10-ubuntu-14-04-and-derivative-systems/
-26217398 0 Cannot get div element by id to display gif in internet explorerI am trying to make a .gif image display in a loading window to alert my user that loading is underway, quite simple. I was doing it using only css and background
property like this:
/background: url(ajax-loader.gif) no-repeat center #fff;/
but my .gif was not loading in internet explorer. So I've made a research and found this and, based on J.Davies's solution, I have implemented this instead in my js file:
function ShowProgress() { if (!spinnerVisible) { $('div#layer').fadeIn("fast"); $('div#spinner').fadeIn("fast"); spinnerVisible = true; var pb = $('#spinner'); pb.innerHTML = '<img src="./ajax-loader.gif" width=200 height=40/>'; pb.style.display = ""; } }
My problem is that it works still in chrome, but I get a crash in internet explorer saying that it pb is undefined. Is there a specificity on how to work with jquery and internet explorer? For information, here's my display:
<div id="body"> @RenderSection("featured", false) <section class="content-wrapper main-content clear-fix"> <section> @Html.Partial("MessageDisplay") </section> <div id="layer"></div> <div id="spinner"> Loading, please wait... </div> @RenderBody() </section> </div>
And the css saying that spinner and layer div are hidden:
div#spinner { display: none; width: 300px; height: 300px; position: fixed; top: 40%; left: 45%; /*background: url(ajax-loader.gif) no-repeat center #fff;*/ text-align: center; padding: 10px; font: normal 16px Tahoma, Geneva, sans-serif; border: 1px solid #666; margin-left: -50px; margin-top: -50px; z-index: 2; overflow: auto; } div#layer { display: none; width: 100%; height: 100%; position: fixed; top: 0; left: 0; background-color: #a4a3a3; background-color: rgba(164, 163, 163, 0.5); z-index: 1; overflow: auto; -moz-opacity: 0.5 }
-12810133 0 link static library in c++ visual studio can someone please help me to understand the process.
in c++ visual studio 2010
i have a visual studio solution (lets call it mysol)
i have a project built as a static library (let's call it staticprj) staticprj needs to use a library from outside (lets call it ext.lib)
in the body of the source code of staticprj i include outside library header file with # include extlib.h and make calls to some of its functions (let call them extfunctions()) i also include the the path to the header files location of the ext.lib.
the staticprj compiles okay without errors
the mysol also has another project which is a dynamic library (dynprj) and which depends on the staticprj.
also in the source files of the dynprj uses functions from outside library.
i have included #include extlib.h in the source code of dynprj. i have included the path of the header files i have attached extlib.h directly to the dynprj i have also added ext.lib to the linker input (along with the path where the ext.lib resides).
i still get a lnk2001 error stating that extfunctions() where not found.
the whole structure (the mysol solution) compiles okay if i do not use ext.lib at all.
my question is how does the linking process works and what can i do to correct this linking error.
(note that without the presence of ext.lib my linking of the staticprj and dynprj is fine. my compilation works okay and my code works. i only get the linking error when i try to link another ext.lib to staticprj and dynprj and use functions from ext.lib)
thanks in advance.
-15570462 0I don't know about that other editor, but for Vim syntax highlighting, this is definitely not possible. Why?
If you just want similar colors in Eclipse, you can certainly re-create your Vim colorscheme in another editor. The output of :highlight
gives you all defined groups and their color values.
Please, try this query (also on SQL Fiddle):
SELECT p.id, p.user_id, m.username, m.privacy, searcher.username "Searcher", p.status_msg FROM posts p JOIN members m ON m.id = p.user_id LEFT JOIN following f ON p.user_id = f.user_id JOIN members searcher ON searcher.username = 'userA' WHERE (m.privacy = 0 OR (m.privacy = 1 AND f.follower_id = searcher.id) OR m.id = searcher.id) AND p.status_msg LIKE '%New%' ORDER BY p.id LIMIT 5;
I removed username
field from posts
table, as it is redundant. Also, I named tables and columns slightly different, so query might need cosmetic changes for your schema.
The first line in the WHERE
clause is the one that you're looking for, it selects posts in the following order:
searcher
;EDIT:
This query is using original identifiers:
SELECT p.id, p.`userID`, m.username, m.privacy, searcher.username "Searcher", p.`statusMsg` FROM posts p JOIN `myMembers` m ON m.id = p.`userID` LEFT JOIN following f ON p.`userID` = f.user_id JOIN `myMembers` searcher ON searcher.username = 'userD' WHERE (m.privacy = 0 OR f.follower_id = searcher.id OR m.id = searcher.id) AND p.`statusMsg` LIKE '%New%' ORDER BY p.id LIMIT 5;
EDIT 2:
To avoid duplicates in case there're several followers for the user from the posts
table, join and filtering conditions should be changed the following way (on SQL Fiddle):
SELECT p.id, p.user_id, m.username, m.privacy, searcher.username "Searcher", p.status_msg FROM posts p JOIN members m ON m.id = p.user_id JOIN members searcher ON searcher.username = 'userC' LEFT JOIN following f ON p.user_id = f.user_id AND follower_id = searcher.id WHERE (m.privacy = 0 OR (m.privacy = 1 AND f.id IS NOT NULL) OR m.id = searcher.id) ORDER BY p.id LIMIT 5;
-27549500 0 I think msmq's answer is valid, but you should be a little careful about using the main info.plist this way. Doing that suggests that all your versions of info.plist are almost identical, except for a couple of differences. That's a recipe for divergence, and then hard-to-debug issues when you want to add a new URI handler or background mode or any of the other things that might modify info.plist.
Instead, I recommend you take the keys that vary out of the main info.plist. Create another plist (say "Config.plist") to store them. Add a Run Script build phase to copy the correct one over. See the Build Settings Reference for a list of variables you can substitute. An example script might be:
cp ${SOURCE_ROOT}/Resources/Config-${CONFIGURATION}.plist ${UNLOCALIZED_RESOURCES_FOLDER_PATH}/Config.plist
Then you can read the file using something like this (based on Read in the Property List):
NSString *baseURL; NSString *path = [[NSBundle mainBundle] pathForResource:@"Config" ofType:@"plist"]; NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath]; NSString *errorDesc = nil; NSDictionary *dict = (NSDictionary *)[NSPropertyListSerialization propertyListFromData:plistXML mutabilityOption:NSPropertyListImmutable format:NULL errorDescription:&errorDesc]; if (dict != nil) { baseUrl = dict[@"baseURL"]; } else { NSAssert(@"Could not read plist: %@", errorDesc); // FIXME: Return error }
There are other solutions of course. I personally generally use the preprocessor for this kind of problem. In my build configuration, I would set GCC_PREPROCESSOR_DEFINITIONS
to include BaseURL=...
for each build configuration and then in some header I would have:
#ifndef BaseURL #define BaseURL @"http://default.example.com" #endif
The plist way is probably clearer and easier if you have several things to set, especially if they're long or complicated (and definitely if they would need quoting). The preprocessor solution takes less code to process and has fewer failure modes (since the strings are embedded in the binary at compile time rather than read at runtime). But both are good solutions.
-20617512 0You are trying to connect to a local instance of RabbitMQ.
BROKER_URL = 'amqp://guest:guest@localhost:5672/'
in your settings.py). If you are working currently on development, you could avoid setting up Rabbit and all the mess around it, and just use a development-version of a Message Queue with the Django Database.
Do this by replacing your previous configuration with
BROKER_URL = 'django://' and add this app:
INSTALLED_APPS += ('kombu.transport.django', )
Finally, launch the worker with
./manage.py celery worker --loglevel=info
Source: http://docs.celeryproject.org/en/latest/getting-started/brokers/django.html
-10737118 0The easiest way to go about it is to offload it to separate process using ztask.
from django_ztask.decorators import task @task() def delayed_save(obj): obj.save() ... your_object.something = "something" delayed_save.async(your_object)
-14476479 0 Using mail() to send an attachment AND text/html in an email in PHP4 To make life difficult, the client I'm working for is using a really large yet old system which runs on PHP4.0 and they're not wanting any additional libraries added.
I'm trying to send out an email through PHP with both an attachment and accompanying text/html content but I'm unable to send both in one email.
This sends the attachment:
$headers = "Content-Type: text/csv;\r\n name=\"result.csv\"\r\n Content-Transfer-Encoding: base64\r\n Content-Disposition: attachment\r\n boundary=\"PHP-mixed-".$random_hash."\""; $output = $attachment; mail($emailTo, $emailSubject, $output, $headers);
This sends text/html:
$headers = "Content-Type: text/html; charset='iso-8859-1'\r\n"; $output = $emailBody; // $emailBody contains the HTML code.
This sends an attachment containing the text/html along with the attachment contents:
$headers = "Content-Type: text/html; charset='iso-8859-1'\r\n".$emailBody."\r\n"; $headers = "Content-Type: text/csv;\r\n name=\"result.csv\"\r\n Content-Transfer-Encoding: base64\r\n Content-Disposition: attachment\r\n boundary=\"PHP-mixed-".$random_hash."\""; $output = $attachment;
What I need to know is how can I send an email with text/html in the email body and also add an attachment to it. I'm sure I'm missing something really simple here!
Thanks in advance.
-37484024 0Here is your code converted to PDO.
// Make sure the email address is available: $q = $dbc->query("SELECT user_id FROM users WHERE email=?"); $q->execute(array($e)); $r = $q->fetchColumn(); if (!$r) { // Available. // Create the activation code: $a = md5(uniqid(rand(), true));
Three things has been corrected
fetchColumn
have to be used instead of fetchAll
Def recadd(lis): If lis[0] + lis[1] - lis[2]] = lis[3]: return lis Else: recadd(lis[3] + lis[0:2]) recadd(lis[0] + lis[3] + lis[1:2]) recadd(lis[0:1] + lis[3]. + lis[2])
Quick and dirty hack on my mobile, could be elegantly expanded for k numbers, untested but it should work.
Edit: realized this won't work if there is no solution.infinite recursion...
-23916553 0try this
def bookList() = { val res = resource.getAssets.open("demo.png") val image = Drawable.createFromStream(res, "demo.png") val map = Map[String, Drawable]() for (i <- 1 to 100) { map += (s"test book$i" -> image) } map }
-6471481 0 This may be useful:
http://gcc.gnu.org/onlinedocs/gcc-4.1.1/cpp/Search-Path.html#Search-Path
I have tried to create a C# application that saves data to an existing local SQL database. I created a local database called AccountDatabase.mdf
which has a table called AccountTable
in it. I first started with an empty table. I then used the code below to get the application to save the input data to the database.
private void FPAccountNotExist_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { //Make forgot password page invisible and create new account page visible ForgotPassword.Visible = false; CreateNewAccount.Visible = true; //Set text content of labels on create new account page CreateNewAccountTitle.Text = "Create New Account"; CNAConfirmLabel.Text = "Confirm Password"; CNAEmailLabel.Text = "Email"; CNAInstruction.Text = "Please fill in the following details."; CNAOpenAccount.Text = "Submit new account"; CNAPasswordLabel.Text = "Password"; CNAUsernameLabel.Text = "Username"; OpenManual.Text = "Start with Manual"; CNAConfirmTextBox.UseSystemPasswordChar = true; CNAPasswordTextBox.UseSystemPasswordChar = true;
}
private void CNAOpenAccount_Click(object sender, EventArgs e) { AccountVariables.ConfirmedPassword = CNAConfirmTextBox.Text; AccountVariables.Email = CNAEmailTextBox.Text; AccountVariables.Password = CNAPasswordTextBox.Text; AccountVariables.Username = CNAUsernameTextBox.Text; //GeneralVariables.ManualOption = OpenManual.Checked; var CreateNewAccountStrings = new List<string> { AccountVariables.ConfirmedPassword, AccountVariables.Password, AccountVariables.Email, AccountVariables.Username }; if (CreateNewAccountStrings.Contains("")) { MessageBox.Show("All textboxes should be filled"); } else { if ((AccountVariables.ConfirmedPassword == AccountVariables.Password) && (AccountVariables.Password.Length >= 8)) { accountTableTableAdapter.Fill(accountDatabaseDataSet.AccountTable); AccountVariables.defaultAccountRow = AccountVariables.defaultAccountRow + 1; AccountVariables.newAccountTableRow = accountDatabaseDataSet.AccountTable.NewAccountTableRow(); AccountVariables.newAccountTableRow.UserId = AccountVariables.defaultAccountRow; AccountVariables.newAccountTableRow.Username = AccountVariables.Username; AccountVariables.newAccountTableRow.Email = AccountVariables.Email; AccountVariables.newAccountTableRow.Password = AccountVariables.Password; accountDatabaseDataSet.AccountTable.AddAccountTableRow(AccountVariables.newAccountTableRow); accountTableTableAdapter.Update(accountDatabaseDataSet.AccountTable); accountDatabaseDataSet.AccountTable.AcceptChanges(); AccountVariables.AccountDatabaseConnection.Close(); } } }
However, when I closed the program after running the application, I looked in the database and saw that the rows had not been saved, even after I have saved it. Please can you help me solve this problem.
-13341544 0I would first try to optimze your query. Is it slow in SSMS? Do you use proper indices? Do you need all columns. Most important: do you need all 50000 rows to be displayed?
50000 records are not many records, but it's unusual to show all in a web application since that means you have to generate the HTML for all records and display it in the client's browser(maybe even using ViewState
). So i would suggest to use database paging(f.e. via ROW_NUMBER
function) to partition your resultset and query only the data you want to show(f.e. 100 rows per page in a GridView
).
Efficiently Paging Through Large Amounts of Data
-39130085 0Object json = mapper.readValue(input, Object.class); String indented = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);
-13966814 0 You can merge all of your string in one string by StringBuilder
and apply it to the TextView
.
I've implemented my own TextView with scrolling by wrapping textview (and maybe some other views)
private Runnable scrollRight = new Runnable() { @Override public void run() { // can control scrolling speed in on tick topScroll.smoothScrollBy(1, 0); } };
and in new Thread I invoke:
while (!interruptScroll){ try{ Thread.sleep(50); // control ticking speed } catch (InterruptedException e){ e.printStackTrace(); } topScroll.post(scrollRight); }
and by manually scrolling the scrollView i interrupt the scrolling (such an automatic scrolling while not interrupted by user).
-29392238 0Using HtmlAgilityPack (HAP) and XPath function name()
didn't work for me, but replacing name()
with local-name()
did the trick :
//*/@*[starts-with(local-name(), 'on')]
However, both SelectSingleNode()
and SelectNodes()
only able to return HtmlNode
(s). When the XPath expression selects an attribute instead of node, the attribute's owner node would be returned. So in the end you still need to get the attribute through some options besides XPath, for example :
HtmlDocument doc; ...... var link = doc.DocumentNode .SelectSingleNode("//*/@*[starts-with(local-name(), 'on')]"); var onclick = link.Attributes .First(o => o.Name.StartsWith("on"));
-23678485 0 Adding parameters to URL in ZF2
I am trying to construct url which looks like this:
abc.com/folder?user_id=1&category=v
Followed the suggestion given in this link:
How can you add query parameters in the ZF2 url view helper
Initially, it throws up this error
Query route deprecated as of ZF 2.1.4; use the "query" option of the HTTP router\'s assembling method instead
Following suggestion, I used similar to
$name = 'index/article'; $params = ['article_id' => $articleId]; $options = [ 'query' => ['param' => 'value'], ]; $this->url($name, $params, $options);
Now, I am getting syntax error saying,
Parse error: syntax error, unexpected '[' in /var/www/test/module/Dashboard/view/dashboard/dashboard/product.phtml on line 3
My module.config.php is configured like this:
'browse_test_case' => array( 'type' => 'Literal', 'options' => array( 'route' => '/browse-case[/:productId]', 'defaults' => array( 'controller' => 'Test\Controller\Browse', 'action' => 'browse-test-case', ), ), 'may_terminate' => true, 'child_routes' => array( 'query' => array( 'type' => 'Query', ), ), ),
Any Idea, please help!
-119732 0 How to initialize Hibernate entities fetched by a remote method call?When calling a remote service (e.g. over RMI) to load a list of entities from a database using Hibernate, how do you manage it to initialize all the fields and references the client needs?
Example: The client calls a remote method to load all customers. With each customer the client wants the reference to the customer's list of bought articles to be initialized.
I can imagine the following solutions:
Write a remote method for each special query, which initializes the required fields (e.g. Hibernate.initialize()) and returns the domain objects to the client.
Like 1. but create DTOs
Split the query up into multiple queries, e.g. one for the customers, a second for the customers' articles, and let the client manage the results
The remote method takes a DetachedCriteria, which is created by the client and executed by the server
Develop a custom "Preload-Pattern", i.e. a way for the client to specify explicitly which properties to preload.
I would like to store a ABRecordRef in a 'Client' entity in core data.
I have read in apples documentation that ABRecordRef is a primitive C data type. As far as I am aware, you can only insert objects in core data. With this in mind, what is the best way to store it in core data?
I thought about converting it into a NSNumber for storage, but dont know how to convert it back to ABRecordRef for use.
I also thought I could just put it in a NSArray/NSSet/NSDictionary on its own just acting as a wrapper but didnt know if this was silly/inefficient/would even work.
Thoughts appreciated.
Many thanks
-22052735 0 Trace a curve with two colors?is there a way to have a curve with two colors, well i have many curves in my plot. But I like to add a specific characteristic, i want the curve 1 to be simple line in[a,b] interval, and dotted line in interval [b,c].
an example of my graph:
plot exp(-x**2 / 2), sin(x)
can we make sin(x) plotted in dotted line from[0,5]
thanks in advance.
-31312465 0 How to avoid duplicate insert of ToolbarItem in Xamarin.forms?protected override void OnAppearing(){ ToolbarItem itemStudy = new ToolbarItem { Name = "Study", Order = ToolbarItemOrder.Primary, Command = new Command (() => Navigation.PushAsync (studyPage)) }; if (ToolbarItems.Count > 0) { ToolbarItems.RemoveAt(0); } ToolbarItems.Add (itemStudy); }
This is my Code snipped on Xamarin.forms for adding Toolbaritem. Anyhow I don't think this is an elegant way and looking for better solution. Can anyone help? Thanks.
-34020483 0 Where is PFFile saved?I save UIImage as PFFile:
let imageFile = PFFile(data: imageData) imageFile?.saveInBackgroundWithBlock({})
This file is not referenced with any PFObject, so what happens to him?
This file is saved on my reserved storage (20GB)?
Is there any tool for clean non-referenced files?
If I assign some PFFile to object and replace it by other PFFile after that, first object will be deleted?
I think what you will see is just differences in coding practice.
If all child classes have the same exact init()
method, there is no reason to even have the method declared within the child classes.
In some cases, however I have seen developers do exactly what you have shown. In a lot of cases this may because the eventual intent may be to somehow augment the parent method behavior in a way specific to the class. In other cases, I have seen some collection of children classes override the functionality, so the developer puts a method like this in all child classes just so the intent (execute parent method as is for this child class) is clear to other developers.
-15086294 0You can also do it like tihs:
public static function generateCode($length = 6) { $az = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $azr = rand(0, 51); $azs = substr($az, $azr, 10); $stamp = hash('sha256', time()); $mt = hash('sha256', mt_rand(5, 20)); $alpha = hash('sha256', $azs); $hash = str_shuffle($stamp . $mt . $alpha); $code = ucfirst(substr($hash, $azr, $length)); return $code; }
-8972776 0 Yes - you or have to introduce date_of_entry field or some other vector field like IDENTITY
. For example if column Id
is your INT IDENTITY
, then your query will look like this:
;WITH cte AS (SELECT ROW_NUMBER() OVER (PARTITION BY person_id, date_work, hours ORDER BY ( SELECT Id DESC)) RN FROM work_hours) DELETE FROM cte WHERE RN > 1
Of course it is valid if nobody changes the values in IDENTITY
column
And if your conditions suits - then you may want to use column Hours
as your vector field within grouping range of person_id, date_work
And even better way is to have an UNIQUE INDEX
over columns person_id, date_work, hours
, then there will no any ability to add duplicates.
If I run the site using the internal Visual Studio web server, I get the failed to map path error.
-35561493 0There's a few ways to clean this up in Ruby that I'll demonstrate here:
puts 'Hello mate what is thy first name?' name1 = gets.chomp # Inline string interpolation using #{...} inside double quotes puts "Your name is #{name1} eh? What is thy middle name?" name2 = gets.chomp # Interpolating a single string argument using the String#% method puts 'What is your last name then %s?' % name1 name3 = gets.chomp # Interpolating with an expression that includes code puts "Oh! So your full name is #{ [ name1, name2, name3 ].join(' ') }?" puts 'That is lovey!' # Combining the strings and taking their aggregate length puts 'Did you know there are %d letters in your full name?' % [ (name1 + name2 + name3).length ] # Using collect and inject to convert to length, then sum. puts 'Did you know there are %d letters in your full name?' % [ [ name1, name2, name3 ].collect(&:length).inject(:+) ]
The String#%
method is a variant of sprintf
that's very convenient for this sort of formatting. It gives you a lot of control over presentation.
That last one might look a bit mind-bending but one of the powerful features of Ruby is being able to string together a series of simple transformations into something that does a lot of work.
That part would look even more concise if you used an array to store the name instead of three independent variables:
name = [ ] name << gets.chomp name << gets.chomp name << gets.chomp # Name components are name[0], name[1], and name[2] # Using collect -> inject name.collect(&:length).inject(:+) # Using join -> length name.join.length
It's generally a good idea to organize things in structures that lend themselves to easy manipulation, exchange with other methods, and are easy to persist and restore, such as from a database or a file.
-2773791 0I finally got the solution. The problem was with the field's verbose name - it was str instead of unicode. Moving to unicode helped.
Thanks :-)
-39429247 0you can use the all
method.
Book.all
This will return all of the books on record.
-25918441 0 Creating links relative to localhostI'm trying to create a custom menu in drupal 7 by coding it in a custom code block, but I'm running into the issue that the links I create aren't lined up to the way my local site is setup. Is there php code or a drupal setting of some sort that can create a link relative to the local machine setup?
To give more context: My friend and I are working on creating a drupal site and have individually setup our local files differently (we are sharing the database which is on a remote server). When browsing to the site, his URL shows up: localhost/content/page
. Whereas how I have it setup is: localhost/sitename/content/page
.
When I create an internal link in the nav menu, I have to create it using a relative path /content/page, otherwise the link wont work on my coworkers localhost. This, in turn, makes it so that the link doesn't work on my locahost.
Is there a way I can create these links relative to the localhost so that it works on both machines? When creating a navigation menu using my Drupal theme this is not an issue, but since the link list I'm creating is custom coded, I can't seem to figure out how to mimic this same functionality.
Any ideas? Thanks!
-5588023 0 ASP.NET MVC - How to re-run jQuery tabs script after getJSON call?I have some data wrapped in 3 divs, each div represents a 'tab', and a jQuery script to create the tab effect. The 3 tabs include hours of operation, contact info, location info.
Pretty standard, nothing special. When the page loads, the following script is run, creating the 'tab' effect.
$(document).ready(function () { tabs({ block: "#branch" }); });
I have a drop down list that triggers a call to an action that returns a JsonResult, and the following code to handle the change:
$("#branches").change(function () { $("#branches option:selected").each(function () { $.getJSON("/Branch/JsonBranch/" + $(this)[0].value, null, function (data) { $("#branchinfo").html(data); }); }); });
The action is a variation on the post ASP.NET MVC - Combine Json result with ViewResult
The action code isn't relevant. The problem is that, since I'm not reloading the whole page, the 'tab' script is never run again. So, once the html code is replaced, ALL the data shows, the tabs are not created.
Is there a way to run the tab script again after just reloading that one portion of the page? I tried adding the call to tabs() in the .change() function call, but that didn't work.
Any help would be appreciated! Thanks!
-22077268 0The above code will only run once only which will add information to head only once. If you want to add more information in case of second run then add code for else condition. Example:-
if ( head == NULL ) { // code to insert data in case of first run }else{ // code to insert data for second run and so..... }
-32280035 0 Prevent IE caching AngularJS/Restangular In IE, when I make an update to or destroy an item in a list, the action is successful, but the updated list/data is not returned from the server, thus the list is not being updated in the view.
I've tried the following to no avail:
angular.module('casemanagerApp') .config(function($stateProvider, $urlRouterProvider, RestangularProvider) { if (!RestangularProvider.setDefaultHeaders) { RestangularProvider.setDefaultHeaders({}); } RestangularProvider.setDefaultHeaders({'If-Modified-Since': 'Mon, 26 Jul 1997 05:00:00 GMT'}); RestangularProvider.setDefaultHeaders({'Cache-Control': 'no-cache'}); RestangularProvider.setDefaultHeaders({'Pragma': 'no-cache'}); $stateProvider ... });
Can anyone point me in the right direction for a solution to this?
-37733893 0 Squash git commits from topic branchI have a topic branch (macaroni), and I have submitted a pull request. I had to make a change after feedback. It was requested that I squash the two commits into a single commit. This is what I have done:
git status On branch macaroni git log commit def feedback fixes commit abc fix cheddar flavor git rebase -i origin/master .. go through screen where I pick commit to squash .. .. go through screen where I update commit message .. git log commit abc fix cheddar flavor, squashing done!
at this point I believe I have to push my topic branch using the -force flag, because I have changed history:
git push -f
I am using the second answer from this question:
Preferred Github workflow for updating a pull request after code review
with subtitle "Optional - Cleaning commit history". The author mentions at the end that you should be using topic branches, not sure if I should have changed any of the commands since I'm already on a topic branch.
I am also concerned with accidentally force-pushing something onto the master branch with the above since I'm using -f, but since I'm on the topic branch, only that branch should be affected, right?
Thanks
-38084853 0 how to show a window only one time?I want display a window only one time. When the user click on this button:
private void Notification_Click(object sender, RoutedEventArgs e) { NotificationSettings notifications = new NotificationSettings(); notifications.ShowDialog(); }
this will create a new window, I want that if there is already a window opened the user can't open a new one. There is an option in xaml for tell to compiler this? I remember the vb.net with windows form that allow to set the option to show only one windows at time.
Thanks.
-10302647 0If you want to pass the whole list in a single parameter, use array datatype:
SELECT * FROM word_weight WHERE word = ANY('{a,steeple,the}'); -- or ANY('{a,steeple,the}'::TEXT[]) to make explicit array conversion
-5108964 0 Attached databases in Honeycomb Has anyone ran into attached database issues with Honeycomb yet? My application uses attached databases (working on 1.5 through 2.3) using the statements:
...
String newDb = "/data/data/com.stuff.app/databases/mydata.db"; db.execSQL("attach database ? as newDb", new String[] {newDb}); String[] columns = MY_COL_NAMES; String orderBy = DEFAULT_SORT_ORDER; Cursor cursor = db.query("newDb.mydata", columns, null, null, null, null, orderBy);
...
This is working (1.5 through 2.3) regardless of the actual location of the sqlite database file (local or SD Card)...However, in Honeycomb, the db.query statement results in a "I/SqliteDatabaseCpp( 628): sqlite returned: error code = 1, msg = no such table: newDb.mydata ..."
I can manually attach the database from within sqlit3 by issuing the statement:
sqlite3>attach database '/data/data/com.stuff.app/databases/mydata.db' as newDb;
Any help resolving this would be greatly appreciated.
-9047001 0If your receiver must know the concrete type, then you're not using Interfaces properly.
If you're returning a page, there's really no reason for anything to know what kind of page it is. I would add a Render
method to the IPage
interface so that all the receiver has to do is call Render()
and the page will handle the rest.
The collection is a reference type, so other holding code onto that will see the old data.
Two possible solutions:
Instead of data = temp use data.Clear(); data.AddRange(temp) which will change the contents of the data field.
Or better delete the MyCollection property and make class implement IEnumerable. This results in much better encapsulation.
-18949117 0Assuming a dash following a space or vice versa is ok:
^( -?|- ?)?(\d( -?|- ?)?){9,13}$
Explanation:
( -?|- ?)
- this is equivalent to ( | -|-|- )
. Note that there can't be 2 consecutive dashes or spaces here, and this can only appear at the start or directly after a digit, so this prevents 2 consecutive dashes or spaces in the string.
And there clearly must be exactly one digit in (\d( -?|- ?)?)
, thus the {9,13}
enforces 9-13 digits.
Assuming a dash following a space or vice versa is NOT ok:
^[ -]?(\d[ -]?){9,13}$
Explanation similar to the above.
Both of the above allows the string to start or end with a digit, dash or space.
-37299020 0Instance types are cached in the browser's local storage. You can explicitly refresh the cache via the 'Refresh all caches' link:
If you show the network tab of your browser's console (prior to clicking 'Refresh all caches'), you should see a request to http://localhost:8084/instanceTypes.
If the response contains your instance types, you should be good to go.
-15978379 0This command does two main things: create a mask with that torn-paper effect, apply the mask to the image. It does them, fancily, in one line, by using +clone and the parentheses. It's less confusing to do it as two commmands though:
convert thumbnail.gif \ -alpha extract \ -virtual-pixel black \ -spread 10 \ -blur 0x3 \ -threshold 50% \ -spread 1 \ -blur 0x.7 \ mask.png convert thumbnail.gif mask.png \ -alpha off \ -compose Copy_Opacity \ -composite torn_paper.png
The first command is fairly complex. But you can find decent explanations of each of the component commands in the ImageMagick docs:
Also, by splitting the command into these two pieces, you can see what the mask looks like on its own. It's basically the inverse of the paper effect. White throughout the middle of the images, fading to black around the "torn edges".
The second command is a lot more straightforward. Copy_Opacity, as described in the ImageMagick docs, is a way of making parts of an image transparent or not. Anything that's black in the mask will be made transparent in the resulting image. In effect, the second command uses the mask to "erase" the edges of the original thumbnail in a stylistically interesting way.
-18597835 0 Placing a TextView below two ImageViews and in middle - AndroidPlease share code to achieve the layout of the screen shown in the below link. The text should be in center of the two images and all these components can be dynamic.
(https://docs.google.com/file/d/0B9n2IhVep_QeNDFKaWFHVERQOVk/edit?usp=sharing)
https://www.dropbox.com/s/2j4bpwdmv0wgesg/Untitled%20Diagram.png
-30757002 0pboedker and ChrisKo answers are both good. A couple of extra warnings are needed.
A scan (or the scan time) can be shorter than your code's execution time. In most PLC's there is a "watchdog" to detect this, and warn you that it is happening. You often need to set this "watchdog" up, and set up a alarm/event handler for it.
Know how your PLC executes I/O. Some (Such as ControlLogix) are Asynchronous, I/O gets read into your controllers memory based on the RPI (request packet interval), and gets written out (same RPI) when you make a change to the I/O point with code. Others (Such as AutomationDirect's Productivity 2000 series) only write the outputs upon a COMPLETE scan of your code. I'm sure you can picture the pro's and cons of each scenario, especially if your controller is not completing your code before restarting a scan.
PLC's that allow you to have different scan rates for different pieces of code give you powerful tools for I/O and program flow management. Slow processes can be scanned slowly, allowing you more PLC time for other things.
-9814937 0Follow this guide: http://weblogs.asp.net/psheriff/archive/2009/12/01/load-resource-dictionaries-at-runtime-in-wpf.aspx
DynamicResource
s.Basically, you are looking to "skin" your application. The code that loads in your resource file can take advantage of the TimeOfDay
enumeration.
If you want it automated you can even have some static class that has a timer to automatically attempt to change the resource and set the timer on the application startup. :)
-40354505 0You can manually bootstrap angular after receive data from server.
Example on jsfiddle:
var app = angular.module("myApp", []); app.controller("myController", function($scope, servicesConfig) { console.log(servicesConfig); $scope.model = servicesConfig.host; $scope.reset = function() { $scope.model = ''; }; }); angular.element(document).ready(function() { //Simulate AJAX call to server setTimeout(function() { app.constant('servicesConfig', { host: "appdev" }); angular.bootstrap(document, ['myApp']); }, 2000); });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-cloak> <div ng-controller="myController"> <input type="text" ng-model="model" /> {{model}} <button ng-click="reset()">Reset</button> </div> </div>
Can properties such as yarn.log-aggregation-enable and yarn.log-aggregation.retain-seconds applied on a per job basis? I would not like this to be enabled at a cluster-wide scale but only for a few tasks.
-5286116 0If you like to learn by doing then learn by doing it in PDO and bind the parameters. This is the safe and correct way to do it these days.
-4193721 0If you want to implement server side sorting then it does not matter what technology you are using in the front end.
On a conceptual level you can do the following things:
EDIT: Updated with resize
event listener. Updated fiddle.
As I understand it, you want the text to be as large as possible while still fitting inside the containing <div>
, correct? My solution is to put a <span>
around the text, which conforms to the text's normal size. Then calculate the ratios between the container's dimensions and the <span>
's dimensions. Whichever is the smaller ratio (either width or height), use that ratio to enlarge the text.
HTML:
<div class="container"> <span class="text-fitter"> text here </span> </div>
JS (jQuery):
textfit(); $(window).on('resize', textfit); function textfit() { $('.text-fitter').css('font-size', 'medium'); var w1 = $('.container').width()-10; var w2 = $('.text-fitter').width(); var wRatio = Math.round(w1 / w2 * 10) / 10; var h1 = $('.container').height()-10; var h2 = $('.text-fitter').height(); var hRatio = Math.round(h1 / h2 * 10) / 10; var constraint = Math.min(wRatio, hRatio); $('.text-fitter').css('font-size', constraint + 'em'); }
Here's a fiddle. Adjust the .container
dimensions in the CSS to see it in action.
I'm only marking this as the answer to close the case, what the actual answer was to the problem we will never know. The solution: automatic updates. After much hassles with getting automatic updates to actually go through, my machine is now working well.
-4969681 0in case you want both containers to float besides each other, you can rather use a span instead of a div. That might bring the problem to an end.
-33093272 0It's related with thread not killed after use, not related with logging module, it's solved now, thanks for attention.
-23032838 0If you are looking to just "preload" the images so that you can use them later (in your app/page), then you can use the following HTML 5 code:
<link rel="prefetch" href="http://davidwalsh.name/wp-content/themes/walshbook3/images/sprite.png" />
See: Link prefetching is a browser mechanism, which utilizes browser idle time to download or prefetch documents that the user might visit in the near future. A web page provides a set of prefetching hints to the browser, and after the browser is finished loading the page, it begins silently prefetching specified documents and stores them in its cache. When the user visits one of the prefetched documents, it can be served up quickly out of the browser's cache. URL, then description, then title, keywords.. and finally body.
If for gallery, then @Santosh is correct. Or http://code.msdn.microsoft.com/Infinite-Scroll-Like-Bing-bc05262b
-32792841 0self.printfunc = weakref.ref(printfunc)()
isn't actually using weakref
s to solve your problem; the line is effectively a noop. You create a weakref
with weakref.ref(printfunc)
, but you follow it up with call parens, which converts back from weakref
to a strong ref which you store (and the weakref
object promptly disappears). Apparently it's not possible to store a weakref
to the bound method itself (because the bound method is its own object created each time it's referenced on self
, not a cached object whose lifetime is tied to self
), so you have to get a bit hacky, unbinding the method so you can take a weakref
on the object itself. Python 3.4 introduced WeakMethod
to simplify this, but if you can't use that, then you're stuck doing it by hand.
Try changing it to (on Python 2.7, and you must import inspect
):
# Must special case printfunc=None, since None is not weakref-able if printfunc is None: # Nothing provided self.printobjref = self.printfuncref = None elif inspect.ismethod(printfunc) and printfunc.im_self is not None: # Handling bound method self.printobjref = weakref.ref(printfunc.im_self) self.printfuncref = weakref.ref(printfunc.im_func) else: self.printobjref = None self.printfuncref = weakref.ref(printfunc)
and change myprint
to:
def myprint(self,text): if self.printfuncref is not None: printfunc = self.printfuncref() if printfunc is None: self.printfuncref = self.printobjref = None # Ref died, so clear it to avoid rechecking later elif self.printobjref is not None: # Bound method not known to have disappeared printobj = self.printobjref() if printobj is not None: print ("ExtenalFUNC:%s" %text) # To call it instead of just saying you have it, do printfunc(printobj, text) return self.printobjref = self.printfuncref = None # Ref died, so clear it to avoid rechecking later else: print ("ExtenalFUNC:%s" %text) # To call it instead of just saying you have it, do printfunc(text) return print ("JustPrint:%s" %text)
Yeah, it's ugly. You could factor out the ugly if you like (borrowing the implementation of WeakMethod
from Python 3.4's source code would make sense, but names would have to change; __self__
is im_self
in Py2, __func__
is im_func
), but it's unpleasant even so. It's definitely not thread safe if the weakref
s could actually go dark, since the checks and clears of the weakref
members aren't protected.
Seems that runjags suddenly (after update to version 2.0.3-2) has trouble finding JAGS binary, issuing an error:
[1] "Error in system(\"where jags\", intern = TRUE) : 'where' not found\n" attr(,"class") [1] "try-error" attr(,"condition") <simpleError in system("where jags", intern = TRUE): 'where' not found
I fixed this by putting this line to my Rprofile
:
.runjags.options <- list(jagspath = "c:/Program Files/JAGS/JAGS-4.2.0/i386/bin/jags-terminal.exe")
This pretty much fixes the problem (although it is not ideal - previous versions of runjags could find the binary automatically).
However, when the Rgui (in Windows XP) is launched by opening an .Rdata file, which is associated to it, it stops working:
> .runjags.options # it was set in the Rprofile $jagspath [1] "c:/Program Files/JAGS/JAGS-4.2.0/i386/bin/jags-terminal.exe" > require(runjags) Loading required package: runjags Warning message: package ‘runjags’ was built under R version 3.1.3 > runjags.getOption("jagspath") [1] "Error in system(\"where jags\", intern = TRUE) : 'where' not found\n" attr(,"class") [1] "try-error" attr(,"condition") <simpleError in system("where jags", intern = TRUE): 'where' not found
Is this a bug? How to fix this?
I am currently calling runjags.options(jagspath = "c:/Program Files/JAGS/JAGS-4.2.0/i386/bin/jags-terminal.exe")
in my source after require(runjags)
, but I would like to avoid this as much as possible!
I am new to android. I want to know how to set the parameters or attributes to layout x and layout y width and height from the program for any layouts like absolute.
-9671918 0 Disable submit if inputs empty jqueryDisclaimer: I know there are quite a few questions out there with this topic and it has been highly addressed, though I need assistance in my particular case.
I am trying to check if the input values are empty on keyup then disable the submit button.
My HTML snippet:
<div class='form'> <form> <div class='field'> <label for="username">Username</label> <input id="username" type="text" /> </div> <div class='field'> <label for="password">Password</label> <input id="password" type="password" /> </div> <div class='actions'> <input type="submit" value="Login" /> </div> </form> </div>
I have used the example answer from here with some modifications:
(function() { $('.field input').keyup(function() { var empty = false; $('.field input').each(function() { if ($(this).val() == '') { empty = true; } }); if (empty) { $('.actions input').attr('disabled', true); } else { $('.actions input').attr('disabled', false); } }); })()
Any help would be greatly appreciated!
-38587336 0mysqli_real_escape_string
is good, but not always safe as prepared statement.
mysql_real_escape_string()
prone to the same kind of issues affecting addslashes()
.
So use of prepared statement is much better.
-26567465 0 GeckoInputElement.Click returns System.NullReferenceExceptionI am making use of the GeckoWebbrowser control in a C# Windows forms app environment.
I am wanting to call the click event on a button on the browser page, from a code event behind.
When I try an access a specific button I can find it by making use of the GetElementById command, however after assigning this information to the GeckoInputElement to call the click event, there is a null reference exception visible with this.
My code call to get the element looks like this:
GeckoInputElement betbt = new GeckoInputElement(wBrowser.Document.GetElementById("bet-bt").DomObject);
If I assign it like this I can access the element but still cannot click it with the GeckoElement object:
GeckoElement g1 = (GeckoElement)wBrowser.Document.GetElementById("bet-bt");
The HTML for the button looks as follows:
<button data-action="bet" id="bet-bt" class="action">Bet</button>
-36754439 0 Use background-size: cover;
or background-size: contain;
as per your necessity. That should fix it.
The PowerPivot tab is a COM Add-In. To view the progID of it and other COM Add-Ins use:
Sub ListCOMAddins() Dim lngRow As Long, objCOMAddin As COMAddIn lngRow = 1 With ActiveSheet For Each objCOMAddin In Application.COMAddIns .Cells(lngRow, "A").Value = objCOMAddin.Description .Cells(lngRow, "B").Value = objCOMAddin.Connect .Cells(lngRow, "C").Value = objCOMAddin.progID lngRow = lngRow + 1 Next objCOMAddin End With End Sub`
In my case the progID of the PowerPivot tab is "Microsoft.AnalysisServices.Modeler.FieldList". So to close the tab use:
Private Sub Workbook_Open() Application.COMAddIns("Microsoft.AnalysisServices.Modeler.FieldList").Connect = False End Sub
-33940429 0 In order to define an ArrayList
with CheckBoxes
please refer to following example:
List<JCheckBox> chkBoxes = new ArrayList<JCheckBox>();
Add your JCheckBox
elements to the ArrayList
using standard approach, for example:
JCheckBox chkBox1 = new JCheckBox(); chkBoxes.add(chkBox1);
Interatve over the list and carry out check if selected using JCheckBox
method #.isSelected()
as follows:
for(JCheckBox chkBox : chkBoxes){ chkBox.isSelected(); // do something with this! }
-13315966 0 There's another angle to this one. If you have SQL Server 2008 already installed, you need to select the upgrade option. If you don't, then in your installation of SQL Server 2008 R2 your "management tools - complete" will be grayed out when you get to the install items choice screen. Hover over it and it will tell you as much. Hope this helps someone.
-24004362 0I think that you can change the new
resource to newVisit
like this:
App.Router.map () -> @resource 'visits', -> @resource 'visit', { path: '/:visit_id' } @resource 'newVisit', -> @route 'welcome' @route 'directory' @route 'thanks'
Now you will have a NewVisitRoute
where you can create a new Visit
model to use in each of the child routes.
And you will be able to make a transition to this routes with the route names: newVisit.welcome
, newVisit.directory
and newVisit.thanks
. You can use this route names in a link-to
helper link this:
{{link-to "Welcome", "newVisit.welcome"}}
-15040416 0 I use LaTeX to create the DOM representation.
Here is a minimal working example:
\documentclass{scrreprt} \usepackage{tikz-qtree} \begin{document} \Tree[.table [.thead [.tr [.th [.\textit{Vorname} ] ] [.th [.\textit{Nachname} ] ] ] ] [.tbody [.tr [.td [.\textit{Donald} ] ] [.td [.\textit{Duck} ] ] ] ] ] \end{document}
Which gives:
Q: How can I have DNS name resolving running while other protocols seem to be down?
A: Your local DNS resolver (bind
is another possibility besides ncsd
) might be caching the first response. dig
will tell you where you are getting the response from:
[mpenning@Bucksnort ~]$ dig cisco.com ; <<>> DiG 9.6-ESV-R4 <<>> +all cisco.com ;; global options: +cmd ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 22106 ;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 2, ADDITIONAL: 0 ;; QUESTION SECTION: ;cisco.com. IN A ;; ANSWER SECTION: cisco.com. 86367 IN A 198.133.219.25 ;; AUTHORITY SECTION: cisco.com. 86367 IN NS ns2.cisco.com. cisco.com. 86367 IN NS ns1.cisco.com. ;; Query time: 1 msec <----------------------- 1msec is usually cached ;; SERVER: 127.0.0.1#53(127.0.0.1) <--------------- Answered by localhost ;; WHEN: Wed Dec 7 04:41:21 2011 ;; MSG SIZE rcvd: 79 [mpenning@Bucksnort ~]$
If you are getting a very quick (low milliseconds) answer from 127.0.0.1
, then it's very likely that you're getting a locally cached answer from a prior query of the same DNS name (and it's quite common for people to use caching DNS resolvers on a ppp
connection to reduce connection time, as well as achieving a small load reduction on the ppp link).
If you suspect a cached answer, do a dig
on some other DNS name to see whether it can resolve too.
ppp
connection going down.If you find yourself in either of the last situations I described, you need to do some IP and ppp-level debugs before this can be isolated further. As someone mentioned, tcpdump
is quite valuable at this point, but it sounds like you don't have it available.
I assume you are not making a TCP connection to the same IP address of your DNS server. There are many possibilities at this point... If you can still resolve random DNS names, but TCP connections are failing, it is possible that the problem you are seeing is on the other side of the ppp connection, that the kernel routing cache (which holds a little TCP state information like MSS
) is getting messed up, you have too much packet loss for tcp
, or any number of things.
Let's assume your topology is like this:
10.1.1.2/30 10.1.1.1/30 [ppp0] [pppX] uCLinux----------------------AccessServer---->[To the reset of the network]
When you initiate your ppp connection, take note of your IP address and the address of your default gateway:
ip link show ppp0 # display the link status of your ppp0 intf (is it up?) ip addr show ppp0 # display the IP address of your ppp0 interface ip route show # display your routing table route -Cevn # display the kernel's routing cache
Similar results can be found if you don't have the iproute2
package as part of your distro (iproute2
provides the ip
utility):
ifconfig ppp0 # display link status and addresses on ppp0 netstat -rn # display routing table route -Cevn # display kernel routing table
For those with the iproute2
utilities (which is almost everybody these days), ifconfig
has been deprecated and replaced by the ip
commands; however, if you have an older 2.2 or 2.4-based system you may still need to use ifconfig
.
Troubleshooting steps:
When you start having the problem, first check whether you can ping the address of pppX
on your access server.
pppX
on the other side, then it is highly unlikely your DNS is getting resolved by anything other than a cached response on your uCLinux machine.pppX
, then try to ping
the ip address of your TCP peer and the IP address of the DNS (if it is not on localhost
). Unless there is a firewall involved, you must be able to ping
it successfully for any of this to work.If you can ping
the ip address of pppX
but you cannot ping
your TCP peer's ip address, check your routing table to see whether your default route is still pointing out ppp0
If your default route points through ppp0
, check whether you can still ping the ip address of the default route.
If you can ping
your default route and you can ping
the remote host that you're trying to connect to, check the kernel's routing cache for the IP address of the remote TCP host.... look for anything odd or suspicious
If you can ping
the remote TCP host (and you need to do about 200 pings
to be sure... tcp
is sensitive to significant packet loss & GPRS is notoriously lossy), try making a successful telnet <remote_host> <remote_port>
. If both are successful, then it's time to start looking inside your software for clues.
If you still can't untangle what is happening, please include the output of the aforementioned commands when you come back... as well as how you're starting the ppp
connection.
I want to ad a title "Instant Independent" to the center "featured" section of my wordpress blog. Directly above where the "fee increase coming soon for lake mohave" story. http://www2.az-independent.com/
How do I do this?
-27392016 0 Incorrectly parsed ReturnJSON methodThis method
var fListItems = db.FListItems.Include(f => f.FList) .Include(f => f.Item) .GroupBy(g => new { g.Item.Name, g.FList.Title }) .Select(lg => new FListItemsViewModel { Title = lg.Key.Title, ItemStat = new ItemStat { Name = lg.Key.Name, NameCount = lg.Count(), NameSum = lg.Sum(w => w.Score), NameAverage = lg.Average(w => w.Score) } });
returns this JSON
[ { Title: "Animals", ItemStat: { Name: "Cat", NameCount: 2, NameSum: 8, NameAverage: 4 } }, { Title: "Animals", ItemStat: { Name: "Dog", NameCount: 1, NameSum: 5, NameAverage: 5 } } ]
but I'd like it to return this JSON:
[ { Title: "Animals", ItemStats: [ { Name: "Cat", NameCount: 2, NameSum: 8, NameAverage: 4 }, { Name: "Dog", NameCount: 1, NameSum: 5, NameAverage: 5 } ] } ]
Can anybody suggest how to do this? Here's the viewmodel:
public class FListItemsViewModel { public string Title { get; set; } public ItemStat ItemStat { get; set; } } public class ItemStat { public string Name { get; set; } public int NameCount { get; set; } public int NameSum { get; set; } public double NameAverage { get; set; } }
Rather than GroupBy
Title
and Name
in the same clause, could it be better to re-write my query with two seperate GroupBy
s?
Progress based on Rahul's answer:
[ { Title: "Animals", ItemStat: [ { Name: "Cat", NameCount: 2, NameSum: 8, NameAverage: 4 }, { Name: "Cat", NameCount: 2, NameSum: 8, NameAverage: 4 } ] }, { Title: "Animals", ItemStat: [ { Name: "Dog", NameCount: 1, NameSum: 5, NameAverage: 5 } ] } ]
-7172537 0 If you accept to recycle the random numbers, why do you want to wait for the exhaustion of the combinations before recycling?
I would just generate random numbers, without caring if they've been used already.
If you really really want to keep it like you asked, here's how you could do it:
You could improve it by moving the used numbers from one table to another, and use the second table instead of the first one when the first table is empty.
You could also do that in memory, if you have enough of it.
-5613804 0Assuming you've made sure your application doesn't persist anything, all you have left to do is add UIApplicationExitsOnSuspend
and set it to true in your application's Info.plist
. The moment the user leaves your application, its process will terminate. When the user starts your application again it won't remember anything; it'll just start from the beginning. This includes displaying the launch image.
What I am trying to achieve is to find smallest number in array and it initial position. Here's an example what it should do:
temp = new Array(); temp[0] = 43; temp[1] = 3; temp[2] = 23;
So in the end I should know number 3 and position 1. I also had a look here: Obtain smallest value from array in Javascript? , but this way does not gives me a number position in array. Any tips, or code snippets are appreciated. Thanks.
-26963227 0Your recursive predicate isConnected/2 misses the base case:
isConnected(X,Y) :- graph1(X,Y).
(assuming we are checking graph1, of course).
Anyway, you cannot use isConnected/2, since Prolog will loop on cyclic graphs.
-27267854 0 Rounded Corner imagesI've been trying to do perfectly shaped circular images with non-square images. I tried to make it with
[self.photoView.layer setCornerRadius:50.0f]; [self.photoView.layer setMasksToBounds:YES];
It becomes something like this:
I want to make it full perfect circular.
PhotoView's content mode is setted to Aspect Fill, It's height and width fixed to 80x80 with autolayout. I could not figure it out.
I made circular images with cropping and scaling them, but also want to add a border to it, in this way i need to recreate new uiimage to draw borders in it. It's expensive thing. I want to use photoView's layer to do this.
Any help is appreciated.
-11979894 0You are accessing getResources()
without a reference to a Context
. Because this is a static method, you can only access other static methods within that class without providing a reference.
Instead, you must pass the Context
as an argument:
// the 34th button Button tf = (Button) findViewById(R.id.tFour); tf.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Apply.applyBitmap(v.getContext(), R.drawable.tFour); // Pass your context to the static method } });
Then, you must reference it for getResources()
:
public static void applyBitmap(Context context, int resourceID) { BitmapFactory.Options opt = new BitmapFactory.Options(); opt.inScaled = true; opt.inPurgeable = true; opt.inInputShareable = true; Bitmap brightBitmap = BitmapFactory.decodeResource(context.getResources(), resourceID, opt); // Use the passed context to access resources brightBitmap = Bitmap.createScaledBitmap(brightBitmap, 100, 100, false); MyBitmap = brightBitmap; }
-9489652 0 the warnings are caused by the maven tar archiver. By default, it warns for tar entries with path length > 100 chars. Considering this is an ancient tar format limitation, I changed the default to "gnu" for tycho 0.17.0-SNAPSHOT so you should no longer get these warnings:
https://github.com/eclipse/tycho/commit/5db5cc2b76bdba8526cfc4acb66b3e4674f23f03
-38432502 0 PayPal iOS Network Connection Was LostI actually posted this question on PayPal Repository GitHub, but no one was answering me.
The PayPal SDK works so fine when using a PayPal Account, but when I try to use Pay with card, I can't connect to the PayPal Server, and there is no debug logs, only this:
2016-07-18 10:00:03.447 UPlant[23489:265771] NSScanner: nil string argument 2016-07-18 10:00:04.036 UPlant[23489:265771] Can't find keyplane that supports type 4 for keyboard iPhone-Portrait-NumberPad; using 563160167_Portrait_iPhone-Simple-Pad_Default 2016-07-18 10:00:04.077 UPlant[23489:265771] NSScanner: nil string argument 2016-07-18 10:00:04.077 UPlant[23489:265771] NSScanner: nil string argument 2016-07-18 10:00:04.077 UPlant[23489:265771] NSScanner: nil string argument 2016-07-18 10:00:08.415 UPlant[23489:265771] Can't find keyplane that supports type 4 for keyboard iPhone-Portrait-NumberPad; using 563160167_Portrait_iPhone-Simple-Pad_Default 2016-07-18 10:00:10.070 UPlant[23489:265771] Can't find keyplane that supports type 4 for keyboard iPhone-Portrait-NumberPad; using 563160167_Portrait_iPhone-Simple-Pad_Default
Additional Information
Mode (Mock/Sandbox/Live): Sandbox
PayPal iOS SDK Version: sandbox, PayPal iOS SDK 2.14.2
iOS Version and Device (iOS 8.x, iOS 9.3 on an iPhone 6s, etc.): iOS 9.3 iPhone 5 Simulator
PayPal-Debug-ID(s) (from any logs): No debug logs
After attempting the PayPal to do the transaction with Card, it pops up an alert saying
The Network Connection Was Lost.
Any idea on this why is this happening and how to solve it?
-31597735 0After playing around with it a bit I came to this conclusion. I changed the HTML a bit because I wanted to use the Bootstrap alert boxes.
public static string MyValidationSummary(this HtmlHelper helper, string validationMessage = "") { string retVal = ""; string errorList = ""; foreach (var key in helper.ViewData.ModelState.Keys) { retVal = ""; foreach (var err in helper.ViewData.ModelState[key].Errors) { retVal += "<div class='alert alert-danger'>"; retVal += "<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>"; retVal += "<i class='icon-remove-sign'></i>"; retVal += helper.Encode(err.ErrorMessage); retVal += "</div>"; errorList += retVal; } } return errorList.ToString(); }
-4488211 0 Observe that:
Here's my C# implementation, though it should be trivial to port to Java:
static long SumSubtring(String s) { long sum = 0, mult = 1; for (int i = s.Length; i > 0; i--, mult = mult * 10 + 1) sum += (s[i - 1] - '0') * mult * i; return sum; }
Note that it is effectively O(n).
-32227126 0 CentOs Magento files created as directories?I noticed a few days ago that a few files that belong to a certain Magento extension were in fact created as directories and not in fact the .png .css and .js files that they were supposed to be. When updating the extension there are errors as the files are unable to overwrite the existing directories. I mainly noticed this due to the icons being missing from the Magento admin panel. Although baffling, no big deal, I deleted the directories (x4) and copied the correct files from the original distribution. Problem solved.
I used find . -type d "." and also the 'empty' option to identify directories which should be files. This fixes the symptom but not the cause. There were around 10 files, mostly images but some .js and .css affected.
I've just run an update of M2e via Magento connect, 'successfully', but having noticed some missing icons/graphics in admin I checked the code and have identified 17 empty directories that should have been image files (.png and .gif).
I guess my questions are how and why is this happening? How can I stop it happening again?
I have a dedicated CentOS server running Apache. Installs are done via Filezilla FTP upload or Magento Connect, it seems most likely that it's Connect causing the problem, both extensions have been updated by Connect at least once in their lifetime.
Hoping someone can enlighten me, though not a huge problem in itself, it is a concern that critical files (rather than images) may be prone to the same problems...Anyone seen this before??
Cheers RobH
-3294365 0The destination anchor for a link in an HTML page may be any element with an id
attribute. See Links on the W3C site. Here's a quote from the relevant section:
Destination anchors in HTML documents may be specified either by the A element (naming it with the name attribute), or by any other element (naming with the id attribute).
Markdown treats HTML as HTML (see Inline HTML), so you can create your fragment identifiers from any element you like. If, for example, you want to link to a paragraph, just wrap the paragraph in a paragraph tag, and include an id:
<p id="mylink">Lorem ipsum dolor sit amet...</p>
Then use your standard Markdown [My link](#mylink)
to create a link to fragment anchor. This will help to keep your HTML clean, as there's no need for extra markup.
Which are some of the famous research papers and/or books which concern Autoencoders and the various different training algorithms for Autoencoders? I'm talking about research papers and/or books which lay the foundation for the different training algorithms used to train autoencoders.
-34564942 0Am assuming you know javascript array and few method
Use the window.location.href
var url = 'site.com/seach?a=val0&b=val1'
split the '?'
var someArray = url.split('?');
The someArray looks like this ['site.com/seach', 'a=1000&b=c'] index 0 is the window.location and index 1 is queryString
var queryString = someArray[1];
Go futher a split '&' so u get a key=value
var keyValue = queryString.split('&');
keyVal looks like this ['a=val0', 'b=val1'];
Now lets get keys and values.
var keyArray=[], valArray=[];
Loop through the keyValue array and split '=' the update keyArray and valArray
for(var i = 0; i < keyValue.length; i++){
key = keyValue[i].split('=')[0];
val = keyValue[i].split('=')[1];
keyArray.push(key);
valArray.push(val);
}
Finally we have
keyArray = ['a', 'b'];
valArray = ['val0', 'val1'];
Our full codes looks like this.
var url = 'site.com/seach?a=val0&b=val1';
var someArray = url.split('?');
var queryString = someArray[1];
var keyValue = queryString.split('&');
var keyArray=[], valArray=[];
for(var i = 0; i < keyValue.length; i++){
key = keyValue[i].split('=')[0];
val = keyValue[i].split('=')[1];
keyArray.push(key);
valArray.push(val);
}
DONE!
-18217302 0You might need to change
-lopencv_core244 \ -lopencv_highgui244 \ -lopencv_imgproc244
to
-lopencv_core244d \ -lopencv_highgui244d \ -lopencv_imgproc244d
Do not set any IBOutlet
of your UIViewController
before it is displayed.
The IBOutlet
is probably not initialised yet. I would suggest making a string property, setting it when you initialise your UIViewController
and setting that text to your UILabel
in the viewDidLoad
or viewWillAppear
method.
Hope this helped!
-9449562 0 How to remove Scrollbar in ChromeDriver, how to change http-agent?I use IWebDriver driver = new ChromeDriver(options)
in C#
When I take .GetScreenshot();
, often see scrollbar, is there a way to remove it?
2nd question, how to mock/change http_agent
in ChromeDriver?
I will take it from the silence that there is no such feature. So here is the macro for it:
Sub StopDebugAndKillProcesses() Dim dbg As EnvDTE80.Debugger2 = DTE.Debugger dbg.Stop() Dim shell_string As String shell_string = "taskkill /F /IM TheProcessToKill.exe" Shell(shell_string) End Sub
Assign it to a button, put it next to the original "Stop" button and your done.
-24771191 0The local file system is declared to be cross-origin and will taint the canvas. This is a good declaration given that your most sensitive information is probably on a local file system.
Here are some ways to be compliant with CORS security:
Install a web server on your local computer and serve both your images and .html/.css/.js files on that server. PHP & IIS both have excellent local editions.
Put your images on a CORS compliant hosting service (imagur.com is one among others)
For small projects, it sometimes works to put both the image and webpage files all on the desktop.
It's equivalent to
least = Math.min(least, k);
or
if (!(least < k)) { least = k }
See also: the Java documentation on the ternary operator (scroll to the "The Conditional Operators" section).
-30244323 0 PHP - Cast type from variableI was asking myself if it's possible to cast a string to become another type defined before
e.g.
$type = "int"; $foo = "5"; $bar = ($type) $foo;
and where $bar === 5
-319672 0 GetWindowLong vs GetWindowLongPtr in C#I was using GetWindowLong like this:
[DllImport("user32.dll")] private static extern IntPtr GetWindowLong(IntPtr hWnd, int nIndex);
But according to the MSDN docs I am supposed to be using GetWindowLongPtr to be 64bit compatible. http://msdn.microsoft.com/en-us/library/ms633584(VS.85).aspx
The MSDN docs for GetWindowLongPtr say that I should define it like this (in C++):
LONG_PTR GetWindowLongPtr(HWND hWnd, int nIndex);
I used to be using IntPtr as the return type, but what the heck would I use for an equivalent for LONG_PTR? I have also seen GetWindowLong defined as this in C#:
[DllImport("user32.dll")] private static extern long GetWindowLong(IntPtr hWnd, int nIndex);
What is right, and how can I ensure proper 64bit compatibility?
-17641209 0Your app crashing because the variable maxInt
in plus1 is undefined. maxInt
's scope is local to onCreate
. Also final
variables are like constant
variables in C. They can only get a value when you initialize them, meaning you can't change their value.
Your maxInt should not be final and should be a global variable:
public class ScoreActivity extends Activity { int maxInt; protected void onCreate(Bundle savedInstanceState) { ... maxInt = Integer.parseInt(max); ... } public void plus1 (View V) { maxInt ++; } ... }
-1641232 0 Python has limited support for private identifiers, through a feature that automatically prepends the class name to any identifiers starting with two underscores. This is transparent to the programmer, for the most part, but the net effect is that any variables named this way can be used as private variables.
See here for more on that.
In general, Python's implementation of object orientation is a bit primitive compared to other languages. But I enjoy this, actually. It's a very conceptually simple implementation and fits well with the dynamic style of the language.
-4759726 0 .NET - Multiple libraries with the same namespace - referencingToday I am faced with a curious challenge...
This challenge involves two .NET libraries that I need to reference from my application. Both of which I have no control over and have the same namespace within them.
So...
I have foo.dll
that contains a Widget
class that is located on the Blue.Red.Orange
namespace.
I have bar.dll
that also contains a Widget
class that is also located on the Blue.Red.Orange
namespace.
Finally I have my application that needs to reference both foo.dll
and bar.dll
. This is needed as within my application I need to use the Widget
class from foo
and also the Widget
class from bar
So, the question is how can I manage these references so that I can be certain I am using the correct Widget
class?
As mentioned, I have no control over the foo
or bar
libraries, they are what they are and cannot be changed. I do however have full control over my application.
Add a hidden field to your aspx page.
<asp:HiddenField ID="hfrecordID" runat="server" />
And assign the recodId to it in the ItemDataBound event and use it in the aspx page.
<telerik:RadCodeBlock ID="RadCodeBlock1" runat="server"> <script type="text/javascript"> function ViewCheck(filename) { var targetfile = "Allegati/" + <%= hfrecordID.value %> + filename; var openWnd = radopen(targetfile, "RadWindowDetails"); } </script> protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e) { if (e.Item is GridEditableItem && e.Item.IsInEditMode) { GridEditableItem editedItem = e.Item as GridEditableItem; hfrecordID= editedItem.GetDataKeyValue("TransazioneID").ToString(); } }
-18151503 0 It looks from your code like you're trying to run some php code (tradeformresult.php). Loading it this way isn't going to work as expected-that require_once will be run as the page is being built in PHP, not in the browser.
For sending a form without refreshing the page, you should look into AJAX (http://en.wikipedia.org/wiki/Ajax_(programming))
JQuery has a good AJAX method. Here is a simple example of how to use it:
$.ajax({url:"http://www.someserver.com/api/path", data:{val1:"value",val2:"value"}) .success(function(returnData) { console.log(returnData); });
The above will call the given URL with the given data as parameters, then, if successful, will return whatever data the server gave back into the returnData
variable.
If you're using AJAX, you don't really even have to use a <form>
tag, since you'll be building the query string manually. You can have the function that makes the AJAX call be triggered from the onClick
event of a button.
There is a wordpress plugin CC Circle Progress Bar which will work for you. Here is the link: https://wordpress.org/plugins/cc-circle-progress-bar/
-32958703 0You need to create a resources folder in your eclipse project. and then add that folder to your project sources. application.properties file (which contains IP/Port of RTSP server) should be located there.
-20176778 0 Is it good to make function in function using 'return'?While I was investigating functions, I realised that I can create embedded functions. Firstly, I thought it may be useful for structuring code. But now I suppose it isn't good style of coding. Am I right? Here is an example.
function show () { return function a() { alert('a'); return function b() { alert('b'); } } }
And I can call alert('b')
using this string: show()()
;
In what situations is better to use this method and in what not?
-16930087 0The error is in this line of code.
if (sqlite3_prepare_v2(contactDB, query_stmt, 1, &statement, NULL) == SQLITE_OK) {
The 1
is wrong. From the SQLite docs:
int sqlite3_prepare_v2( sqlite3 *db, /* Database handle */ const char *zSql, /* SQL statement, UTF-8 encoded */ int nByte, /* Maximum length of zSql in bytes. */ sqlite3_stmt **ppStmt, /* OUT: Statement handle */ const char **pzTail /* OUT: Pointer to unused portion of zSql */ ); If the nByte argument is less than zero, then zSql is read up to the first zero terminator. If nByte is non-negative, then it is the maximum number of bytes read from zSql.
So you are forcing SQLite to only read the first byte from the statement. Of course this is invalid.
-22399218 0Maybe you could use .promise()
for this.
You can add a promise to the upload function. This way you could run functions like upload.done(function(e) { /* do stuff */ });
The $.ajax()
in jQuery has its build-in promise. You can check if an ajax call succeeded with xhr.done(function(e) { /* do stuff */ });
Hi guys I'm a Jquery noob ,I'm using jqueryUI slider but the slider handle always stucks on div border (left side) and after clicking on the slider bar it moves forward but doesn't reaches max limit and stucks in between.
Check the JsFiddle the snapshot is from the browser (where you can see the slider handle) ,I have put all the code on fiddle ,but can't make jsFiddle work.
Slider:
1. Slider handle sticks to the div border.
2. Slider handle doesnt move towards the max value and stucks at some value in between.
You can of course use a regexp, but there are libraries which will do the job quicker and easier. Try using a HTML dom parser, or phquery which is an implementation of jquery lib in php. It's also available for Composer. So if you're familiar with jquery syntax, you can find it very neat.
Get the html you need using this: $html = pq('.modal.ww')->html();
-18818456 0 center site content on all devicesThis is the site I am referring to: http://heattreatforum.flyten.net/
It was built as a child-site to the twenty-twelve theme.
I can't seem to get the content to center on every screen, and I am seeing a strange wide margin on the right that I just can't seem to locate in my css.
Any help would be much appreciated - thanks for looking!
-23659948 0 WCF binding over HTTPS an security at message levelI have a WCF Service over HTTP with the following binding:
<basicHttpBinding> <binding name="RegistreReferenciaBinding"> <security mode="Message"> <message clientCredentialType="Certificate" /> </security> </binding> </basicHttpBinding>
A third party service is connecting to this Service and now this third party is requiring an HTTPS connection.
The problem is that I need to maintain the security at message level in order to be compatible with the third party Service.
To resume the situation what I need to do is configure the service to be HTTPS compatible, without client certificate while maintaining the security at message level.
What is the configuration needed to get this Service working with the same configuration but over HTTPS?
UPDATE:
I tried to use the following configuration:
<basicHttpBinding> <binding name="RegistreReferenciaBinding"> <security mode="Transport" /> </binding> </basicHttpBinding>
But with this configuration the third party Service could not connect because there was no security at message level.
From what I viewed in captured messages with Wireshark, the third party Service is using SOAP 1
The error message with this configuration was:
<?xml version="1.0"?> <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"> <s:Body> <s:Fault> <faultcode>s:MustUnderstand</faultcode> <faultstring xml:lang="es-ES">El destinatario de este mensaje no entendió el encabezado 'Security' del espacio de nombres 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd', por lo que el mensaje no se procesó. Este error suele indicar que el remitente del mensaje habilitó un protocolo de comunicación que el destinatario no puede procesar. Asegúrese de que la configuración del enlace del cliente es coherente con el enlace del servicio. </faultstring> </s:Fault> </s:Body> </s:Envelope>
UPDATE 2
I also tried with the following configuration:
<basicHttpBinding> <binding name="RegistreReferenciaBinding"> <security mode="TransportWithMessageCredentials"> <message clientCredentialType="Certificate" /> </security> </binding> </basicHttpBinding>
And it failed again.
-13617138 0 php validation is incorrect for drop down menuI have a code below where it displays students details in a drop down menu, and then it does a php validation to see if a student is selected from the drop down menu or not:
$sql = "SELECT StudentUsername, StudentForename, StudentSurname FROM Student ORDER BY StudentUsername"; $sqlstmt = $mysqli->prepare($sql); $sqlstmt->execute(); $sqlstmt->bind_result($dbStudentUsername, $dbStudentForename, $dbStudentSurname); $students = array(); // easier if you don't use generic names for data $studentHTML = ""; $studentHTML .= '<select name="students" id="studentsDrop">'.PHP_EOL; $studentHTML .= '<option value="">Please Select</option>'.PHP_EOL; $outputstudent = ""; while($sqlstmt->fetch()) { $student = $dbStudentUsername; $firstname = $dbStudentForename; $surname = $dbStudentSurname; $studentHTML .= "<option value='" . $student . "'>" . $student . " - " . $firstname . " " . $surname . "</option>" . PHP_EOL; } $studentHTML .= '</select>'; $errormsg = (isset($errormsg)) ? $errormsg : ''; if(isset($_POST['resetpass'])) { //get the form data $studentdrop = (isset($_POST['students'])) ? $_POST['students'] : ''; if($studentdrop = "") { $errormsg = "Student is Selected"; } else{ $errormsg = "You must Select a Student"; } }
The problem I have though is that even though I have selected a student from the drop down menu, it still displays a message stating that "You Must select a Student".
What is suppose to happen is that if the user has not selected a student or in other words when they have submitted the form and the drop down menu is still on the "Please Select" option, then it displays the message stating that user must select a student, else if the user does select a student from the drop down menu then display the message that a student has been selected.
-3207102 0Make sure you have the exact same service pack levels on the test and production servers. Also make sure you have the same version of all the assemblies of the third party library.
-39528057 0It is usually a bad idea to use a python
for
loop to iterate over a large pandas.DataFrame
or a numpy.ndarray
. You should rather use the available build in functions on them as they are optimized and in many cases actually not written in python but in a compiled language. In your case you should use the methods pandas.DataFrame.max and pandas.DataFrame.min that both give you an option skipna
to skip nan
values in your DataFrame
without the need to actually drop them manually. Furthermore, you can choose a axis
to minimize along. So you can specifiy axis=1
to get the minimum along columns.
This will add up to something similar as what @EdChum just mentioned in the comments:
data.max(axis=1, skipna=True) - data.min(axis=1, skipna=True)
-31202407 0 Even though not specifically mentioned in the API description, the Google GSA Search Protocol Reference is pretty explicit about this limitation:
The maximum number of results available for a query is 1,000, i.e., the value of the start parameter added to the value of the num parameter cannot exceed 1,000.
However, if all you need is more than 1,000 records (as you indicated) you can structure your query to return a well-defined non-overlapping subset of potential results, then piece together the overall result.
A simple example would segment results by date. For the custom query you posted, appending something like &sort=date:r:20100101:20101231
would return 1,000 results from the year 2010. If you repeat this for 2011, you would have a total of 2,000 results.
This might be something you can try: http://www.krautcomputing.com/blog/2012/03/27/how-to-compile-custom-sass-stylesheets-dynamically-during-runtime/.
I've used this in a Rails 3.2x project and it works fine, but I'm having difficulties getting it working in a different (somewhat modified Rails 4 project).
It's older article about compiling css on the fly using the Sprockets::StaticCompiler class.
-7704031 0 jquery sliding menu opening/closing animations issueI'm testing this on local : http://jsfiddle.net/fYkMk/1/ This is a booking form that opens up on mouse over (booking-mask) and closes when mouse leaves it. It has 4 fields :
the last three fields are sliding menus that open up with a click on the relative icon.
These sliding animations work until The user decide to "mouseover" then "mouseleave" and "mouseover" again over the booking-mask div before the oprning/closing animations are finished yet.
So it happens the lists are broken and I can only see a piece of them.[see image below]
Hope you can help me out with this. Thanks
Luca
-9416950 0I would first fetch the title tag and then process the title further. The other answers contain perfectly valid solutions for this task.
Please use the non-greedy version of .*
: .*?
, otherwise you will run into funny things like:
<html> <head> <title>a</title> </head> <body> <title>test</title> <!-- not allowed in HTML, but since when does the web pages online actually care about that? --> </body> </html>
You will now match everything between <title>a</title>...
up to <title>test</title>
, including everything in between.
I have a web service with a WS-security. I can have access to this web service only with my machine IP address and only if I make the right WS configuration.
So when testing it in Soap-ui, I get responses! and when testing connection in browser of my emulator, I get the wsdl page!
But when implemented in my application, I can not call the web service! I'm making something really wrong and didn't get it!
Is the URL I'm using for calling my web service right? Have I to configure the DNS server in the emulator? What have I to do ?
Here is my SOAP request:
POST http://172.xxx.xxx.xxx:8080/wbb HTTP/1.1 Accept-Encoding: gzip,deflate Content-Type: text/xml;charset=UTF-8 SOAPAction: "" Content-Length: 1146 Host: 172.xxx.xxx.xxx:8080 Connection: Keep-Alive User-Agent: Apache-HttpClient/4.1.1 (java 1.5) <soapenv:Envelope xmlns:ser="http://www.''''.com/wbb/service" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> <soapenv:Header><wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"> <wsse:UsernameToken wsu:Id="UsernameToken-11"> <wsse:Username>whatever2</wsse:Username> <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">whatever3</wsse:Password> <wsse:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">whatever4</wsse:Nonce> <wsu:Created>whatever5</wsu:Created> </wsse:UsernameToken></wsse:Security></soapenv:Header> <soapenv:Body> <ser:RechargeRequest> <ser:value1>?</ser:value1> <ser:value2>?</ser:value2> <!--Optional:--> <ser:value3>?</ser:value3> </ser:RechargeRequest>
and my android code:
protected String doInBackground(String... params) { private static final String SOAP_ACTION = ""; private static final String NAMESPACE"http://www.'''''.com/wbb/ws"; private static final String METHOD_NAME="Recharge"; private static final String URL = "http://172.xxx.xxx.xxx:8080/wbb/wbb.wsdl"; SoapPrimitive response = null; String xml=""; SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); PropertyInfo p1 =new PropertyInfo(); p1.name = "value1"; p1.setValue(params[0]); request.addProperty(p1); PropertyInfo p2 =new PropertyInfo(); p2.name = "value2"; p2.setValue(params[1]); request.addProperty(p2); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER12); // create header Element[] header = new Element[1]; header[0] = new Element().createElement("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd","Security"); Element usernametoken = new Element().createElement("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "UsernameToken"); usernametoken.setAttribute(null, "Id", "UsernameToken-1"); header[0].addChild(Node.ELEMENT,usernametoken); Element username = new Element().createElement(null, "n0:Username"); username.addChild(Node.IGNORABLE_WHITESPACE,"whatever2"); usernametoken.addChild(Node.ELEMENT,username); Element pass = new Element().createElement(null,"n0:Password"); pass.setAttribute(null, "Type", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText"); pass.addChild(Node.TEXT, "whatever3"); usernametoken.addChild(Node.ELEMENT, pass); Element nonce = new Element().createElement(null, "n0:Nonce"); nonce.setAttribute(null, "EncodingType","http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary"); nonce.addChild(Node.TEXT, "whatever3"); usernametoken.addChild(Node.ELEMENT, nonce); Element created = new Element().createElement(null, "n0:Created"); created.addChild(Node.TEXT, "whatever4"); usernametoken.addChild(Node.ELEMENT, created); // add header to envelope envelope.headerOut = header; Log.i("header", "" + envelope.headerOut.toString()); envelope.dotNet = false; envelope.bodyOut = request; envelope.setOutputSoapObject(request); //HttpTransportSE androidHttpTransport = new HttpTransportSE(URL); URL url = null; try { url = new URL(URL); } catch (MalformedURLException e1) { e1.printStackTrace(); } HttpTransportSE androidHttpTransport = null; String host = url.getHost(); int port = url.getPort(); String file = url.getPath(); Log.d("Exception d", "host -> " + host); Log.d("Exception d", "port -> " + port); Log.d("Exception d", "file -> " + file); androidHttpTransport = new KeepAliveHttpsTransportSE(host, port, file, 25000); Log.i("bodyout", "" + envelope.bodyOut.toString()); try { androidHttpTransport.debug = true; androidHttpTransport.call(SOAP_ACTION, envelope); xml = androidHttpTransport.responseDump; response = (SoapPrimitive)envelope.getResponse(); Log.i("myApp", response.toString()); } catch (SoapFault e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); Log.d("Exception Generated", ""+e.getMessage()); } return response; }
Sorry for my bad english and for the mistakes!
-21502773 0As others have said, you update properties of an immutable object by creating a new object with updated properties. But let me try to illustrate how this might work with some code.
For simplicity, let's say you are modelling a particle system, where each particle moves accordingly to it's velocity.
Your model comprises of a set of particles that are updated and then rendered to the screen each frame.
In C#, your model implementation might look like this:
public class Model { public class Particle { public double X { get; set; } public double Y { get; set; } public double Vx { get; set; } public double Vy { get; set; } } public Model() { this.particles = /* ... initialize a set of particles ... */ } public void Update() { foreach (var p in this.particles) { p.X += p.Vx; p.Y += p.Vy; } } public void Render() { /* ... clear video buffer, init something, etc ... */ foreach (var p in this.particles) { this.RenderParticle(p); } } }
Pretty straightforward. As you can see, each frame we go over entire set of particles and update coordinates of each one according to it's velocity.
Now, if the particle was immutable, there'd be no way to change it's properties, but as been said, we just create a new one with updated values. But hold on a second, doesn't that mean we'd have to replace the original particle object with an updated one in our set? Yes it does. And doesn't that mean that the set now has to be mutable? Looks like we just transfered the mutability from one place to another...
Well, we could refactor to rebuild the entire set of particles each frame. But then, the property that stores the set would have to be mutable... Hmmm. Do you follow?
It appears that at some point you'll have to lose immutability in order to cause effects, and depending on where that point is, your program will or will not have some (arguably) useful properties.
In our case (we're making a video game), we technically can postpone the mutability all the way until we get to drawing on the screen. It's good that the screen is mutable, otherwise we'd have to create a new display each frame :)
Now, let's see how this could be implemented in F#:
type Particle = { X : double Y : double Vx : double Vy : double } type Model = { Particles : Particle seq } module Game = let update model = let updateParticle p = { p with X = p.X + p.Vx; Y = p.Y + p.Vy } { model with Particles = seq { for p in model.Particles do yield updateParticle p } } let render model = for p in model.Particles do Graphics.drawParticle p
Note that in order to preserve immutability, we had to make the Update
method a function that takes a model object and returns it updated. The Render
now also takes the model object as an argument, as we don't keep it in memory anymore because it is immutable.
Hope this helps!
-30605081 0OK the answer to my 2 questions are: Yes and No.
I was missing something and there is nothing wrong with my approach.
What was worrying me was that the instantiate approach might be causing the problem as it isn't the method described in the documentation. It turns out that this was not the problem.
What was the problem was lazy copying and pasting. When I copied the tracking code from the GA website I accidentally also copied the line below. When this was copied into the single line textbox for the variable in the inspector the tracking code showed as expected but there was a hidden line that was also part of the string variable that couldn't be seen.
Slap me.
Hopefully this lesson learned helps another careless idiot avoid the same or similar mistake.
-37710071 0 Could someone tell me why this code isn't working?So I have been stuck with this for a long time now, unable to figure why it isn't working. This is a registration page which, after submitting information, should upload the information (the one I choose, not all the registration options enter the database) into a table (called tbl) inside the database (known as Database2.mdf). This is through Visual Studio 2010. There is also a java phase that checks the information but I don't think that is what is causing the problem so I'll just post the SQL code and the HTML code, along with the names of the table lines.
The SQL bit:
<%@ Page Language="C#" %> <%@ Import Namespace="System.Data.SqlClient" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> protected void Page_Load(object sender, EventArgs e) { if (Request.Form["sub"] != null) { string fName = Request.Form["FName"]; string lName = Request.Form["LName"]; string uName = Request.Form["UName"]; string Street = Request.Form["Street"]; string City = Request.Form["City"]; string Pass = Request.Form["Password"]; string PassCon = Request.Form["PasswordConf"]; string Email = Request.Form["Email"]; string Comments = Request.Form["Comment"]; int ID = int.Parse(Request.Form["ID"]); string conStr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database2.mdf;Integrated Security=True;User Instance=True"; string cmdStr = string.Format("INSERT INTO tbl (FirstName, LastName, UserName, Street, City, Password, PasswordConfirm, Email, Comments, IdentificationNumber) VALUES (N'{0}', N'{1}', N'{2}', N'{3}', N'{4}', N'{5}', N'{6}', N'{7}', N'{8}', {9})", fName, lName, uName, Street, City, Pass, PassCon, Email, Comments, ID); SqlConnection conObj = new SqlConnection(conStr); SqlCommand cmdObj = new SqlCommand(cmdStr, conObj); conObj.Open(); cmdObj.ExecuteNonQuery(); conObj.Close(); } } </script>
The HTML bit: (CheckForm is the name of the Javassript action that checks if the form matches the requirements, also Registration.aspx is the registration page obviously, and it is not linked to a master page)
<form action="Registration.aspx" method="post" name="ContactForm" onsubmit="return CheckForm()"> First Name: <input type="text" size="65" name="FName" /> <br /> Last Name: <input type="text" size="65" name="LName" /> <br /> Username: <input type="text" size="65" name="UName" /> <br /> Street: <input type="text" size="65" name="Street" /> <br /> City: <input type="text" size="65" name="City" /> <br /> Password: <input type="password" size="65" name="Password" /> <br /> Password Confimration: <input type="password" size="65" name="PasswordConf" /> <br /> E-mail Address: <input type="text" size="65" name="Email" /> <br /> Comments: <input type="text" size="100" name="Comment" /> <br /> Identification Number: <input type="password" size="65" name="ID" /> <br /> Mobile : <input type="text" id="mobile" name="mobile" style="width: 40px;" maxlength="3" /> - <input type="text" name="mobile1" maxlength="7" /> <br /> Gender: Male<input type="radio" name="gender" id="gender_Male" value="Male" checked /> Female<input type="radio" name="gender" id="gender_Female" value="Female" /> <br /> Which countries would you like to recieve political news for?: <br /> <input type='checkbox' name='files[]' id='1' value='1' /> Israel <input type='checkbox' name='files[]' id='2' value='2' /> Russia <input type='checkbox' name='files[]' id='3' value='3' /> Canada <br /> How often do you read the newspaper? <br /> <select id="cardtype" name="sel"> <option value=""></option> <option value="1">Never</option> <option value="2">Everyday</option> <option value="3">Once a week</option> <option value="4">Once a year</option> </select> <br /> What can we help you with? <select type="text" value="" name="Subject"> <option></option> <option>Customer Service</option> <option>Question</option> <option>Comment</option> <option>Consultation</option> <option>Other</option> </select> <br /> <input type="submit" value="Send" name="submit" /> <input type="reset" value="Reset" name="reset" /> </form>
The table lines are as follows:
I know this is A LOT to sift through but I have been stuck with it for so long and I must get it fixed very quickly, I would VERY much appreciate any help provided! Thanks in advance!
-24779469 0 Implement rollback in Nested stored procedureI am using TRY CATCH block to capture error and do rollback
ALTER PROCEDURE sp_first /* parameters */ BEGIN TRY BEGIN TRANSACTION /* statements */ COMMIT END TRY BEGIN CATCH IF(@@TRANCOUNT>0) ROLLBACK END CATCH
Will the above approach work if there is another stored procedure sp_inner
being called inside sp_first
which also performs DML statements INSERT , DELETE , UPDATE etc.
ALTER PROCEDURE sp_first /* parameters */ BEGIN TRY BEGIN TRANSACTION /* statements of sp_first */ -- stored procedure sp_inner also requires rollback if error occurs. EXEC sp_inner @paramaterList COMMIT END TRY BEGIN CATCH IF(@@TRANCOUNT>0) ROLLBACK END CATCH
How to implement roll back if nested stored procedure is used?
-35751448 0 Disabling"Synchronous XMLHttpRequest on the main thread is deprecated"I'm using Chrome to debug a web page, and while debugging I get frequent warnings and stops with the message "Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/."
I understand what is causing these, but they are in code over which I have no control. But their existence is making it hard to debug my code, as I have to click past twenty or so of these warnings to reach my code, and sometimes others are thrown during the execution of my code.
My question is: How do I prevent the Chrome debugger from stopping on these warnings?
-23276302 0Assuming your adapter is based off some class, and this class has the methods to set and get the switch value, you should be able to do something like this in your adapter:
public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.some_layout, null); } Switch switch_temp = (Switch) v.findViewById(R.id.item_pers_ajout_op_switch); switch_temp.setChecked(getItem(position).getTousCoches()); return convertView; } public void switchAll(boolean mySwitch) { for (int i=0; i<getCount(); i++) { getItem(i).setTousCoches(mySwitch); } notifyDataSetChanged(); }
-8174516 0 You should use strtod; it checks double overflow/underflow also like:
#include <errno.h> #include <stdio.h> #include <math.h> #include <stdlib.h> double d; char *e,s[100]; fgets(s,100,stdin); if( s[strlen(s)-1]=='\n' ) s[strlen(s)-1]=0; errno=0; d=strtod(s,&e); if( *e || errno==EINVAL || errno==ERANGE ) puts("error"); else printf("d=%f\n",d);
-22043342 0 Any decent JPA docs would tell you that a 1-N bidir relation needs mappedBy on the side with the collection. The error message is pretty clear too
-12870896 0 Google Analytics Traffic Sources issue with mobile traffic redirected to m. siteA big chunk of my traffic is mobile. My server identifies this traffic by regex on the user agent and redirects (301) from www.mydomain.com to m.mydomain.com
My site has different sources I want to get insights on (ads, Facebook, referrer sites etc)
In the traffic sources report in Google Analytics I see a big chunk of visits originate from mydomain.com. That chunk size is similar to my mobile traffic, though a little lower.
Does it make sense that the traffic source issue is related to mobile?
If so:
One option I saw was faking a Google campaign by having the server add fake parameters to the query. This way I can use Google Analytics advertising-related reports to track origin.
I'm looking for something more straightforward if possible.
Will HTTP 302 work better?
I write one function which will convert date as per my requirement as given below
var getRequiredDate = function(date) { var monthList = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; var day = date.getDate(); var month = date.getMonth(); var year = date.getFullYear(); // Use standard date methods var newdate = monthList[month] + ' ' + day + ", " + year; Ti.API.info("Date :" + newdate);
};
Hope this helps you.
-39908486 0 Django attachment and custom data in responseCould someone please let me know if I can add custom message in HTTP response along with a attachment in Django
Here is my django response with file attachment.
data = key[0] response = HttpResponse(data, content_type='text/plain') response['Content-Disposition'] = 'filename=license.txt'
I also want to send additional data with response (not part of attachment) like employee id '2343'. Can it be done? Is it a good idea to add data to header ?
thanks in advance!
-10669832 0 How to customize the full page of a listpicker?Possible Duplicate:
ListPicker FullMode Selected Item Color
I've a long list of things loading from a listpicker, mostly "useless".
Is there the possibility to add a button on top of the full page opened when I click the listpicker (so when I click on it I only show the most useful things?
Thanks a lot!
-14098246 0If you are hoping to do a random choice using strings you need to put them in an array and do Array shuffle.
shuffle($array_of_filenames); echo $array_of_filenames[0];
More examples: http://php.net/manual/en/function.shuffle.php
-38301548 0I think you did not connect the label with xib or storyboard properly.Kindly again connect the label with xib or storyboard correctly with the following screenshots and coding.
FIRST : I drag and drop the Label from the Object Library
SECOND : CLICK control + mouse on label and drag that label to ViewController.h
THIRD : Now BOX shows with default cursor in Name field
FOUR : Finally give the Label Name in Name Field of BOX
Once I did that Now the View Controller.h
#import <UIKit/UIKit.h> @interface ViewController : UIViewController @property (strong, nonatomic) IBOutlet UILabel *labelStringText; @end
Then in ViewController.m
#import "ViewController.h" @interface ViewController () @end @implementation ViewController @synthesize labelStringText; - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. labelStringText.text = @""; NSString *strLabelText = [NSString stringWithFormat:@"%@",labelStringText.text]; //OR NSString *strLabelText = labelStringText.text; }
for your simple understanding I set the label.text to string in viewDidLoad.You just set the string where you want.
-40689117 0Seems you set inappropriate maximum nested level in style checks which provided by compiler switch "-gnatyL" and then set up the compiler to treat all warnings and style checks as errors by "-gnatwe" switch.
-2473340 0Why are you making this generic? Just overload the method.
void bar(A a) { a.Foo(); } void bar(B b) { b.Foo(); }
Generics are there so that you can make potentially infinite bar()
methods.
I am trying to execute multiple docker images run from single docker file with different ports. Please advise How to execute multiple "docker run" commands from single docker file with different ports.
-14085145 0Tobias Ternstrom at Microsoft has a workaround that works for sql server2005 and higher: Consider the following example using the AdventureWorks microsoft sample database:
SELECT soh.OrderDate ,( SELECT p.Name + ', ' FROM Production.Product AS p INNER JOIN Sales.SalesOrderDetail AS sod ON p.ProductID = sod.ProductID WHERE sod.SalesOrderID = soh.SalesOrderID FOR XML PATH(''), TYPE ).value('/', 'NVARCHAR(max)') AS ProductsOrdered FROM Sales.SalesOrderHeader AS soh
See where they discuss the same problem here: string aggregate function, something like SUM for numbers
-17070179 0 Deleting a file in JavaI want to delete a file, and sometimes I can, sometimes I don't. I'm doing this:
String filePath = "C:\\Users\\User\\Desktop\\temp.xml"; File f = new File(filePath); if (f.exists()) { if(f.delete()) System.out.println("deleted"); else System.out.println("not deleted"); }
I think that when I can't delete it is because it is still open somewhere in the Application. But how can I can I close it, if I don't use the FileInputStream
or the BufferedReader
? Because if I use those classes, I can't see if the file exists. Or can I?
Edit: I just found my error. I was doing this:
XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(new FileOutputStream(filePath));
and then, closing just the eventWriter
.
And I have to do this:
FileOutputStream fos = new FileOutputStream(filePath); XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(fos);
and then:
eventWriter.close(); fos.close();
-10876559 0 char * bytes = [SomeData bytes];
-14547761 0 Your code looks correct. The most likely problem is that it's being built incorrectly, but to address this we need to see your Makefile.
At the link below (wouldn't let me post the link so you have to copy/paste it yourself) is a post by someone who had a very similar problem to yours. It turned out that he was not running his compiled object file through the linker, with the result that some essential library was missing which caused the PIC to loop endlessly, trying to execute an invalid opcode (instruction).
efreedom dot com/Question/E-27081/Using-Avr-Gcc-Delay-Ms-Causes-Chip-Freeze
If this doesn't fix it, try posting your Makefile.
Also, there is no reason to call _delay_ms(10) 100 times, you can just call _delay_ms(1000) directly. It will use a lower resolution.
Edit: After seeing your Makefile it looks like your clock speed might be set incorrectly. The CLOCK setting specifies what speed you are running your AVR at, if it's set to something way off (like 8MHz and your PIC is running at 1MHz), the delay loop will take 8 seconds when you expect it to take one - if that's the problem your LED's will appear frozen but if you wait long enough they will actually change. Try removing the -DF_CPU=$(CLOCK) statement and see if it makes a difference.
Apart from that your Makefile has a lot of unused/unnecessary stuff, and since I don't have a working avr-gcc setup at the moment, it's hard to follow, so it will help if you try simplifying the Makefile like the following, and see if it works - it will be close, please comment below if you get any problems!
DEVICE = attiny2313 CLOCK = 8000000 OBJECTS = main.o # Tune the lines below only if you know what you are doing: AVRDUDE = avrdude $(PROGRAMMER) -p $(DEVICE) COMPILE = avr-gcc -Wall -Os -DF_CPU=$(CLOCK) -mmcu=$(DEVICE) # symbolic targets: all: main.hex flash: all $(AVRDUDE) -U flash:w:main.hex:i clean: rm -f main.hex main.elf $(OBJECTS) main.elf: $(OBJECTS) $(COMPILE) -o main.elf $(OBJECTS) main.hex: main.elf rm -f main.hex avr-objcopy -j .text -j .data -O ihex main.elf main.hex avr-size --format=avr --mcu=$(DEVICE) main.elf
-23849929 0 how to make uitextview scroll in iOS Storyboards I have a uitextview with more text that can fit in the view. I enabled "scrolling enabled" on the textview, however the scrollview does not scroll.
Here is how I populate the textview in viewDidLoad
:
PFQuery *query = [MyObject query]; [query whereKey:@"cycleNumber" equalTo:_cycleNumber]; [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) { if([objects count] > 0){ NSString *description = objects[0]; _lessonDescriptionTextView.text = description; } }];
How can I make the textview scroll to show all content?
-27820074 0If you change
<xsl:template match="order"> <order job_id="{job_id}" site_code="{site_code}" replace="{replace}"> <xsl:apply-templates/> </order> </xsl:template>
to
<xsl:template match="order"> <order job_id="{job_id}" site_code="{site_code}" replace="{replace}"> <xsl:apply-templates select="node()[not(self::job_id|self::site_code|self::replace)"/> <xsl:copy-of select="following-sibling::master_version[1]"/> </order> </xsl:template>
and then add <xsl:template match="master_version"/>
you get the nesting, assuming it should be done for the following sibling master_version
element and not based on some reference value.
void *multiply()
The values of struct variables a
and b
are not initialized within this function you should be passing the scanned values in main()
to this function as well as divide()
There is no reason here I see why you are returning void *
. Pass parameters by reference or by value.
Template value must be compile-time constant, that is literal, constexpr
or static const
variable.
Using: ember 1.7.0
I have some server-side data that I want to load up in my ember app before any routes are transitioned to. Multiple (but not all) of my other routes / controllers need this data. I was thinking that I could just load up this data in the ApplicationRoute model
method. It works fine, but does not display a loading state.
Is it possible to have the ApplicationRoute display a loading state until it's model
promise gets resolved.
Here's a jsbin illustrating the problem: http://jsbin.com/soqivo/1/
Thanks for the help!
-7237488 0Value property of NumericUpDown is Decimal - that is perhaps why you are having issues. In your if block, I would consider casting the Value Property of NumericUpDown object into an integer in the true part and use integer value 3 in its else part. There after, I would avoid parsing again and give it to Substring as is.
-17839560 0To answer your question directly:
Configuration > Content Authoring > Configure (the format)
At the bottom under "Filter settings" there should be a list of allowable HTML tags. Just add in
For a better solution:
Create an image field and display that above the text. The advantage is that Drupal will handle the uploading and storing of the image.
or install the following modules.
-23868607 0Please see this example that I made for you: http://jsfiddle.net/972ak/
$('form .close').click(function(event) { Boxy.confirm("Are you sure ?", function() { alert('ok'); }); return false; });
Boxy documentation says:
Boxy.confirm(message, callback, options) Displays a modal, non-closeable dialog displaying a message with OK and Cancel buttons. Callback will only be fired if user selects OK.
http://onehackoranother.com/projects/jquery/boxy/
-37124233 0In your __init__
method and in some other places you refer to self.__speed
. However, in your accelerate
and brake
methods you refer to self.speed
, which is not the same thing. Make all the references the same and your problem should be resolved.
I have a webserver (CherryPy) running with on a Cubox (armhf platform) and upon starting the wever i get the following error:
[14/Aug/2015:09:33:40] HTTP Traceback (most recent call last): File "(...)/lib/python3.4/site-packages/cherrypy/_cprequest.py", line 661, in respond self.hooks.run('before_request_body') File "(...)/lib/python3.4/site-packages/cherrypy/_cprequest.py", line 114, in run raise exc File "(...)/lib/python3.4/site-packages/cherrypy/_cprequest.py", line 104, in run hook() File "(...)/lib/python3.4/site-packages/cherrypy/_cprequest.py", line 63, in __call__ return self.callback(**self.kwargs) File "(...)/lib/python3.4/site-packages/cherrypy/lib/sessions.py", line 901, in init httponly=httponly) File "(...)/lib/python3.4/site-packages/cherrypy/lib/sessions.py", line 951, in set_response_cookie cookie[name]['expires'] = httputil.HTTPDate(e) File "(...)/lib/python3.4/site-packages/cherrypy/_cpcompat.py", line 278, in HTTPDate return formatdate(timeval, usegmt=True) File "/usr/lib/python3.4/email/utils.py", line 177, in formatdate now = time.gmtime(timeval) OverflowError: timestamp out of range for platform time_t
I'm not sure whether I understand the problem correctly and I am not sure if it can be fixed by me. As far as I can tell by the Traceback it is caused by CherryPy. This error causes a 500 Internal Server Error
and won't load the page.
As asked in the comments I inserted a print. I don't see any thing special. This is the output of starting the server and once trying to load the page:
1439551125.1483066 1439551132.639804 4593151132.6458025 1439551132.723468 1439551132.7210276 1439551132.7268708 1439551132.7359934 1439551132.741787 1439551132.7452564 4593151132.750907 4593151132.762612 4593151132.749376 4593151132.731232 4593151132.754474 4593151132.763546 1439551132.8183882 4593151132.828029 1439551132.8379567 4593151132.856025 1439551132.8734775 1439551132.8554301 1439551132.879614 4593151132.884698 4593151132.890394 1439551132.8971672 4593151132.902081 4593151132.908171 1439551132.931757 4593151132.944052 1439551132.9759347 1439551132.9714596 4593151132.987068 4593151132.985899 1439551132.9926524 1439551133.0088623 4593151133.013047 1439551133.0280995 4593151133.040709 4593151133.029601 1439551133.0500746 4593151133.057341 1439551133.0749385 4593151133.081711 1439551133.1032782 4593151133.115171 1439551133.1194305 1439551133.1354048 4593151133.143136 4593151133.151044 1439551133.1612003 4593151133.16934 1439551133.1827784 4593151133.19687 1439551133.201899 4593151133.209947 1439551133.271833 4593151133.277573 1439551133.3090906 4593151133.312978 1439551133.3408027 4593151133.344741 1439551133.3722978 4593151133.376283 1439551133.4031894 4593151133.407124 1439551133.434834 4593151133.439074
I am not sure which of these values causes the error. I am guessing it's the one with 4 in front? On a windows machine time.gmtime(4593151133.439074)
returns a struct which contains the year 2115.
On the Cubox when starting a python shell and entering time.gmtime(4593151133.439074)
I can reproduce the error. But I don't know where these values come from.
EDIT
I have found the file and line in CherryPy that returns me the floating numbers which lead to the year 2115. It is line 949 - 951 in the file session.py:
if timeout: e = time.time() + (timeout * 60) cookie[name]['expires'] = httputil.HTTPDate(e)
Why I get such a high timeout, I don't know.
-28701232 0In order to query based on two separate Parse classes, where one part of the query is a pointer to another class, the best way to do so is to have an outer query on the class which contains the pointer, and then an inner query that finds whatever supplementary objects you're looking for. In my case, this meant finding businesses that were in the user's location, and then only showing Business Posts near the user's location, where in the "BusinessPost" class, the key "Business" is a pointer to my "Business" class, that contains other information about the business that the UI needed. The query would look as follows:
override func queryForTable() -> PFQuery! { var getPosts = PFQuery(className: self.parseClassName) var getBusinesses = PFQuery(className: "Businesses") if locationUpdated == false { return nil } else { getBusinesses.whereKey("City", equalTo: self.city) getBusinesses.whereKey("State", equalTo: self.state) getPosts.whereKey("Business", matchesQuery: getBusinesses) getPosts.includeKey("Business") self.tableView.hidden = false self.tableView.reloadData() return getPosts }
Hope this can help others that are looking to accomplish a similar query with Parse and Swift.
-24622604 0$('td:first-child').after('<td>new cell</td>');
-9245224 0 What you are looking for is a clearfix so that your elements will load properly. See the linked SO question "Which method of 'clearfix' is best?" for numerous possible clearfixes.
The reason why the footer
element places itself next to the main
element is because absolutely-positioned elements are removed from the page flow. As a result, later elements treat the absolutely-positioned element as if it was not there in the first place. With a clearfix, this issue is resolved.
I need to install the JCE in my Wheezy machine.
According to the documentation, I should replace the files local_policy.jar and US_export_policy.jar in $java_home/lib/security. However, my system doesn't have these files, and just copying JCE's files there don't work, as my code is failing and looking for the error it seems to be due to the lack of JCE.
[java] GSSException: Failure unspecified at GSS-API level (Mechanism level: Checksum failed) [java] at sun.security.jgss.krb5.Krb5Context.acceptSecContext(Krb5Context.java:788) [java] at sun.security.jgss.GSSContextImpl.acceptSecContext(GSSContextImpl.java:342) [java] at sun.security.jgss.GSSContextImpl.acceptSecContext(GSSContextImpl.java:285) [java] at mistic.id.krbAction.run(krbAction.java:44) [java] at mistic.id.krbAction.run(krbAction.java:1) [java] at java.security.AccessController.doPrivileged(Native Method) [java] at javax.security.auth.Subject.doAs(Subject.java:356) [java] at mistic.id.Server.acceptSecurityContext(Server.java:119) [java] at mistic.id.Server.main(Server.java:70) [java] Caused by: KrbException: Checksum failed [java] at sun.security.krb5.internal.crypto.Aes256CtsHmacSha1EType.decrypt(Aes256CtsHmacSha1EType.java:102) [java] at sun.security.krb5.internal.crypto.Aes256CtsHmacSha1EType.decrypt(Aes256CtsHmacSha1EType.java:94) [java] at sun.security.krb5.EncryptedData.decrypt(EncryptedData.java:177) [java] at sun.security.krb5.KrbApReq.authenticate(KrbApReq.java:278) [java] at sun.security.krb5.KrbApReq.<init>(KrbApReq.java:144) [java] at sun.security.jgss.krb5.InitSecContextToken.<init>(InitSecContextToken.java:108) [java] at sun.security.jgss.krb5.Krb5Context.acceptSecContext(Krb5Context.java:771) [java] ... 8 more [java] Caused by: java.security.GeneralSecurityException: Checksum failed [java] at sun.security.krb5.internal.crypto.dk.AesDkCrypto.decryptCTS(AesDkCrypto.java:451) [java] at sun.security.krb5.internal.crypto.dk.AesDkCrypto.decrypt(AesDkCrypto.java:272) [java] at sun.security.krb5.internal.crypto.Aes256.decrypt(Aes256.java:76) [java] at sun.security.krb5.internal.crypto.Aes256CtsHmacSha1EType.decrypt(Aes256CtsHmacSha1EType.java:100) [java] ... 14 more
So, how could I successfully install JCE in Debian?
-37040467 1 Ignoring zero division errorI'm writing a program that reads integer values from an input file, divides the numbers, then writes percentages to an output file. Some of the values that my program may be zero, and bring up a 0/0 or 4/0 occasion.
From here, I get a Zerodivisionerror, is there a way to ignore this error so that it simply prints 0%??
Thanks.
-20989083 0atomically $ readTVar checking
does what you want. The GHCi REPL automatically executes any IO action that you give it.
In my split app the detail view does not bind any model.
In the component.js
I instantiate a named model like this:
// creation and setup of the oData model var oConfig = { metadataUrlParams: {}, json: true, defaultBindingMode : "TwoWay", defaultCountMode : "Inline", useBatch : false } // ### tab-employee ### var oModelEmpl = new sap.ui.model.odata.v2.ODataModel("/sap/opu/odata/sap/EMP_SRV"), oConfig); oModelEmpl.attachMetadataFailed(function() { this.getEventBus().publish("Component", "MetadataFailedEMPL"); }, this); this.setModel(oModelEmpl, "EMPL");
The method onSelect
in der master-view controller is fired by clicking on an listitem.
onSelect: function(oEvent) { this.showDetail(oEvent.getParameter("listItem") || oEvent.getSource()); }
This will call the method showDetail
showDetail: function(oItem) { var bReplace = jQuery.device.is.phone ? false : true; this.getRouter().navTo("detail", { from: "master", entity: oItem.getBindingContext('EMPL').getPath().substr(1), }, bReplace); },
In the controller of the detail-view I've these two methods for updating the binding. onRouteMatched
calls bindView
, where I get the error-message TypeError: oView.getModel(...) is undefined
.
onRouteMatched: function(oEvent) { var oParameters = oEvent.getParameters(); jQuery.when(this.oInitialLoadFinishedDeferred).then(jQuery.proxy(function() { var oView = this.getView(); if (oParameters.name !== "detail") { return; } var sEntityPath = "/" + oParameters.arguments.entity; this.bindView(sEntityPath); }, this)); }, bindView: function(sEntityPath) { var oView = this.getView(); oView.bindElement(sEntityPath); //Check if the data is already on the client if (!oView.getModel().getData(sEntityPath)) { // Check that the entity specified was found. oView.getElementBinding().attachEventOnce("dataReceived", jQuery.proxy(function() { var oData = oView.getModel().getData(sEntityPath); if (!oData) { this.showEmptyView(); this.fireDetailNotFound(); } else { this.fireDetailChanged(sEntityPath); } }, this)); } else { this.fireDetailChanged(sEntityPath); } },
I've tried to implement this split app relative to the template generated by WebIDE. Any idea what is missing?
-178891 0I would avoid using the !important clause and instead just ensure their values appear in a <style>
tag following the import of the regular style sheets.
Otherwise, I would do it the same way.
-12311391 0set height as fill_parent
, the width as wrap_content
and you fix the aspect ratio with android:adjustViewBounds="true"
containerView
and show button
are in different viewControllers. So you can't just hide it. The simple way to achieve it is when you select the cell in containerView
, present the ParentViewController
, and the view in ContainerViewController
will dismiss automatically.
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { [self.delegate ContainerViewBLETable:self andSelectedDone:[NSString stringWithFormat:@"%ld",indexPath.row]]; ParentViewController *vc = [[self storyboard] instantiateViewControllerWithIdentifier:@"ParentViewController"]; [self presentViewController:vc animated:YES completion:nil]; }
To show the container, you can just dismiss the ParentViewController
that presenting. 1.
- (IBAction)btnAction:(id)sender { [self.presentingViewController dismissModalViewControllerAnimated:YES]; }
Or 2. Set up segue to dismiss viewController and use prepareForSegue for delegate to communicate with other viewController.
Also REMOVE vc.view.hidden = YES
in delegate you had implemented
-(void) ContainerViewBLETable:(ContainerViewBLETable *)vc andSelectedDone:(NSString *)selectedStr.
-24762104 0 Prevent recursive function locking the browser I have a recursive function which is locking my browser while running.
While this function is running all my jquery commands are locked waiting for the function end.
What should I do to make this function asynchronous?
This function runs on document.ready
function SearchTrip() { $.post("/extensions/searchtrip", { from: $("#from").val(), to: $("#to").val(), ddate: $("#ddate").val() }, function (mReturn) { if (mReturn.fTotalAmount != '0,00') { var sAirline = ''; if (mReturn.Airline) sAirline = ' pela ' + mReturn.Airline; $("#buscandoPassagens").hide(); } else if (SearchTripAmount < 5) { SearchTripAmount++; setTimeout(function () { SearchTrip(); }, 500); } else { $("#pNaoEncontrada").show(); } }, "json"); }
-7788299 0 I agree with the other commenters that this question needs more information about the initial conditions of your problem before it can be properly answered. However, a scenario that causes your code to fail comes to mind immediately.
Suppose that plist is a circularly linked list with three elements: A <-> B <-> C <-> A, and plist points to A.
When your code runs, it will: deallocate A, advance to B, deallocate B, advance to C, deallocate C and then advance to the freed memory that was A. Now your code blows up. (or runs forever)
Since it is a doubly linked list, you should use your previous links to null out your next links before deallocating. And for good measure, null out your prev links as well.
temp_nlist = n_list->next; temp_nlist->prev = NULL; if (n_list->prev != NULL) n_list->prev->next = NULL; free(n_list); n_list = temp_nlist;
-15538241 0 combining cells in table how do i embed a youtube video to a table. i want the left and right columns to be 2 rows high and the middle column to have 2 cells, i want the video in the bottom cell, and the text in the top but i cant figure out how to move it there
<div class="cbody"> <table class="ctable"> <tr> <td rowspan="2" style="width:105px"><img class="cimg1" src="meh.png" alt=" " width="100px" height="500px"></td> <td><p class="ctxt"> my text here </p></td> <td rowspan="2" style="width:105px"><img class="cimg2" src="meh.png" alt=" " width="100px" height="500px"></td> </tr> <tr> <iframe width="420" height="315" src="http://www.youtube.com/embed/xI_6oLPC-S0" frameborder="0" allowfullscreen></iframe> </tr> </table> </div>
and the css...
.cbody { width:800px; margin-left: auto; margin-right: auto; border-style:solid; border-width:3px; } .cimg1 { padding-left:5px; padding-top:5px; padding-bottom:5px; float:left; } .cimg2 { padding-left:5px; padding-top:5px; padding-bottom:5px; float:right; } .ctxt { margin-left:5px; margin-right:5px; text-align:center; } .ctable { width:800px; margin-left:auto; margin-right: auto; border-style:solid; border-width:2px; }
-19477217 0 Calling a Java method using javascript from within a JPanel I have a Java application which displays results on a JPanel. The results are displayed using HTML by using a JLabel.
Now I want to let the user interact with the local application by allowing local methods to be called when the user clicks on a link in that HTML document.
Is this possible?
-1551407 0 How to represent AppDomain in ASP.NET?Recently i attentened an interview.I have been asked to explain the "Application Domain" and the special purpose about the introduction of "application domain".
I explained :
AppDomain is a runtime representation of a logical process withing a physical process (win32) managed by CLR.
Special purpose :
Keeps high level application isolation ;fall down of one AppDomain never interrupt othe AppDomain.
But still the interviewer expects lots from me ? what are the additional points could i add further?
Thanks.
-40659955 0What happened to?:
public interface AsyncResponse<T> { void processFinish(T output); }
Even if it's not overloading, it seems simple In my eyes.
-14040996 0No. Theres a similar question here: Why should you remove unnecessary C# using directives?
Check it out, it's very well answered.
-13975467 0Change your code as:
String strcategory = getIntent().getExtras().getString("categoriaId");
because you are passing String
from onListItemClick to sondaggioActivity Activity and trying to receive as Int
NOTE :
Second and important point is id
is long
and you are trying to parsing it to Int
which is also not valid . see this post: How can I convert a long to int in Java?
Solution is just send id as long from onListItemClick
as
myIntent.putExtra("categoriaId",id);
and receive it as in sondaggioActivity
Activity :
long category = getIntent().getExtras().getLong("categoriaId");
-16050081 0 PostgresSQL combining tables I am a little confused about merging one table into another. My two tables looks like so:
Table A Table B id | name | likes | email | username id | name | email | username 1 | joe | 3 | null | null 1 | ben | a@co.co | user Result: Table A id | name | likes | email | username 1 | joe | 3 | null | null 2 | ben | null | a@co.co | user
My issue is that I do not want to overwrite the properties that are in the Table A. Is this a simple UNION
?
Slight modification to @maxim-lanin's answer. You can use it like this, fluently.
\Mail::send('email.view', ['user' => $user], function ($message) use ($user) { $message->to($user->email, $user->name) ->subject('your message') ->getSwiftMessage() ->getHeaders() ->addTextHeader('x-mailgun-native-send', 'true'); });
-6915150 0 Error when using getter/setter methods on Sprite I'm trying to make a class that extends the Sprite, have some private properties attached to it and be able to read and write those properties using getters and setters. Simple... but the compiler throw this error "Access of possibly undefined property speed through a reference with static type flash.display:Sprite." It works if I set my class to extend the MovieClip object. Could someone explain me the logic behind this? why I can't use getter and setters with a Sprite?
Here is a sample code:
package { import flash.display.Sprite; public class Vehicle extends Sprite{ private var _speed:uint = 3; public function get speed():uint { return _speed; } public function set speed(value:uint):void { _speed = value; } public function Vehicle() { super(); } } }
-34697812 0 With Automatic Uploads checked ON, it is uploading files automatically even before I'm done making all changes to the PHP files and before I even click SAVE button and resulting in INCOMPLETE script files. It is also uploading files in other tab pages. Looks like there is no precise control on uploads in PhpStorm.
-39116778 0 how to convert S3ObjectInputStream to PushbackInputStreamI am uploading an excel(xls) file to s3 and then another application should download that file from s3 and parse using Apache POI reader. The reader accepts inputstream
type as the input but for proper parsing of the excel it expects PushbackInputStream
. The inputstream i get from the file downloaded from s3 is of type S3ObjectInputStream
. How do i convert S3ObjectInputStream
to PushbackInputStream
?
I tried directly passing the S3ObjectInputStream
(since this is an inputStream
) to PushbackInputStream
, but it resulted in the following exception :
org.springframework.batch.item.ItemStreamException: Failed to initialize the reader at org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader.open(AbstractItemCountingItemStreamItemReader.java:147) at org.springframework.batch.item.support.CompositeItemStream.open(CompositeItemStream.java:96) ..... ..... Caused by: java.lang.IllegalStateException: InputStream MUST either support mark/reset, or be wrapped as a PushbackInputStream at org.springframework.batch.item.excel.poi.PoiItemReader.openExcelFile(PoiItemReader.java:82) .....
I tried casting S3ObjectInputStream to PushbackInputStream, but it resulted in classcastexception.
java.lang.ClassCastException: com.amazonaws.services.s3.model.S3ObjectInputStream cannot be cast to java.io.PushbackInputStream
Anyone knows the solution for this
-40348524 0Never ever solve that kind of problems via symlinking. If your system does not provide the exact soname required by a library or an executable, you'll need to recompile that library or executable. There is a reason why libraries have the soname version number in their file names, and a mismatching soname will result in a not found
for the dynamic linker/loader. You're just breaking that process and your entire system by inserting a broken soname for a library.
/usr/lib/x86_64-linux-gnu/
and remove it. Do it now.Then, how to recompile the plugin so that it works on Ubuntu?
(Or, actually, anywhere. Even Windows or Mac. Just adapt the instructions)
Step by step:
libmysqlclient-dev
package, but double check in case the name changed on your particular Ubuntu edition. Go on https://packages.ubuntu.com and use the file-based search to look for mysql.h
.INSTALL_DIR/Src/5.7/qtbase/src/plugins/sqldrivers/mysql
(adjust INSTALL_DIR
and 5.7
to your actual case).qmake
. The right one is the one coming from the same installation of Qt, and whose version matches the sources. In your case it's likely to be in INSTALL_DIR/5.7/gcc_64/bin/qmake
.make
. If it fails to compile due to some library not found, install the required packages on your system. The Ubuntu package search linked above may be useful.make
runs successfully, it will create a brand new libqsqlmysql.so
. It should automatically overwrite the one in INSTALL_DIR/5.7/gcc_64/plugins/sqldrivers
. If for any reason it's not automatically overwritten, move it manually there.Done! Enjoy your MySQL database connection.
-3474206 0Hope I understood it right. Basically you want a mapping from primitive class types to their wrapper methods.
A static utility method implemented in some Utility class would be an elegant solution, because you would use the conversion like this:
Class<?> wrapper = convertToWrapper(int.class);
Alternatively, declare and populate a static map:
public final static Map<Class<?>, Class<?>> map = new HashMap<Class<?>, Class<?>>(); static { map.put(boolean.class, Boolean.class); map.put(byte.class, Byte.class); map.put(short.class, Short.class); map.put(char.class, Character.class); map.put(int.class, Integer.class); map.put(long.class, Long.class); map.put(float.class, Float.class); map.put(double.class, Double.class); } private Class<?> clazz = map.get(int.class); // usage
-39910041 0 How to Route without reloading the whole page? I am Using react-route, and i am facing some trouble with routing.
The whole page is reloading , causing all the data that i have already fetched and stored in the reducer to load every time.
Here is my Route file :
var CustomRoute = React.createClass({ render:function(){ return <Router history={browserHistory}> <Route path="/" component={Layout}> <IndexRedirect to="/landing" /> <Route path="landing" component={Landing} /> <Route path="login" component={Login} /> <Route path="form" component={Form} /> <Route path="*" component={NoMatch} /> </Route> </Router> }, });
Before routing i already store data by calling action in my main.jsx
/** @jsx React.DOM */ 'use strict' var ReactDOM = require('react-dom') var React = require('react') var Index = require('./components/index') var createStore = require("redux").createStore var applyMiddleware = require("redux").applyMiddleware var Provider = require("react-redux").Provider var thunkMiddleware = require("redux-thunk").default var reducer = require("./reducers") var injectTapEventPlugin =require('react-tap-event-plugin'); injectTapEventPlugin() var createStoreWithMiddleware=applyMiddleware(thunkMiddleware)(createStore); var store=createStoreWithMiddleware(reducer); store.dispatch(actions.load_contacts()) //////////// <<<<<< this is what i call to store data already ReactDOM.render( <Provider store={store}><Index/></Provider> , document.getElementById('content'))
The issue is i have to route to another page if sucess login :
this.props.dispatch(actions.login(this.state.login,this.state.password,(err)=>{ this.setState({err:err}) if (!err){ window.location = "/form" } }));
The window.location does the trick but it reloads everything which is very inefficient. In manual route i use <Link\>
that routes without reloading, however for automated i am not sure how to do it.
Any Suggestion will be much appreciated.
-40233293 0The error, if you say callbacks are not being called, might just be the sign that you may not have connected first. I imagine you have implemented the callbacks and they are not being called?
In any case, to "handle" the error situation, you may want to check if the GoogleApiClient
is connected.. like this:
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) { Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback( new ResultCallback<Status>() { @Override public void onResult(Status status) { ApplicationPreferences.get().clearAll(); Intent intent = getIntent(); finish(); startActivity(intent); } }); } else{ Log.w("SomeTag", "It looks like GoogleApiClient is not connected"); }
But I do think you need to check if there are any errors (for instance does onConnectionFailed(ConnectionResult result)
get called instead? What error do you see?
Hope this helps.
-23265815 0 ASP.NET MVC: Accessing binded model in controller without using a form AND AjaxI have the following scenario:
@model IEnumerable<UI.Models.Customer> @grid.GetHtml( columns: grid.Columns( grid.Column( format: @<text> @Html.ActionLink("Edit", "EditAct", ???) </text> ), grid.Column( format: @<text> @Html.TextBox("Name", (string)item.Name) </text> ) ) )
model is just a List consisting of 3 Customer's (Customer is a dummy class with only 2 properties, i.e. ID and Name)
Now, i want to be able to capture in the controller action "EditAct "the Customer, which the user want's to edit. Those were the things, that i desperately tried without success:
1) I tried to fill in ??? with a
new {customer: item}
and to capture it in controller this way:
public ActionResult SampleFormParams(Customer customer) {...}
This approach does not work, because HTML anchor links uses GET and we can't send an object with GET.
2) It tried to fill in ??? with a
new {customer: jsSerializer.Serialize(item)}
and to capture it in controller this way:
public ActionResult SampleFormParams(String customer) { //deserialize(customer) }
This also does not work, because "item" is not a Customer object, but it is a WebGridRow object.
3) It tried to fill in ??? with a
new {customer: item.ID}
and to capture it in controller this way:
public ActionResult SampleFormParams(int id) { ... }
I wanted to know if it would be possible to access the whole IEnumerable model, so that i can find the specified customer in the model using the given id ?
So the question is, is there any way, that i can access model directly just with an anchor i.e. ActionLink
- without using a form> AND without using Ajax ?
I also checked the Custom Model Binder, but it is also based on a form>.
-40341014 0The list is showing inside a Bottom Sheet. It can be slide up from the bottom of the screen to reveal more content. Bottom Sheets are now supported in v23.2 of the support design library and onwards. There are two types of bottom sheets supported: persistent and modal. Persistent bottom sheets show in-app content, while modal sheets expose menus or simple dialogs.
There are lots of tutorials available. Here are some of them: https://guides.codepath.com/android/Handling-Scrolls-with-CoordinatorLayout#bottom-sheets
-27377491 0 Set number of cells depending on array sizeI'm a beginner and I want to change the number of cells in a collection view depending on whether the user would like to add more cells or not. I tried doing the same thing i did for table views but that doesn't seem to work. no matter what I change the size of the decks array to i only seem to be getting one cell on the screen.
Here is my code :
class FlashViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { @IBOutlet var collectionView: UICollectionView! var decks = [5] override func viewDidLoad() { super.viewDidLoad() // Move on ... let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout() layout.sectionInset = UIEdgeInsets(top: 75, left: 20, bottom: 10, right: 20) layout.itemSize = CGSize(width: 150, height: 200) collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout) self.collectionView.dataSource = self self.collectionView.delegate = self collectionView.registerClass(DeckCollectionViewCell.self, forCellWithReuseIdentifier: "DeckCollectionViewCell") collectionView.backgroundColor = UIColor.whiteColor() self.view.addSubview(collectionView!) } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.decks.count }
-21113348 0 Android alertdialog not showing when I think it should I'm developing an android app which I want to check if there's internet connection, if it's not the case display a warning message, and when there's internet connection again load a certain url.
It can be said that both displaying the message and checking there's internet connection work... but no separately.
I mean I have the following code:
if (!checkConnectivity()) { browser.stopLoading(); LayoutInflater layoutinflater = LayoutInflater.from(app); final View textEntryView; textEntryView = layoutinflater.inflate(R.layout.exitdialog, null); new AlertDialog.Builder(app) .setView(textEntryView) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle("Exit") .setNegativeButton("CANCEL", null) .show(); while (!checkConnectivity()) { } browser.loadUrl(url); }
If I don't use from while (!checkConnectivity()) to browser.loadUrl(url); then AlertDialog shows properly.
If I don't use from LayoutInflater layoutinflater = LayoutInflater.from(app); to .show(); then the app loads the web page correctly on browser.
But if I use the whole code it looks like it enters the while (!checkConnectivity()) loop before it does the show as what happens when internet connection is restabilished is that the alert dialog is shown briefly and the the web page is loaded.
I find this pretty weird, as I'm not using, as far as I know, threads that could cause that one could be executed before other one, and this is not the case this thing doesn't fulfill one of the most basic things in programming, I mean if an instruction is before another one, the one that's before should be plenty executed logically (except for threads).
Hope someone has an idea about this and can help me.
-12054987 0 Devise/OmniAuth - LinkedIn: Email is blank in callbackI'm using Devise 2.1.2 with multiple OmniAuth providers. My devise.rb file contains this line:
config.omniauth :linkedin, API_KEY, SECRET_KEY, :scope => 'r_emailaddress', :fields => ["email-address"]
It is currently stripped down to just email-address since that is the only thing acting strange. Taking a look inside request.env['omniauth.auth'].info
, the email
key is blank.
How come? I don't want to bypass validation, I wan't to use the email address from the users LinkedIn account.
-36608393 0scanf
doesn't try to do a full pattern match of the format string. %s
input format simply reads everything up to the next whitespace (or EOF). After that, it looks for a ;
, and since it doesn't find that it doesn't parse any of the other inputs.
If you want to stop at some other character, use [^char]
scanf("[^;];%[^=]=%s", id, banner, cp);
-30664773 0 Why ClassName.class.getFields() returns only public fields? I have one class A
public class A { String host = "localhost"; public String port = "8078"; protected String preFix = "www."; private String postFix = "/uploads"; }
I am getting field details of class A using below code
public static void main(String[] args) { Field[] fields = A.class.getFields(); System.out.println("fields are:" + Arrays.toString(fields)); }
The output is
fields are:[public java.lang.String org.test.A.port]
I understand getFields() method returns only those fields which are declared with public access specifier.
But why Java implemented getFields() like this?
What is the main intention of Java Team for this kind of implementation?
-8073396 0When the file is uploaded it is stored in the tmp folder, to perform any action on it you need to use the tmp path which can be accessed using $_FILES['fotoname']['tmp_name']
, I think thats what you are looking for.
You can take the iterator
from the List of OrdemItem here:
private List<OrderItem> items = new ArrayList<OrderItem>();
and do:
public Iterator<OrderItem> iterator() { return items.iterator(); }
instead of doing
public Iterator<OrderItem> iterator() { return this.iterator(); //How to do this part?? }
-40956784 0 I would use:
if [ $YARN -eq 1 ]; then npm install -g yarn && echo "yarn installed" fi
My bash reports 1 if program is not installed and i am not sure if value 1 will pass the -z test
-10050677 0You can enable the re-pinning button by clicking the "Stop Debugging" button.
-30422729 0 Performance difference between member function and global function in release versionI have implemented two functions to perform the cross product of two Vectors (not std::vector), one is a member function and another is a global one, here is the key codes(additional parts are ommitted)
//for member function template <typename Scalar> SquareMatrix<Scalar,3> Vector<Scalar,3>::outerProduct(const Vector<Scalar,3> &vec3) const { SquareMatrix<Scalar,3> result; for(unsigned int i = 0; i < 3; ++i) for(unsigned int j = 0; j < 3; ++j) result(i,j) = (*this)[i]*vec3[j]; return result; } //for global function: Dim = 3 template<typename Scalar, int Dim> void outerProduct(const Vector<Scalar, Dim> & v1 , const Vector<Scalar, Dim> & v2, SquareMatrix<Scalar, Dim> & m) { for (unsigned int i=0; i<Dim; i++) for (unsigned int j=0; j<Dim; j++) { m(i,j) = v1[i]*v2[j]; } }
They are almost the same except that one is a member function having a return value and another is a global function where the values calculated are straightforwardly assigned to a square matrix, thus requiring no return value.
Actually, I was meant to replace the member one by the global one to improve the performance, since the first one involes copy operations. The strange thing, however, is that the time cost by the global function is almost two times longer than the member one. Furthermore, I find that the execution of
m(i,j) = v1[i]*v2[j]; // in global function
requires much more time than that of
result(i,j) = (*this)[i]*vec3[j]; // in member function
So the question is, how does this performance difference between member and global function arise?
Anyone can tell the reasons?
Hope I have presented my question clearly, and sorry to my poor english!
//----------------------------------------------------------------------------------------
More information added:
The following is the codes I use to test the performance:
//the codes below is in a loop Vector<double, 3> vec1; Vector<double, 3> vec2; Timer timer; timer.startTimer(); for (unsigned int i=0; i<100000; i++) { SquareMatrix<double,3> m = vec1.outerProduct(vec2); } timer.stopTimer(); std::cout<<"time cost for member function: "<< timer.getElapsedTime()<<std::endl; timer.startTimer(); SquareMatrix<double,3> m; for (unsigned int i=0; i<100000; i++) { outerProduct(vec1, vec2, m); } timer.stopTimer(); std::cout<<"time cost for global function: "<< timer.getElapsedTime()<<std::endl; std::system("pause");
and the result captured:
You can see that the member funtion is almost twice faster than the global one.
Additionally, my project is built upon a 64bit windows system, and the codes are in fact used to generate the static lib files based on the Scons construction tools, along with vs2010 project files produced.
I have to remind that the strange performance difference only occurs in a release version, while in a debug build type, the global function is almost five times faster than the member one.(about 0.10s vs 0.02s)
-26994885 0I think you can't do this only in css. I think some JQuery will help.
$('#mytable tr:visible').each(function( index ){ //Your code to add ODD and even class })
-13676790 0 It seems that Visual Studio 2012 doesn't like non-default fonts. Probably a bug in VS2012. Press the use Default fonts to solve the problem, so far that's the only solution I know.
-36784597 0Assuming you already have a database connection called db
set up, to get a list of the column names, you can use the following code:
do { let tableInfo = Array(try db.prepare("PRAGMA table_info(table_name)")) for line in tableInfo { print(line[1]!, terminator: " ") } print() } catch _ { }
where table_name
is replaced with the literal string of your table's name.
You can also add
print(tableInfo)
to see more pragma info about your table.
Credits
Thanks to this answer for clues of how to do this.
-4993372 0You should not embed firstName and lastName in the primary key. userId should be your primary key, and you should add a unique constraint on [firstName, lastName]. BTW, putting these additional fields in the primary key only guarantees that [idUser, firstName, lastName] is unique, but you might still have two users with different idUsers, but with the same [firstName, lastName].
Now to answer the original question, I don't see where the problem is :
UserId userId = new UserId("theId", "theFirstName", "theLastName"); User user = (User) session.load(User.class, userId);
-3272072 0 As explained in this answer, you need to add a TargetFrameworkVersion by manually editing the .vcxproj file.
I have VS2008 installed on that machine but I think I also selected to include the VC90 compilers when I installed 2010.
However, it appears it is not supported by design, according to this Microsoft response: targeting the 3.5 framework with the Visual C++ 2010 compiler is not supported. The Visual C++ 2010 compiler only supports targeting the 4.0 framework.
-1070569 0The answer is: don't do it.
Have the calling application either pass you whatever you need to know in the call, or perhaps in your constructor. The called component should not require knowledge of the caller.
-18254011 0The first expands to the second, so there is no technical difference. Nowadays, the first is the recommended one, while the second is the underlying implementation.
-13248261 0 How to make inapp purchase using MKStoreKit 4.x receipt secure from being modified?I have been storing inapp purchase receipt string in nsuserdefaults or a custom plist .This string used to determine the version of the app as full or limited.But how to make it secure.If any person modify this string by modifying the plist the app will change to full version rite.Then i came to know about keychains,but i am not able to understand how it works..is it a separate place where the string is saved or is it encrypting the string and saving it in plist..If anybody knows how to save inapp receipts from mkstorekit using keychains please share it here.. and also the keychains concept
-39987143 0Final Update: I was able to fix this by using psqlodbc_09_03_0400. For whatever reason, other versions kept throwing error.
-38548372 0 Reformatting a csv file, script is confused by ' %." 'I'm using bash on cygwin.
I have to take a .csv file that is a subset of a much larger set of settings and shuffle the new csv settings (same keys, different values) into the 1000-plus-line original, making a new .json file.
I have put together a script to automate this. The first step in the process is to "clean up" the csv file by extracting lines that start with "mme " and "sms ". Everything else is to pass through cleanly to the "clean" .csv file.
This routine is as follows:
# clean up the settings, throwing out mme and sms entries cat extract.csv | while read -r LINE; do if [[ $LINE == "mme "* ]] then printf "$LINE\n" >> mme_settings.csv elif [[ $LINE == "sms "* ]] then printf "$LINE\n" >> sms_settings.csv else printf "$LINE\n" >> extract_clean.csv fi done
My problem is that this thing stubs its toe on the following string at the end of one entry: 100%."
When it's done with the line, it simply elides the %."
and the new-line marker following it, and smears the two lines together:
... 100next.entry.keyname...
I would love to reach in and simply manually delimit the %
sign, but it's not a realistic option for my use case. Clearly I'm missing something. My suspicion is that I am in some wise abusing cat
or read
in the first line.
If there is some place I should have looked to find the answer before bugging you all, by all means point me in that direction and I'll sod off.
-29217158 0 how to list all directories for group has access to in unix/linuxIs there a way to list all directories for group has access to in unix/linux. Or a way to list all groups along with directories for which the group has access.
-22636707 0No, it's not possible. But you can add your feature request on JetBrains tracker: http://youtrack.jetbrains.com/issues/WI#newissue=yes
-34643822 0 Accessing Metacritic API and/or ScrapingDoes anybody know where documentation for the Metacritic api is/if it still works. There used to be a Metacritic API at https://market.mashape.com/byroredux/metacritic-v2#get-user-details which disappeared today.
Otherwise I'm trying to scrape the site myself but keeping getting a blocked by a 429 Slow down. I got data like 3 times this hour and haven't been able to get anymore in the last 20 minutes which is making testing difficult and application possibly useless. Please let me know if there's anything else I can be doing to scape I don't know about.
-32780669 0From developer.android.com:
Subclasses should override this method and verify that the given fragment is a valid type to be attached to this activity. The default implementation returns true for apps built for android:targetSdkVersion older than KITKAT. For later versions, it will throw an exception.
Basically on TargetSDK <= KITKAT, you should make sure the fragment name isValidFragment
passes is a correct one.
If you come from the webforms and code-behind world is common to you that an HTML element calls a script in the code, but actually what asp.net webforms does is an http call to the script on the server. If you had an updatepanel
, asp.net webforms would have done the same call via ajax.
That's the reason why in asp.net webforms the elements have the preceding asp:
on their branded html
tags. That way asp.net can convert their branded elements to real HTML elements.
The only way to execute the code of an action
from an HTML element on-click event in asp.net MVC is by calling the URL that gets to that method. Either via ajax or by a request from the browser, an http request needs to be done.
With javascript you can listen when an element's on-click event is fired and then do some logic. If you're using jquery you can use the $.ajax()
or $.get()
methods to make a call to your action URL.
Premise: We've got a table with 5 fields. 2 fields are always unique.
What would be a good way to fulfill this:
if (count_of_result == 3) { add up the 3 rows from the same table. unique values get added up & the non-unique values are assumed to be same for all the 3 rows. the query result should show 1 row, with the values added up. } else {
display all the results of the query as usual.
}
Thank you.
-15897174 0This thread seems to describe the solution:
object Test { def apply( int : Int ) = new Test( int ) } class Test @deprecated( "Don't construct directly - use companion constructor", "09/04/13" ) ( int : Int ) { override def toString() = "Test: %d".format( int ) }
Can't try it right now though.
-28931183 0Further messing around yielded the answer: xargs
instead of a subshell:
echo \'foo bar\' \'baz quux\' | xargs /usr/bin/defaults write com.apple.systemuiserver menuExtras -array
-35168470 0 Windows Virtual Machine getting connection refused to port 9090 webpack dev server I have a Meteor + Webpack application I'm working on, but I can't get a Windows VM (Win10, IE11, from modern.ie running inside VirtualBox) to access the Webpack dev server assets on port 9090, while the Meteor assets on the same host but on port 3000 work fine for whatever reason. The app is running and being accessed at {host}:3000 but this one bundled JS file is on on the same host at port 9090 and the VM is unable to fetch it.
-14158048 0According to the TODO file on CPAN, this capability is not currently supported, but the developers see it as a valuable addition:
- Enhancements:
- Marking of unreachable code - commandline tool and gui.
The cover
script mentions promising options: -add_uncoverable_point
and -delete_uncoverable_point
.
I was trying to help someone solve a problem the other day and I came across an interesting issue I couldn't solve.
Imagine two sheets. One containing HYPERLINKS created by HYPERLINK function in Google Sheets, such as this sheet. Source Sheet
Then you have another sheet that uses importRange to import these URL's, like this sheet. import Sheet
The URLs import correctly, with correct link and link text. But no matter what I tried, in the import sheet, I couldn't extract the link value.
I tried to do this via formulas and via scripting. I'm guessing the URL must be some sort of object but I cannot seem to read or split it. Whatever efforts I've tried have always returned the link text, EG Google, Yahoo and not the URL itself.
-22001333 0If you just want to enable/disable input:
$("#your_input").attr('disabled','disabled'); // disable $("#your_input").removeAttr('disabled');//enable
Example:
http://jsfiddle.net/juvian/R95qu
-36711688 0You second thread is not appending content to the file, which was written by first thread. Instead it is overwriting content written by first thread.
So you are getting output only from second thread.
Change your code
from
FileWriter f = new FileWriter("C:\\Users\\Desktop\\sample.txt");
to
FileWriter f = new FileWriter("C:\\Users\\Desktop\\sample.txt",true);
Refer to java documentation page on FileWriter
public FileWriter(File file, boolean append) throws IOException
-20174142 0 keytool error :Alias Constructs a FileWriter object given a File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.
I get an error when I write this command in the console
C:\Program Files\Java\jdk1.7.0_21\bin> keytool-list-alias-andoiddebugkey keystore C:\Users\AbuHamza\android\debug.keystore-storepass android-keypass androi. d
error
keytool error: java.lang.Exception: Alias <andoiddebugkey> does not exist
-4423417 0 C++, function that loads text ignores last few lines with only some of the .txt files I'm following theForger's Win API tutorial to load text files into an edit control. Sometimes the entire file is loaded correctly and sometimes the last part of it is left out, where 'part' is in one case 2 and a half lines and in another 10 lines o_O Here's how the files look:
(I'm a new user so it's not letting me post more than one hyperlink, so here's the gallery where the screenshots are: http://nancy.imgur.com/all/ and I'm referring to the order in which they appear in the gallery)
2.5 lines left out: second (reading stops at the cursor after the 'F')
10 lines left out: fourth (also stops at the cursor after the f)
Read completely: first and third
I tried using fstreams instead, and the same stuff was left out (I also couldn't get the new line characters to show in the edit control =( ). Any idea what could be wrong?
I couldn't link to theForger's tutorial so here's the function:
BOOL LoadTextFileToEdit(HWND hEdit, LPCTSTR pszFileName) { HANDLE hFile; BOOL bSuccess = FALSE; hFile = CreateFile(pszFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); if(hFile != INVALID_HANDLE_VALUE) { DWORD dwFileSize; dwFileSize = GetFileSize(hFile, NULL); if(dwFileSize != 0xFFFFFFFF) { LPSTR pszFileText; pszFileText = GlobalAlloc(GPTR, dwFileSize + 1); if(pszFileText != NULL) { DWORD dwRead; if(ReadFile(hFile, pszFileText, dwFileSize, &dwRead, NULL)) { pszFileText[dwFileSize] = 0; // Add null terminator if(SetWindowText(hEdit, pszFileText)) bSuccess = TRUE; // It worked! } GlobalFree(pszFileText); } } CloseHandle(hFile); } return bSuccess; }
-2844661 0 Checkout the newest revision of the restored backup into a working copy. do an svn export of and old working copy and simply copy all files/folders onto the previously checkout working copy. Than do an svn add if needed and commit. This should summ all changes.
-9025780 0Getting co-ordinates for a polygon would require GIS files and a GIS software like MapInfo to read.
My advice would be visit this site;
http://bbs.keyhole.com/ubb/ubbthreads.php?ubb=showthreaded&Number=332073
Download the KML file which has the district boundaries of UK counties and then use it in either google earth or fusion tables.
Finding out what your using these for may help get a better answer...
-10255619 0I think you're looking for System.Collections.Generic.Queue instead of System.Collections.Queue.
Change
open System.Collections
to
open System.Collections.Generic
-28699427 0 Printing the value of an R variable in Latex I am writing .Rnw file in RStudio. At one point, I store (but do not print) the value of the number of rows (nR) of a data frame (df), using the following command:
<<results = hide, echo=FALSE>>= nR = nrow(sbGeneal) nC = ncol(sbGeneal) @
Late, in the .Rnw file, I would like to use the nR variable and print it. An equivalent syntax in .Rmd (markdown) would be:
`r nrow(sbGeneal)`
Is there such a possibility in Latex? Thanks!
-21699836 0Yet another solution:
<lable>Set1</lable> <input type="checkbox" name="set_199[]" value="Apple" /> <input type="checkbox" name="set_199[]" value="Mango" /> <input type="checkbox" name="set_199[]" value="Grape" /> <input type="button" value="check" class="js-submit">
Js:
$(".js-submit").on("click", function(){ var a = $("input[type='checkbox']:checked"); var values = {}; a.each(function(){ var value = $(this).val(); var name = $(this).attr("name"); if(!values[name]) values[name] = []; values[name].push(value) }); console.log(values) });
-33965928 0 The button elements are not sibling elements.
You need to select the parent element's sibling elements.
$(document).on('click', '.btn-group button', function (e) { $(this).addClass('active').parent().siblings().find('button').removeClass('active'); });
However, the proper way to do this is to use the attribute data-toggle="buttons"
.
In doing so, you don't need to write any custom JS. For more information, see this old answer of mine explaining how it works.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"/> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> <div class="btn-group btn-group-justified" data-toggle="buttons" role="group" aria-label="..."> <label class="btn btn-default"> <input type="radio" name="options" />Low Cost/Effeciency </label> <label class="btn btn-default"> <input type="radio" name="options" />Average </label> <label class="btn btn-default"> <input type="radio" name="options" />High Cost/Effeciency </label> </div>
I have listview with Title, image and date. I want to sort that list on the basis of date field and then display in html5 page. I used jquery and html5 on this.
$j('#task_summary_list').empty(); if (response.totalSize > 0) { $j.each(response.records, function(i, record) { var imgName; switch (record.Priority) { case "High": imgName = "images/prio_high24.png"; break; case "Low": imgName = "images/prio_low24.png"; break; default: imgName = "images/prio_normal24.png"; } // create new list entry for record to the listview $j('<li></li>') .attr('id', record.Id) .hide() .append( '<a href="#">' + '<img src="' + imgName + '" alt="High" class="ui-li-icon">' + '<h1>' + record.Subject + '</h1>' + '<p>' + '<strong>' + record.ActivityDate + '</strong>' + '</p>' + '</a>') .click(function(e) { e.preventDefault(); console.log("Under onSuccessTasks " + record.Id); showTaskDetails(record); }) .appendTo('#task_summary_list') .show(); }); } else { $j('<li class="norecord">No records to display</li>').appendTo('#task_summary_list'); } $j('#task_summary_list').listview('refresh'); $j.mobile.hidePageLoadingMsg();
Any help is appreciated. Thanks in avance.
-30296654 0 OnClientClick not working in IE11The onClientClick event is not getting fired in IE11 browser, however the same piece of code is working perfectly fine in IE8,9 and 10 browsers. Is there any extra piece of code that i need to add in there.
<table width="100%"> <tr> <td align="center"> <asp:Button runat="server" ID="btnFTCancel" Text="Cancel" OnClientClick="return confirmCancel();" OnClick="btnUpdate_Click" ClientIDMode="Static"/> </td> <td align="center"> <asp:Button runat="server" ID="btnApprove" Text="Approve" Enabled="false" OnClientClick="return confirmApprove();" OnClick="btnUpdate_Click"/> </td> </tr> </table> <script type="text/javascript"> function confirmCancel() { var returnvalue; $("#btnFTCancel").css("cursor", "text"); returnvalue = confirm('Transactions generated for this request ID will be cancelled. Do you wish to continue ?'); return returnvalue; } function confirmApprove() { var returnvalue; returnvalue = confirm('Transactions generated for this request ID will be sent to FCS. Do you wish to continue ?'); return returnvalue; } function setBtnCursor() { $("input[type='submit']").css('cursor', 'pointer'); $("input[type='submit'][disabled='disabled']").css('cursor', 'default'); } </script>
TIA,
Amit
-9081449 0According to here:
Operators on the same line have equal precedence. When operators of equal precedence appear in the same expression, a rule must govern which is evaluated first. All binary operators except for the assignment operators are evaluated from left to right; assignment operators are evaluated right to left.
So yes.
-1808882 0Not too sure if this will help, but perhaps try getting the the modules first and then the types from there.
Assembly a = Assembly.Load(brockenAssembly); Module[] mList = a.GetModules(); for (int i = 0; i < mList.length; i++) { Module m = a.GetModules()[i]; Type[] tList = m.GetTypes(); }
Hope fully you could get the list of types available in one of the modules.
-16967562 0Yould could just popup a dialog with the progress in there but if you do not want to block the user from using the map then another alternative would be to overlay another layout on top of the map fragment and put the progress bar in that layout
-17161110 0 How to turn on table name autocomplete feature in Toad?I'm using Toad version 11.0.0.116. I'm not getting default tablename options when I start typing table. How to turn the autocomplete feature on??
-13292537 0Assuming you have any View
instance in your activity, you can use View.postDelayed() to post runnable with a given delay. In this runnable you can call Activity.finish(). You should also use View.removeCallbacks() to remove your callback in onDestroy()
, to avoid your callback being called after user already navigated back from your activity.
Using AsyncTask
just to count some time is just an overkill (unless you want to use AsyncTask
to actually do some useful, background work). The Looper
and Handler
classes provide everything you need to execute any code on UI thread after a given delay. The View
methods mentioned above are just convenience methods exposing the Handler
functionality.
The upload_to
argument can be a function, as described in the documentation:
def group_based_upload_to(instance, filename): return "image/group/{}/{}".format(instance.group.id, filename) class Group_Photo(models.Model): group = models.ForeignKey(Group) photo = models.ImageField(upload_to=group_based_upload_to)
The function takes two arguments - instance of the model to which the file is being attached and the original name of the file. It has to return a relative path under witch the file will be saved. It will be appended to the path defined in the MEDIA_ROOT
setting.
The example above uses directories based on group's numeric id. You can obviously use other fields, for example to use the slug (if it has one) just replace instance.group.id
with instance.group.slug
.
You should also measure the length of the stick in the first part of the for loop, otherwise you'll be measuring it with every iteration. And you can also make the k
bit even more compact:
for (var i = k = 0, j = mystick.length; i < j; i++) { if (mystick[i] == 'huge') { k++; } }
-39233034 0 Well, I dont have a direct approach. But this hack should help you get what you want..
// Start the Browser As Process to start in Private mode Process browserProcess = new Process(); browserProcess.StartInfo.FileName = "iexplore.exe"; browserProcess.StartInfo.Arguments = "-private"; browserProcess.StartInfo.WindowStyle = ProcessWindowStyle.Maximized; // Start browser browserProcess.Start(); // Get Process (Browser) Handle Int64 browserHandle = browserProcess.Handle.ToInt64(); // Create a new Browser Instance & Assign the browser created as process using the window Handle BrowserWindow browserFormHandle = new BrowserWindow(); browserFormHandle.SearchProperties.Add(BrowserWindow.PropertyNames.WindowHandle, browserFormHandle.ToString()); browserFormHandle.NavigateToUrl(new Uri("http://www.google.com"));
-37114802 0 You need to set the value of $scope.objectData[key]
to an object before you can add more keys to it.
$scope.objectData[key] = {}; $scope.objectData[key]['digits'] = 'foo';
-29356529 0 If you don't need it to undock and float then you can use a HeaderedContentControl.
When you want to add the close button you can template the header presenter to include a button.
-18965510 0The way to do this is in the controller for the news_article in def show
you write redirect_to @news_article.attach.url
in news_article paperclip store url in attach (I call it this in model) and the .url helper is what makes the browser go there :)
-5223322 0 Domain Name with unicode PitfallsAccording to yahoo and stackoverflow.com they advise having a static content site that you don't assign cookies to. http://developer.yahoo.com/performance/rules.html#cookie_free http://sstatic.net
Based of the desire for a static only domain name I though it would be cool to have the domain name made up of unicode characters. From what I understand pitfalls of unicode characters include: difficulty to type and automatic punycode conversation due to the paypal.com innocent.
For example if I wanted to link my stylesheet.
<link rel=stylesheet href=☺.com/s.css> .... <script src=☺.com/s.js></script>
Considering I only plan to link to static content, are there are issues or pitfalls?
Do all browsers natively support unicode -> punycode conversation? It has been unclear to me if internet explorer less than 7 supports punycode. Also would IE display a notice if you are simply linking to server content in unicode format.
Bonus: Also is there any place to find a list of legal url unicode url characters? Supposedly some characters aren't permitted?! Or would a url containing non permitted characters simply be translated to punycode immediately therefore not effecting my situation?
-40751775 0Not sure how this should be done in query syntax, but here is the method syntax version:
this.Data = data .Split(new[] { "@" }, StringSplitOptions.RemoveEmptyEntries) .Select(table => table.Split(new[] { "^^" }, StringSplitOptions.RemoveEmptyEntries) .Select(row => row.Split(';')) .ToArray()) .ToArray();
In query synax :
this.Data = ( from table in data.Split(new[] { "@" }, StringSplitOptions.RemoveEmptyEntries) select ( from row in table.Split(new[] { "^^" }, StringSplitOptions.RemoveEmptyEntries) select row.Split(';') ).ToArray() ).ToArray();
-5817142 0 Exactly, UML class diagrams are just a notation that you could (and should) differently depending on the sofware development phase you are in. You can start with only classes, attributes and associations, then refine the diagram to add types information for the attributes, then navigation, class methods, qualifiers for associations ... until you get a complete class diagram ready for the implementation phase
Note that you could even iterate to the point in which you remove associations and replace them by attributes of complex types to have a class diagram even more similar to the final implementation. It's up to you how to use class diagrams in each phase.
-40989587 0If you use a val, you're not allowed to assign it a new value, so in your code example above, if you switch the third line with
val fa2 = fa.:+(ra)
then fa can be a val.
-33589252 0I see only two good choices:
unlimitedStorage
permission and store the urls in WebSQL database (it's also the fastest). Despite the general concern that it may be deprecated in Chrome after W3C stopped developing the specification in favor of IndexedDB I don't think it'll happen any time soon because all the other available storage options are either [much] slower or less functional.Use is_page
to detect your front-end login and registration pages:
<?php if ( ! is_user_logged_in() && ! ( is_page( 'register' ) || is_page( 'login' ) ) ) { echo '<div>Some stuff here</div>'; // your code } ?>
-32933716 0 NPE is because of the below reason
try { desktop.browse(uri); } catch(IOException ioe) { System.out.println("The system cannot find the " + uri + " file specified"); //ioe.printStackTrace(); }
you are initializing desktop in DesktopDemo constructor but onLaunchBrowser() is a static method so desktop object is not instantiated!
-5645072 0Hope U R USING PHP
choose your own separator like
$glue=®(alt 0174) CONCAT_WS($glue,str1,$str2)
-27037271 0 One quick solution is to change your html structure and move sidebar as first child of div wih id #tekst
:
body { background: #98c8d7; width: 1000px; margin: auto; font-family: "Trebuchet ms", Verdana, sans-serif; } #header { background: #fff url(banner.jpg) no-repeat; margin: 10px 0 10px 0; padding: 8em 2em 1em 2em; text-align: center; border-radius: 15px; opacity: 0.8; border: 1px dotted #000 } /*Dette formaterer menuen */ ul { list-style-type: none; margin: 0; padding: 0; overflow: hidden; } li { float: left; } a:link, a:visited { display: block; width: 312.5px; font-weight: bold; color: #000; background-color: #51a7c2; text-align: center; padding: 4px; text-decoration: none; text-transform: uppercase; border: 1px solid #91cfca; opacity: 0.8; } a:hover, a:active { background-color: #98c8d7; } #content { background: #b4cdd9; color: #000; padding: 1em 1em 1em 1em; top right bottom left } #tekst { background: #98c8d7; color: #000; opacity: 0.8; margin: 5px 0 5px 0; padding: 0.5em 1em 1em 1em; text-align: left; } #sidebar { background: #b4cdd9; color: #000; width: 320px; position: relative; float: right; margin: 5px 0 5px 0; padding: 0.5em 1em 1em 1em; text-align: left; border-style: outset; border-width: 3px; border-color: black; } a { color: #0060B6; text-decoration: none; } a:hover { color: #00A0C6; text-decoration: none; cursor: pointer; }
<body> <!-- Denne div indeholder dit content, altså din brødtekst --> <div id="content"> <!--Header. Indeholder banner --> <div id="header"></div> <!-- Menu --> <ul> <li><a href="forside.html">Forside</a> </li> <li><a href="priser.html">Priser</a> </li> <li><a href="kontakt.html">Kontakt</a> </li> </ul> <!-- Her kommer din brødtekst så --> <div id="tekst"> <div id="sidebar"> <!-- move it here --> <h3>Leon Laksø</h3> <p>Så-og-så-mange år i tjeneste, certificeret bla bla, alt muligt andet shit her. Måske et billede hvor du ser venlig ud?</p> <p>Mail link kunne være her?</p> </div> <h1>Overskrift 1</h1> <p>Her kan du skrive, hvad du tilbuder, hvorfor, hvorledes, til hvem og anden info</p> <!-- Overskrift to. Der er flere former for overskrifter. H1 betegner en bestemt slags, H2 en mindre slags osv. Du kan godt bruge H1 flere gange --> <h2>Underoverskrift 1</h2> <p>Her kan du måske skrive lidt om dig selv og dine kvalifikationer?</p> </div> </div> </body>
OK, I'm not going to try a fix your code. I'm just going to create constraints that I would use to achieve your layout. I'll put the thought process in comments.
First get a nice vertical layout going...
// I'm just using standard padding to make it easier to read. // Also, I'd avoid the variable padding stuff. Just set it to a fixed value. // i.e. ==padding not (>=0, <=padding). That's confusing to read and ambiguous. @"V:|-[titleLabel]-[ratingBubbleView]-[descriptionLabel]-|"
Then go through layer by layer adding horizontal constraints...
// constraint the trailing edge too. You never know if you'll get a stupidly // long title. You want to stop it colliding with the end of the screen. // use >= here. The label will try to take it's intrinsic content size // i.e. the smallest size to fit the text. Until it can't and then it will // break it's content size to keep your >= constraint. @"|-[titleLabel]->=20-|" // when adding this you need the option "NSLayoutFormatAlignAllBottom". @"|-[ratingBubbleView]-[dateLabel]->=20-|" @"|-[descriptionLabel]-|"
Try not to "over constrain" your view. In your code you are constraining the same views with multiple constraints (like descriptionLabel to the bottom of the superview).
Once they're defined they don't need to be defined again.
Again, with the padding. Just use padding
rather than >=padding
. Does >=20 mean 20, 21.5, or 320? The inequality is ambiguous when laying out.
Also, In my constraints I have used the layout option to constrain the vertical axis of the date label to the rating view. i.e. "Stay in line vertically with the rating view". Instead of constraining against the title label and stuff... This means I only need to define the position of that line of UI once.
-2846831 0An alternative to filtering would be to maintain the list of selected users. In setSelected(true)
you could add a user to the list and use setSelected(false)
to remove it.
class User { List<User> selectedUsers = new ArrayList<User>(0); void setSelected(boolean isSelected) { if ( isSelected) { selectedUsers.add(user.getId()); } else { int idx = selectedUsers.indexOf( this ); if ( idx >= 0 ) selectedUsers.remove( idx ); } } }
This aproach requires an implemented equals method. BTW your snippet adds the userId (Int?) to the list of type User.
-18205592 0When you do writeObject, the objevt you write needs to be Serializable. Try to change the signature of your copy
-method to
public static Object copy(Serializable oldObj)
The error message will be clearer.
-2894704 0The DataContext
on your usercontrol isn't set. Specify a Name
for it (I usually call mine "ThisControl") and modify the TextBox's binding to Text="{Binding ElementName=ThisControl, Path=TitleValue, Mode=TwoWay}"
. You can also set the DataContext
explicitly, but I believe this is the preferred way.
It seems like the default DataContext should be "this", but by default, it's nothing.
[edit] You may also want to add , UpdateSourceTrigger=PropertyChanged
to your binding, as by default TextBoxes' Text binding only updates when focus is lost.
I have one UIViewController
without NIB file. Now i have one my customized UIView
. I want to make UIViewController
's view inherit from my customized UIView
, is it possible ? I know that if I have XIB file than I can make Custom Class from there but without XIB can it be done?
Thanks in Advance
-2038527 0int* memory = NULL; memory = malloc(sizeof(int)); if (memory != NULL) { memory=10; free(memory); }
This will crash. You're setting the pointer to memory location 10 and then asking the system to release the memory. It's extremely unlikely that you previously allocated some memory that happeneds to start at 0x10, even in the crazy world of virutal address spaces. Furthermore, IF malloc failed, no memory has been allocated, so you do not need to free it.
int* memory = NULL; memory = malloc(sizeof(int)); if (memory != NULL) { memory=10; } free(memory);
This is also a bug. If malloc fails, then you are setting the pointer to 10 and freeing that memory. (as before.) If malloc succeeds, then you're immediately freeing the memory, which means it was pointless to allocate it! Now, I imagine this is just example code simplified to get the point across, and that this isn't present in your real program? :)
-16783675 0 Running Continumm StandaloneI have downloaded apache continuum.
After that i unpacked and i typed continuun console.
It´s started fine... but when i put localhost:8080/continuum in the browser the console show this error: What´s happend?
jvm 1 | org.apache.jasper.JasperException: PWC6345: There is an error in invo king javac. A full JDK (not just JRE) is required jvm 1 | at org.apache.jasper.compiler.DefaultErrorHandler.jspError(Defau ltErrorHandler.java:92) jvm 1 | at org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDisp atcher.java:378) jvm 1 | at org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDisp atcher.java:119) jvm 1 | at org.apache.jasper.compiler.Jsr199JavaCompiler.compile(Jsr199J avaCompiler.java:208) jvm 1 | at org.apache.jasper.compiler.Compiler.generateClass(Compiler.ja va:384) jvm 1 | at org.apache.jasper.compiler.Compiler.compile(Compiler.java:453 ) jvm 1 | at org.apache.jasper.JspCompilationContext.compile(JspCompilatio nContext.java:625) jvm 1 | at org.apache.jasper.servlet.JspServletWrapper.service(JspServle tWrapper.java:374) jvm 1 | at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServle t.java:492) jvm 1 | at org.apache.jasper.servlet.JspServlet.service(JspServlet.java: 378) jvm 1 | at javax.servlet.http.HttpServlet.service(HttpServlet.java:848) jvm 1 | at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder. java:648) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHand ler.java:455) jvm 1 | at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedH andler.java:137) jvm 1 | at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHan dler.java:577) jvm 1 | at org.eclipse.jetty.server.session.SessionHandler.doHandle(Sess ionHandler.java:231) jvm 1 | at org.eclipse.jetty.server.handler.ContextHandler.doHandle(Cont extHandler.java:1072) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandl er.java:382) jvm 1 | at org.eclipse.jetty.server.session.SessionHandler.doScope(Sessi onHandler.java:193) jvm 1 | at org.eclipse.jetty.server.handler.ContextHandler.doScope(Conte xtHandler.java:1006) jvm 1 | at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedH andler.java:135) jvm 1 | at org.eclipse.jetty.server.Dispatcher.forward(Dispatcher.java:2 76) jvm 1 | at org.eclipse.jetty.server.Dispatcher.forward(Dispatcher.java:1 03) jvm 1 | at org.eclipse.jetty.servlet.DefaultServlet.doGet(DefaultServlet .java:566) jvm 1 | at javax.servlet.http.HttpServlet.service(HttpServlet.java:735) jvm 1 | at javax.servlet.http.HttpServlet.service(HttpServlet.java:848) jvm 1 | at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder. java:648) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter (ServletHandler.java:1336) jvm 1 | at org.apache.struts2.dispatcher.ng.filter.StrutsExecuteFilter.d oFilter(StrutsExecuteFilter.java:85) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter (ServletHandler.java:1307) jvm 1 | at com.opensymphony.sitemesh.webapp.SiteMeshFilter.obtainContent (SiteMeshFilter.java:129) jvm 1 | at com.opensymphony.sitemesh.webapp.SiteMeshFilter.doFilter(Site MeshFilter.java:77) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter (ServletHandler.java:1307) jvm 1 | at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareFilter.d oFilter(StrutsPrepareFilter.java:82) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter (ServletHandler.java:1307) jvm 1 | at org.springframework.web.filter.CharacterEncodingFilter.doFilt erInternal(CharacterEncodingFilter.java:96) jvm 1 | at org.springframework.web.filter.OncePerRequestFilter.doFilter( OncePerRequestFilter.java:76) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter (ServletHandler.java:1307) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHand ler.java:453) jvm 1 | at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedH andler.java:137) jvm 1 | at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHan dler.java:559) jvm 1 | at org.eclipse.jetty.server.session.SessionHandler.doHandle(Sess ionHandler.java:231) jvm 1 | at org.eclipse.jetty.server.handler.ContextHandler.doHandle(Cont extHandler.java:1072) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandl er.java:382) jvm 1 | at org.eclipse.jetty.server.session.SessionHandler.doScope(Sessi onHandler.java:193) jvm 1 | at org.eclipse.jetty.server.handler.ContextHandler.doScope(Conte xtHandler.java:1006) jvm 1 | at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedH andler.java:135) jvm 1 | at org.eclipse.jetty.server.handler.ContextHandlerCollection.han dle(ContextHandlerCollection.java:255) jvm 1 | at org.eclipse.jetty.server.handler.HandlerCollection.handle(Han dlerCollection.java:154) jvm 1 | at org.eclipse.jetty.server.handler.HandlerWrapper.handle(Handle rWrapper.java:116) jvm 1 | at org.eclipse.jetty.server.Server.handle(Server.java:365) jvm 1 | at org.eclipse.jetty.server.AbstractHttpConnection.handleRequest (AbstractHttpConnection.java:485) jvm 1 | at org.eclipse.jetty.server.AbstractHttpConnection.headerComplet e(AbstractHttpConnection.java:926) jvm 1 | at org.eclipse.jetty.server.AbstractHttpConnection$RequestHandle r.headerComplete(AbstractHttpConnection.java:988) jvm 1 | at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:6 35) jvm 1 | at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.j ava:235) jvm 1 | at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttp Connection.java:82) jvm 1 | at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectC hannelEndPoint.java:627) jvm 1 | at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectCh annelEndPoint.java:51) jvm 1 | at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedT hreadPool.java:608) jvm 1 | at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedTh readPool.java:543) jvm 1 | at java.lang.Thread.run(Unknown Source) jvm 1 | 2013-05-27 23:52:11.265:WARN:oejs.ErrorPageErrorHandler:EXCEPTION jvm 1 | org.apache.jasper.JasperException: PWC6345: There is an error in invo king javac. A full JDK (not just JRE) is required jvm 1 | at org.apache.jasper.compiler.DefaultErrorHandler.jspError(Defau ltErrorHandler.java:92) jvm 1 | at org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDisp atcher.java:378) jvm 1 | at org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDisp atcher.java:119) jvm 1 | at org.apache.jasper.compiler.Jsr199JavaCompiler.compile(Jsr199J avaCompiler.java:208) jvm 1 | at org.apache.jasper.compiler.Compiler.generateClass(Compiler.ja va:384) jvm 1 | at org.apache.jasper.compiler.Compiler.compile(Compiler.java:453 ) jvm 1 | at org.apache.jasper.JspCompilationContext.compile(JspCompilatio nContext.java:625) jvm 1 | at org.apache.jasper.servlet.JspServletWrapper.service(JspServle tWrapper.java:374) jvm 1 | at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServle t.java:492) jvm 1 | at org.apache.jasper.servlet.JspServlet.service(JspServlet.java: 378) jvm 1 | at javax.servlet.http.HttpServlet.service(HttpServlet.java:848) jvm 1 | at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder. java:648) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHand ler.java:455) jvm 1 | at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedH andler.java:137) jvm 1 | at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHan dler.java:577) jvm 1 | at org.eclipse.jetty.server.session.SessionHandler.doHandle(Sess ionHandler.java:231) jvm 1 | at org.eclipse.jetty.server.handler.ContextHandler.doHandle(Cont extHandler.java:1072) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandl er.java:382) jvm 1 | at org.eclipse.jetty.server.session.SessionHandler.doScope(Sessi onHandler.java:193) jvm 1 | at org.eclipse.jetty.server.handler.ContextHandler.doScope(Conte xtHandler.java:1006) jvm 1 | at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedH andler.java:135) jvm 1 | at org.eclipse.jetty.server.Dispatcher.forward(Dispatcher.java:2 76) jvm 1 | at org.eclipse.jetty.server.Dispatcher.error(Dispatcher.java:112 ) jvm 1 | at org.eclipse.jetty.servlet.ErrorPageErrorHandler.handle(ErrorP ageErrorHandler.java:136) jvm 1 | at org.eclipse.jetty.server.Response.sendError(Response.java:348 ) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHand ler.java:538) jvm 1 | at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedH andler.java:137) jvm 1 | at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHan dler.java:559) jvm 1 | at org.eclipse.jetty.server.session.SessionHandler.doHandle(Sess ionHandler.java:231) jvm 1 | at org.eclipse.jetty.server.handler.ContextHandler.doHandle(Cont extHandler.java:1072) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandl er.java:382) jvm 1 | at org.eclipse.jetty.server.session.SessionHandler.doScope(Sessi onHandler.java:193) jvm 1 | at org.eclipse.jetty.server.handler.ContextHandler.doScope(Conte xtHandler.java:1006) jvm 1 | at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedH andler.java:135) jvm 1 | at org.eclipse.jetty.server.handler.ContextHandlerCollection.han dle(ContextHandlerCollection.java:255) jvm 1 | at org.eclipse.jetty.server.handler.HandlerCollection.handle(Han dlerCollection.java:154) jvm 1 | at org.eclipse.jetty.server.handler.HandlerWrapper.handle(Handle rWrapper.java:116) jvm 1 | at org.eclipse.jetty.server.Server.handle(Server.java:365) jvm 1 | at org.eclipse.jetty.server.AbstractHttpConnection.handleRequest (AbstractHttpConnection.java:485) jvm 1 | at org.eclipse.jetty.server.AbstractHttpConnection.headerComplet e(AbstractHttpConnection.java:926) jvm 1 | at org.eclipse.jetty.server.AbstractHttpConnection$RequestHandle r.headerComplete(AbstractHttpConnection.java:988) jvm 1 | at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:6 35) jvm 1 | at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.j ava:235) jvm 1 | at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttp Connection.java:82) jvm 1 | at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectC hannelEndPoint.java:627) jvm 1 | at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectCh annelEndPoint.java:51) jvm 1 | at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedT hreadPool.java:608) jvm 1 | at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedTh readPool.java:543) jvm 1 | at java.lang.Thread.run(Unknown Source)
-9043173 0 MIniMagick::Image.write() saves files with varying permissions I am writing a little photo gallery with Rails 3.0.11 and MiniMagick.
def JadeImage.rescale path,new_path,max_height=150 image = MiniMagick::Image.open(path) image.adaptive_resize(self.resize(image[:height],max_height))if image[:height] > max_height image.write(new_path) end
I am using this to save two resized images from the same photo. One of the files gets saved with 644 permissions and all is right in the world. The other always get saved as 600 and as such can't be displayed in the webpage.
For now, after saving them, I run a little utility to set everything in that directory as 644 so it works now.
Is there any reason why this would occur?
-40918033 0I ended up using a BindingTargetVisitor
which covers the use cases that I need.
Note that this solution works for our specific use case but might be too limited for your use case, depending on the type of bindings and injections that you use.
public class InjectionPointExtractor extends DefaultBindingTargetVisitor<Object, InjectionPoint> { private final Predicate<TypeLiteral<?>> filter; public InjectionPointExtractor(Predicate<TypeLiteral<?>> filter) { this.filter = filter; } @Override public InjectionPoint visit(UntargettedBinding<?> untargettedBinding) { return getInjectionPointForKey(untargettedBinding.getKey()); } @Override public InjectionPoint visit(LinkedKeyBinding<?> linkedKeyBinding) { return getInjectionPointForKey(linkedKeyBinding.getLinkedKey()); } @Override public InjectionPoint visit(ProviderKeyBinding<?> providerKeyBinding) { return getInjectionPointForKey(providerKeyBinding.getProviderKey()); } private InjectionPoint getInjectionPointForKey(Key<?> key) { if (filter.test(key.getTypeLiteral())) { return InjectionPoint.forConstructorOf(key.getTypeLiteral()); } return null; } }
We use the filter
to filter only on classes defined in our packages. This gets the job done in a nice and clean fashion.
If you don't use @Inject
constructors but instead use Guice to set fields directly, you could use TypeListener
I'm from a design background. My programming knowledge is zero. After learning XHTML and CSS I want to learn and get good command on JavaScript, jQuery, etc. How should I start?
This will be my first attempt to programming. I can use and edit readymade available jQuery/JavaScript scripts, but I can't make my own and can't do high level editing in readymade scripts.
Is there any other post on Stack Overflow, any link of start-up tutorial, or any book for my needs?
Edit 1:
This book will work best for me, "DOM Scripting: Web Design with JavaScript and the Document Object Model".
Edit 2:
Will my design background and knowledge of XHTML CSS help me to learn JavaScript quickly?
and is this correct? If I learn only jQuery then I will not be able to work with other JavaScript framework like MooTools, Prototype, etc. But if I learn core JavaScript then I would be able to work with all JavaScript frameworks and anything in JavaScript.
-9919278 0 SQL multiple replaceI want to read the company table and take out all possible suffixes from the name. Here's what I have so far:
declare @badStrings table (item varchar(50)) INSERT INTO @badStrings(item) SELECT 'company' UNION ALL SELECT 'co.' UNION ALL SELECT 'incorporated' UNION ALL SELECT 'inc.' UNION ALL SELECT 'llc' UNION ALL SELECT 'llp' UNION ALL SELECT 'ltd' select id, (companyname = Replace(name, item, '') FROM @badStrings) from companies where name != ''
-36775266 0 to handle ALL worksheet, place this in ThisWorkbook code pane
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range) If Not Intersect(Target, Sh.Columns(13)) Is Nothing Then MsgBox "Help Help" End If End Sub
or
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range) If Target.Column = 13 Then MsgBox "Help Help" End If End Sub
Otherwise place the following in the code pane of the Sheet(s) you want to "handle" only
Private Sub Worksheet_Change(ByVal Target As Range) If Target.Column = 13 Then MsgBox "Help Help" End If End Sub
-9569438 0 This is an example of code that works for me. It performs these operations:
If the current element is a number, then this element and the next element (the city) is stored on an ArrayList.
import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.*; public class split{ private List<String> newline = new ArrayList<String>(); public split(){ String myString = "Graaf Karel De Goedelaan 1 8500 Kortrijk"; String array[] = myString.split("\\s+"); for(int z = 0;z<arr.length;z++){ int sizestr = array[z].length(); if(sizestr==4){/* if the generic string has 4 characters */ String expression = "[0-9]*"; CharSequence inputStr = array[z]; Pattern pattern = Pattern.compile(expression); Matcher matcher = pattern.matcher(inputStr); if(matcher.matches()){/* then if the string has 4 numbers, we have the postal code" */ newline.add(array[z]); /* now we add the postal code and the next element to an array list" */ newline.add(array[z+1]); } } } Iterator<String> itr = newline.iterator(); while (itr.hasNext()) { String element = itr.next(); System.out.println(element); /* prints "8500" and "Kortrijk" */ } } public static void main(String args[]){ split s = new split(); } }
For further info about the check of the string, take a look to this page, and, for the ArrayList Iterator, see this.
I hope this can help to solve your problem.
-26775709 0 Fastest way to join multiple MVC projects into a single oneWe have about 4 different MVC projects, in separate Solutions, with their own Controllers, Models and Views.
We need to join all these projects into a single Project (Solution). The new project will have an entry point (Home Page), from which you can go to any of the existing projects.
We will navigate from one project to another (one section to another - after integration) using simple navigation links.
Is Areas
a good solution for this approach?
I read this post but i don't understand what the solution from there is.
-26038374 0You can make change in below css
.content { margin-top:50px;//added position:absolute;//changed clear: both; width:100px; height:50px; background:#D52100; } .click_menu{ width:100px; height:50px; float:left; color:#191919; text-align:center; position: absolute;// added z-index: 100;//added }
-38934847 0 The line of code num1, num2 = num2, (num1 + num2)
is assigning two variables at once. num1
gets the old value of num2
, while num2
gets the new value (num1 + num2)
.
Having multiple assignments on a single line of code allows you to do both operations without needing to use a temporary variable. For example, this won't work:
num1 = num2 num2 = (num1 + num2)
because num1
has been overwritten with a new value before the addition step, so num2
will be assigned the wrong value. The one-line version is equivalent to:
temp = (num1 + num2) num1 = num2 num2 = temp
For reference, this is called parallel assignment or sometimes multiple assignment.
-17099774 0Try this:
String strEvents = new JSONArray(apiResponse).getJSONObject(0).toString(); String strVenues= new JSONArray(apiResponse).getJSONObject(1).toString(); jsonArray = new JSONObject(strEvents).getJSONArray("fql_result_set"); jsonVenues = new JSONObject(strVenues).getJSONArray("fql_result_set");
-4159189 0 Rails Bundler on windows refuses to install hpricot (even on manual gem install get Error: no such file to load -- hpricot) Upgraded to rails 3, and using Bundler for gems, in a mixed platform development group. I am on Windows. When I run Bundle Install it completes succesfully but will not install hpricot. The hpricot line is:
gem "hpricot", "0.8.3", :platform => :mswin
also tried
gem "hpricot", :platform => :mswin
Both complete fine but when I try to do a "bundle show hpricot" I get:
Could not find gem 'hpricot' in the current bundle.
If I do a run a rails console and try "require 'hpricot'" I get:
LoadError: no such file to load -- hpricot
I have manually installed hpricot as well, and still get the above error. This worked fine before moving to rails 3.
-28226538 0Try setting your text to "My name is John" outside of the button click, perhaps in a Form.Init
handler, then removing txtOutPut.Text = "My name is John"
from btnClickMe_Click1
What's happening here is the button click is changing the text first to "My name is John", then changing it to "and this is my first VB program" and the change happens too quickly for it to be visible.
-36968760 0As mentioned by Turnip there is -webkit filter for that. However it is more convenient to use SVG:
<svg> <pattern id="mypattern" patternUnits="userSpaceOnUse" width="750" height="800"> <image width="750" height="800" xlink:href="https://placekitten.com/g/100/100"></image> </pattern> <text x="0" y="80" class="fa fa-5x" style="fill:url(#mypattern);"></text> </svg>
You just need to include icon character in SVG
-37612974 0I've spent two days fighting with it. Adding "*" namespace to xPath solved the issue for me (my input file did not have any).
return <label>{fn:doc(fn:concat($collection, '/', $child))//*:testResult/text()}</label>
-2107911 0 Safe class imports from JAR Files Consider a scenario that a java program imports the classes from jar files. If the same class resides in two or more jar files there could be a problem.
In such scenarios what is the class that imported by the program? Is it the class with the older timestamp??
What are the practices we can follow to avoid such complications.
Edit : This is an example. I have 2 jar files my1.jar and my2.jar. Both the files contain com.mycompany.CrazyWriter
-18630530 0You can use ValueProvider.GetValue("HasEditPermission").RawValue
to access the value.
Controller:
public class BController : Controller { public ActionResult Index() { ViewBag.HasEditPermission = Boolean.Parse( ValueProvider.GetValue("HasEditPermission").RawValue.ToString()); return PartialView(); } }
View:
... @if (ViewBag.HasEditPermission) { // some html rendering } ...
Update:
Request.Params
gets a combined collection of QueryString, Form, Cookies, and ServerVariables items not RouteValues.
In
@Html.Action("Index", "BController", new { HasEditPermission = true })
HasEditPermission
is a RouteValue
.
you can also try something like this
ViewContext.RouteData.Values["HasEditPermission"]
in your View and subsequent child action views as well..
-39643679 0var orders = JSON.parse($('#orderData')); console.log(orders[0].value);
-8984472 0 Indeed, it's possible. I suggest you to use a @property/@synthesize object on the receiver UIViewController (the one with the UIWebView) that it's initialized/filled from the calling viewController with the search string that you want to use.
-3092562 0A couple of ways:
In your web.config on the customErrors mode set the redirectMode
to ResponseRewrite
- this removes the 302 redirect from the server to the error page - this also has the happy coincidence that uses can easily see what the original page they requested was, and can retry with an F5 if that's likely to resolve the issue.
If you are hooking into the ApplicationError event, make sure that rather than redirecting to your error pages you use Server.Transfer
instead.
I have the following in one of my web.configs:
<customErrors mode="On" defaultRedirect="ErrorHandler.aspx" redirectMode="ResponseRewrite">
Then in my ErrorHandler page I check for the last error from the server, and configure those:
var serverError = Server.GetLastError(); var error = serverError as HttpException; int errorCode; string errorMessage; if (null != error) { errorCode = error.GetHttpCode(); errorMessage = error.GetHtmlErrorMessage(); } else { errorCode = 404; errorMessage = "Page not found"; } Response.StatusCode = errorCode; Response.StatusDescription = errorMessage;
Obviously you may want to do additional processing - for example before I do all this I'm comparing the original request with my Redirects database to check for moved content/vanity urls, and only falling back to this if I couldn't find a suitable redirect.
-22708706 0 Time taken to reconnect to a BLE peripheral after restored by State RestorationHas anyone used State Restoration to reconnect to a peripheral? if so do you have any feel for the how long it took to reconnect?
It's abit of a difficult question, as it is not easy to tell when to start timing from.
It should be when the iDevice gets in range of its peripheral for which the connection request has been issued.
-7061264 0 Access a flash object from jQueryI am using swfobject 2 to dynamically embed my flash... let's call my object "swfContent"
I have tried to use $('swfContent') and $("#swfContent") to access my swf object, but no luck.
Thanks!
-9369161 0The Visual Studio Visualizer's architecture requires all Visualizers to be Modal windows, so the answer is No. Your best bet is to copy/paste the text into a diff tool.
-36704302 0The error 0000052D
is a system error code. Specifically, it means:
ERROR_PASSWORD_RESTRICTION
1325 (0x52D)
Unable to update the password. The value provided for the new password does not meet the length, complexity, or history requirements of the domain.
The problem would seem to be that the account you're enabling has a password-policy applied to it, whereby enabling it that password-policy would not be met.
I would first figure out what the password policy is for the account, then set the password to something that meets that policy criteria before flipping the bit to enable it.
If, however, you really want the user to be able to login with no password then the password should be set to null. But I'm not sure under what circumstances that would be desirable.
-9729428 0I think you're on the right track. Instead of grouping FlightTimes by FlightType, try building FlightTimeResults and grouping those by FlightType instead:
var results = from ft in schedules.FlightTimes group new FlightTimeResult { FlightTimeData = ft, FlagRedeye = ft.DepartureTime.Hour >= 0 && ft.DepartureTime.Hour < 6 } by ft.FlightType.ToString() into groupedFlights select groupedFlights;
-25581405 0 I'm not quite sure whether I have completely understood what the problem here is! But you can simply use a Dictionary
to hold string values of each 45-degree slice and check it against the word user drags.
Dictionary<int, string> dict = new Dictionary<int, string>(); dict.Add(1, "Eraser"); dict.Add(2, "Glue"); dict.Add(3, "Pen"); dict.Add(4, "Scissors"); dict.Add(5, "Stapler"); dict.Add(6, "Sharpener"); dict.Add(7, "Ruler"); dict.Add(8, "Pencil");
And change your code to:
double degree = rng.Next(360, 720); double resultAngle = degree - 360; int num = (int)Math.Ceiling(resultAngle / 45);
Then, the name of the element the pointer is currently pointing at would be:
string currentElem = dict[num];
-13061209 0 Stopping a CSS animation but letting its current iteration finish I have the following HTML:
<div class="rotate"></div>
And the following CSS:
@-webkit-keyframes rotate { to { -webkit-transform: rotate(360deg); } } .rotate { width: 100px; height: 100px; background: red; -webkit-animation-name: rotate; -webkit-animation-duration: 5s; -webkit-animation-iteration-count: infinite; -webkit-animation-timing-function: linear; }
I want to know if there is a way (using JavaScript) to stop the animation but let it finish its current iteration (preferably by changing one or a few CSS properties). I have tried setting -webkit-animation-name
to have a blank value but that causes the element to jump back to its original position in a jarring fashion. I have also tried setting -webkit-animation-iteration-count
to 1
but that does the same thing.
When you specify the DestinationFolder for the Copy task, it takes all items from the SourceFiles collection and copies them to the DestinationFolder. This is expected, as there is no way for the Copy task to figure out what part of each item's path needs to be replaced with the DestinationFolder in order to keep the tree structure. For example, if your SourceDir collection is defined like this:
<ItemGroup> <SourceDir Include="$(Source)\**\*" /> <SourceDir Include="E:\ExternalDependencies\**\*" /> <SourceDir Include="\\sharedlibraries\gdiplus\*.h" /> </ItemGroup>
What would you expect the destination folder tree look like?
To preserve the tree, you need to do identity transformation and generate one destination item for each item in the SourceFiles collection. Here's an example:
<Copy SourceFiles="@(Compile)" DestinationFiles="@(Compile->'$(DropPath)%(Identity)')" />
The Copy task will take the each item in the SourceFiles collection, and will transform its path by replacing the part before the ** in the source item specification with $(DropPath).
One could argue that the DestinationFolder property should have been written as a shortcut to the following transformation:
<Copy SourceFiles="@(Compile)" DestinationFiles="@(Compile->'$(DestinationFolder)%(Identity)')" />
Alas, that would prevent the deep copy to flat folder scenario that you are trying to avoid, but other people might using in their build process.
-3500096 0 Lost transaction with JPA unique constraint?I have a field with an unique constraint:
@Column(unique=true) private String uriTitle;
When I try to save two entities with the same value, I get an exception - but another exception than I exected:
java.lang.IllegalStateException: <|Exception Description: No transaction is currently active at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.rollback(EntityTransactionImpl.java:122) at com.example.persistence.TransactionFilter.doFilter(TransactionFilter.java:35)
The questionable filter method looks like this:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { EntityManager entityManager = ThreadLocalEntityManager.get(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); try { chain.doFilter(request, response); transaction.commit(); } catch (Throwable t) { transaction.rollback(); // line 35, mentioned in the exception throw new RuntimeException(t); } finally { entityManager.close(); ThreadLocalEntityManager.reset(); } }
... and the ThreadLocalEntityManager like this:
public class ThreadLocalEntityManager { private static EntityManagerFactory entityManagerFactory = null; private static final ThreadLocal<EntityManager> entityManager = new ThreadLocal<EntityManager>() { @Override protected EntityManager initialValue() { return entityManagerFactory.createEntityManager(); } }; private ThreadLocalEntityManager() {} public static synchronized void init(String persistenceUnit) { requireNotNull(persistenceUnit); requireState(entityManagerFactory == null, "'init' can be called only " + "once."); entityManagerFactory = Persistence.createEntityManagerFactory(persistenceUnit); } public static EntityManager get() { requireState(entityManagerFactory != null, "Call 'init' before calling " + "'get'"); return entityManager.get(); } public static void reset() { entityManager.remove(); } }
I wrapped the call to save
with try ...catch
to handle the unique constraint violation, but that doesn't work:
try { ThreadLocalEntityManager.get().persist(article); // article is constrained } catch(Throwable t) { t.printStackTrace(); }
Any idea why there is no transaction? What is the correct way to handle a unique constraint violation?
-36343298 0 semantic-ui search following link when pressing 'enter'I want to allow users to navigate the search tool only with the keyboard which means that they navigate search results with arrows and, when they press 'enter', it follows the item's link.
How could this be done ?
Here is an example from the docs, with a GitHub search box
-9378795 0You can work with fancybox Ajax or Iframe and load your HTML page into box.
-9100372 0 Javascript: obj.fn() vs x=obj.fn;x()Take a look at this snippet:
var obj = { fn: function () {return this;} }; var x = obj.fn; obj.fn(); // returns obj x(); // returns window (in the browser)
I'm curious why obj.fn()
is different from x=obj.fn; x()
. Is there a special case for attribute lookup directly followed by a function call within a single expression - or there is some more complex magic going on under the hood (like with descriptor protocol in Python) ?
You cannot programatically fill in login information, that is against the Facebook terms and conditions. You can, however, authenticate as an application as opposed to a user. Use the following method:
Make a GET request to: https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&client_id=CLIENT_ID&client_secret=CLIENT_SECRET Facebook returns: access_token=SOME_TOKEN Use this token as your access token and it should allow you to access the group. I have tested this with my application and can confirm it works. You request the wall information via the request: https://graph.facebook.com/GROUP_ID/feed?access_token=SOME_TOKEN
This will not pop up any login screens as you are not required to be logged in to view a public group. Ensure your privacy settings are public for the group as well.
-34589096 0 Instagram Media Endpoint PagingI'm currently looking at reading out posts and related json data from a given number of Instagram users using the following URL:
https://www.instagram.com//media/
This will only bring back the latest 20 posts. I have done some hunting around and I am unable to see how to form the url to bring back the next 20 results. I've seen some places that have suggested using max_timestamp, but I can't see how to make this work.
For various reasons I do not wish to use the standard Instagram API.
-15831268 0There is a "cacheDirectory" in your "data/package_name" directory.
If you want to store something in that cache memory,
File cacheDir = new File(this.getCacheDir(), "temp"); if (!cacheDir.exists()) cacheDir.mkdir();
where this is context.
-18177680 0try this
Dim HttpReq As HttpWebRequest = DirectCast(WebRequest.Create("http://...."), HttpWebRequest) Using HttpResponse As HttpWebResponse = DirectCast(HttpReq.GetResponse(), HttpWebResponse) Using Reader As New BinaryReader(HttpResponse.GetResponseStream()) Dim RdByte As Byte() = Reader.ReadBytes(1 * 1024 * 1024 * 10) Using FStream As New FileStream("FileName.extension", FileMode.Create) FStream.Write(RdByte, 0, RdByte.Length) End Using End Using End Using
-8334422 0 I would personally use an interface as suggested, but in case you didn't have access to who is calling you (such as third party .dll) then you can accept an argument of type object:
/// <summary> /// Draw any type of object if the objec type is supported. /// Circles, Squares, etc. /// </summary> /// <param name="objectToDraw"></param> public void Draw(object objectToDraw) { // get the type of object string type = objectToDraw.GetType().ToString(); switch(type) { case "Circle": // cast the objectToDraw as a Circle Circle circle = objectToDraw as Circle; // if the cast was successful if (circle != null) { // draw the circle circle.Draw(); } // required break; case "Square": // cast the object as a square Square square = objectToDraw as Square; // if the square exists if (square != null) { // draw the square square.Draw(); } // required break; default: // raise an error throw new Exception("Object Type Not Supported in Draw method"); } }
-4005032 0 If you're augmenting rows that already exist you'll want to use an UPDATE statement.
-22092822 0There is no official release of OpenCV for system without OS. OpenCV library is available for Windows, linux, mac, Android and Ios operating system.
Here you can find a link which explain the challenges of having OpenCV running on microcontrollers
-39467508 0try this solution:
quest.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(ActionEvent e) { JButton b = (JButton)e.getSource(); for(Component c : yourPanel.getComponents()){ if(c instanceof JButton && !c.equals(b)){ c.setEnabled(false); } } } });
-21394141 0 Database table structure for storing SSO information for FB or Google+ I have a web application that I would like to add single sign on capability using user's Facebook or Google+/Google App account.
I have a USERS
table that stores users login information. All users are required to have a record in this table no matter if they signed up using FB or Google+.
I am trying to figure out the information that I need to store in the database in order to link USERS
table records to FB or Google information.
Facebook documentation states:
the app should store the token in a database along with the
user_id
to identify it.
So should I create a table called SSO_LOOKUP
with following columns:
USER
tableNote that @
is already a 1-char infix operator to concat lists.
JsonObject jObj = JsonObject.Parse(json); JsonArray jArr = jObj.GetNamedArray("records"); for (int i = 0; i < jArr.Count; i++) { JsonObject innerObj = jArr.GetObjectAt(i); mData[i] = new Data(innerObj .GetNamedString("countryName"), innerObj .GetNamedString("countryId"), innerObj.GetNamedString("callPrefix"), innerObj .GetNamedString("isoCode")); }
Visual studio show syntax error: the best overloaded method for jArr.GetObjectAt(uint) has an invalid argument
-25614224 1 How to print a variable from a derived class?I know there are similar questions on this topics but none of them seem to apply to my case Why would the following code print None and not True? Thanks
class A(object): flag = None @classmethod def set_flag(cls): cls.flag = True class B(A): @classmethod def print_super_flag(cls): print cls.__bases__[0].flag # This prints None print super(B, cls).flag # This also if __name__ == "__main__": b = B() b.set_flag() b.print_super_flag()
-19984966 0 No - there are separate endpoints for web services.
Look in ADFS under Services / Endpoints. Note that not all are enabled by default.
I blogged about this - ADFS : WCF web service
-23362695 0 Trouble about assign char pointer in CI have a simple C program about assign char pointer and malloc like this
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char str[] = "0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789"; char* str1 = malloc(sizeof(char*)); strcpy(str1, str); printf("%s\n\n", str1); char* str2 = malloc(sizeof(char*)); str2 = str1; printf("%s\n", str2); return 0; }
And the result is:
0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 01!
So why the str2 just gets 25 characters from str1? And where is the "!" (in the end of str2) come from?
Could you help me? Thanks!
-7650906 0Option 1:
class Example { public: Example( std::string str, const std::complex<float>& v ): m_str( std::move(str) ), m_v( v ) { } /* other methods */ private: std::string m_str; std::complex<float> m_v; };
This has pretty good performance and is easy to code. The one place it falls a little short of the optimum is when you bind an lvalue to str
. In this case you execute both a copy construction and a move construction. The optimum is only a copy construction. Note though that a move construction for a std::string
should be very fast. So I would start with this.
However if you really need to pull the last cycles out of this for performance you can do:
Option 2:
class Example { public: Example( const std::string& str, const std::complex<float>& v ): m_str( str ), m_v( v ) { } Example( std::string&& str, const std::complex<float>& v ): m_str( std::move(str) ), m_v( v ) { } /* other methods */ private: std::string m_str; std::complex<float> m_v; };
The main disadvantage of this option is having to overload/replicate the constructor logic. Indeed this formula will become unrealistic if you have more than one or two parameters that you need to overload between const&
and &&
.
I'm trying to use the method
Windows.System.UserProfile.UserInformation.GetPrincipalNameAsync()
to get Windows Live ID, but it returns an empty string, anyone knows why?
Thanks a lot.
-38896485 0I guess the problem is that CD V:\
is not enough. If you are on C:\ CD V:\
won't move the scope to V:. To achieve this you have to add the /d
switch to the CD
command:
... cd /d V:\ ...
-30187285 0 Values of background-size
property should be like Xpx Ypx
. Try change Your last line to this:
t.getBody().style.backgroundSize = newWidth+"px "+newHeight+"px";
-18876763 0 Android Calendar RRULE - Events not being created in the calendar I would appreciate any possible help from people that have already experienced the same problem.
Thanks.
EDIT: Problem found: https://code.google.com/p/android/issues/detail?id=60589
-13016625 0Assuming your xml code is saved to "test.xml":
from xml.dom.minidom import parse dom1 = parse("test.xml") for node in dom1.getElementsByTagName('t'): print node.childNodes[0].nodeValue
This should print the inner values of all tags "".
-34390723 0From the documentation for dispatchKeyEvent
:
Return
true
if the KeyboardFocusManager should take no further action with regard to the KeyEvent;false
otherwise
Also you can directly consume the event in your dispatchKeyEvent
implementation when no further processing of the event is required.
e.consume();
Suggestion of @MadProgrammer is also important. Using of global event processing possibilities is the last choice.
-30962416 0If you don't want to use RestClient::Resource
, you can include basic auth in a request like this:
RestClient::Request.execute method: :get, url: url, user: 'username', password: 'secret'
The trick is not to use the RestClient.get
(or .post
, .put
etc.) methods since all options you pass in there are used as headers.
I just did a quick writeup on this over here: https://www.krautcomputing.com/blog/2015/06/21/how-to-use-basic-authentication-with-the-ruby-rest-client-gem/
-11361072 0 input not submitting data to mysqlI'm making a very simple groups(like vb forum groups). I've coded all of it, after getting some errors and fixing it now it's showing the page without errors.
The problem now is the data ISN'T being inserted to mysql. When putting the input into forms and then pressing create it goes to "?update=update" and echo's the success message, but doesn't submit to mysql.
Code:
<? if(!$update) { ?> <form action="make_group.php?update=update" method="post"> Group name: <br /> <input name="title" type="text" size="30" /> <br /> Group picture: <br /> <input name="picture" type="text" size="30" /> <br /> Group desc: <br /> <textarea name="desc" cols=30 rows=10 wrap=physical></textarea> <br /> <input type="submit" value="Create" /> <? } elseif($update==update) { $username = $_SESSION[usr_name]; $action = "made a group"; $title = clean($_POST[title]); $desc = clean($_POST[desc]); $pictures = clean($_POST[pictures]); $updateemail = mysql_query("insert into usr_groups(username, title, desc, picture) values('$username', '$title', '$desc', '$picture')"); $result = @mysql_query($qry2); echo("Your group has been created"); } ?>
Above page code
<? session_start(); include("config.php"); $ip = $_SERVER['REMOTE_ADDR']; $sqlcontent = mysql_query("select * from usr_config"); $content = mysql_fetch_array($sqlcontent); if(!isset($_SESSION[usr_name]) || empty($_SESSION[usr_name]) || !isset($_SESSION[usr_level]) || empty($_SESSION[usr_level])) { session_destroy(); session_unset(); die(' <tr> <td><meta http-equiv="REFRESH" content="0;url=/index.php"></HEAD></td> </tr> <tr> <td></td> </tr> </table> </div> </body>'); } include("func.php"); $update = clean($_GET[update]); $getprof = mysql_query("select * from usr_users where username = '$_SESSION[usr_name]'"); $prof = mysql_fetch_array($getprof); ?>
-12528564 0 friend function returning reference to private data member I have two questions about the following code.
class cls{ int vi; public: cls(int v=37) { vi=v; } friend int& f(cls); }; int& f(cls c) { return c.vi; } int main(){ const cls d(15); f(d)=8; cout<<f(d); return 0; }
Initially load part of data in your list view. You have to use concept of Handler
. onclick event you have to send message to handler inside handler you have to write the logic to load your full data and call notifydataSetChanged
method
have a look on the sample code below. Initially user is able to see some part of list. If user cvlicks on any list item then list user is able to see the whole list view. It is similar to as that you are expecting.
import java.util.ArrayList; import android.app.ListActivity; import android.content.res.Configuration; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; public class MyListView extends ListActivity { ArrayList<String> pens = new ArrayList<String>(); ArrayAdapter arrayAdapter = null; private static final byte UPDATE_LIST = 100; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); pens.add("MONT Blanc"); pens.add("Gucci"); pens.add("Parker"); arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, pens); setListAdapter(arrayAdapter); getListView().setTextFilterEnabled(true); ListView lv = getListView(); lv.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub System.out.println("..Item is clicked.."); Message msg = new Message(); msg.what = UPDATE_LIST; updateListHandler.sendMessage(msg); } }); // System.out.println("....g1..."+PhoneNumberUtils.isGlobalPhoneNumber("+912012185234")); // System.out.println("....g2..."+PhoneNumberUtils.isGlobalPhoneNumber("120121852f4")); } @Override public void onConfigurationChanged(Configuration newConfig) { // TODO Auto-generated method stub super.onConfigurationChanged(newConfig); System.out.println("...11configuration is changed..."); } void addMoreDataToList() { pens.add("item1"); pens.add("item2"); pens.add("item3"); } protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); Object o = this.getListAdapter().getItem(position); String pen = o.toString(); Toast.makeText(this, id + "You have chosen the pen: " + " " + pen, Toast.LENGTH_LONG).show(); } private Handler updateListHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case UPDATE_LIST: addMoreDataToList(); arrayAdapter.notifyDataSetChanged(); break; } ; }; }; }
Thanks Deepak
-18350059 0A web proxy is not normally defined by just a port, but is usually a full host name. Charles is very likely installed on localhost. Therefore the following adjustment may work for you:
@agent ||= Mechanize.new do |agent| agent.set_proxy("localhost", 8888) end
-410752 0 See Inversion of Control and Dependency Injection with Castle Windsor Container - Part II at DotNetSlackers. It shows how to pass an array of the same service interface to an object.
-2150387 0Probably both elements are linked by a ID..
-6229054 0 Unable to load webview in tab viewI have no idea why my webview is unable to load in my tabhost/tabwidget. For the tabhost/tabwidget, I am using the tutorial that was provided by Android Developer. Also, in my logcat, the warning seems to be at the tab1Activity.java, pointing the warning to "wv.loadDataWithBaseURL("http://lovetherings.livejournal.com/961.html", myString, "text/html", "UTF-8", "about:blank"); "
Below are my codes. Can anyone help me? Thanks so much in advance! :D
Here is my main.xml
<LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="5dp"> <TabWidget android:id="@android:id/tabs" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <FrameLayout android:id="@android:id/tabcontent" android:layout_width="fill_parent" android:layout_height="fill_parent" > <WebView android:id="@+id/webview" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </FrameLayout> </LinearLayout>
My main activity
public class HelloTabWidgetMain extends TabActivity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Resources res = getResources(); // Resource object to get Drawables TabHost tabHost = getTabHost(); // The activity TabHost TabHost.TabSpec spec; // Resusable TabSpec for each tab Intent intent; // Reusable Intent for each tab // Create an Intent to launch an Activity for the tab (to be reused) intent = new Intent().setClass(this, ArtistsActivity.class); // Initialize a TabSpec for each tab and add it to the TabHost spec = tabHost.newTabSpec("tab1").setIndicator("tab1", res.getDrawable(R.drawable.ic_tab_tab1)) .setContent(intent); tabHost.addTab(spec); // Do the same for the other tabs intent = new Intent().setClass(this, tab2Activity.class); spec = tabHost.newTabSpec("tab2").setIndicator("tab2", res.getDrawable(R.drawable.ic_tab_tab2)) .setContent(intent); tabHost.addTab(spec); intent = new Intent().setClass(this, tab3Activity.class); spec = tabHost.newTabSpec("tab3").setIndicator("tab3", res.getDrawable(R.drawable.ic_tab_tab3)) .setContent(intent); tabHost.addTab(spec); tabHost.setCurrentTab(0); }
}
And my tab activity (where I would want my webview contents to be displayed)
public class tab1Activity extends Activity{ WebView wv; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); try { URL url = new URL("http://lovetherings.livejournal.com/961.html"); // Make the connection URLConnection conn = url.openConnection(); BufferedReader reader = new BufferedReader( new InputStreamReader(conn.getInputStream())); // Read the contents line by line (assume it is text), // storing it all into one string String content =""; String line = reader.readLine(); while (line != null) { content += line + "\n"; line = reader.readLine(); } reader.close(); String myString = content.substring(content.indexOf("<newcollection>")); int start = myString.indexOf("<newcollection>"); if (start < 0) { Log.d(this.toString(), "collection start tag not found"); } else { int end = myString.indexOf("</newcollection>", start) + 8; if (end < 0) { Log.d(this.toString(), "collection end tag not found"); } else { myString = "<html><body>" + myString.substring(start, end) + "</body></html>"; } WebView wv = (WebView)findViewById(R.id.webview); wv.loadDataWithBaseURL("http://lovetherings.livejournal.com/961.html", myString, "text/html", "UTF-8", "about:blank"); } } catch (Exception ex) { ex.printStackTrace(); // Display the string in txt_content //TextView txtContent = (TextView)findViewById(R.id.txt_content); //txtContent.setText(myString); } }
}
Please help me! Thanks in advance!
-21102386 0 What is the term for a "stack" of sub-pages that displays on one page?I'm building a Wordpress site and am looking for a plugin for managing a very specific kind of content / design scheme. Unfortunately, I do not know what this is called, and am looking for pointers on terminology so I can ease my search.
Imagine a very long page (as tall as 7 screens, for instance).
This is divided into 7 sub-pages, each the size of one screen, stacked one on top of the other.
Each sub-page has its own background and content.
The viewer can scroll from top to bottom of the "parent" page, and get 7 distinct background / content groupings for 7 different products.
What is this kind of content called? "Frames", isn't right, and "divs" is too general. I would appreciate any guidance on this that can be provided. Thanks!
I don't have any live demos of this sort of content, but will post them as I find them.
-4440306 0First try updating your statistics.
Then, look into your indexing, and make sure you have only what you need. Additional indexes can most definitely slow down inserts.
Then, try rebuilding the indexes.
Without knowing the schema, query, or amount of data, it is hard to say more than that.
-25039982 0This is implementation defined as per the draft C99 standard section 6.3.2.3
Pointers which says:
Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type, the behavior is undefined. The result need not be in the range of values of any integer type.
gcc
documents there implementation here:
The result of converting a pointer to an integer or vice versa (C90 6.3.4, C99 and C11 6.3.2.3).
A cast from pointer to integer discards most-significant bits if the pointer representation is larger than the integer type, sign-extends1 if the pointer representation is smaller than the integer type, otherwise the bits are unchanged.
A cast from integer to pointer discards most-significant bits if the pointer representation is smaller than the integer type, extends according to the signedness of the integer type if the pointer representation is larger than the integer type, otherwise the bits are unchanged.
Alternatively you could use uinitptr_t assuming stdint.h
is available which is an unsigned integer that can hold a pointer value:
#include <stdint.h> #include <inttypes.h> uintptr_t ip = &i ; printf("0x%016" PRIxPTR "\n", ip ) ;
-4176241 0 I call Alert.Show in a function and want to get the result from there (Flex, ActionScript) I'm using the Alert.show in a function and I want to get the user answer from there. So how can I achieve this. The problem is the function that call Alert.show will return a true or false value depend the user answer. but It seem that in Alert.show it only allow to pass in a CloseHandler for this. that is a new function. and since that I can get the user answer from where it is call to return the user answer.
Really thanks for help Yuan
-6119230 0 You need 10,000 digits of e on a windows boxLet's say you have a bare-bones Windows XP machine, nothing added. This means no compilers, no MS Office, etc. Oh, and no network connection.
You want 10,000 digits of e (e is the base of the natural logarithm). You have one hour. How could you do it?
Disclaimer: There are probably multiple "good" answers, but I have one particular idea in mind.
-25907377 0 error in spring-security.xml for constructor arg errori m using spring security for my login page.in this in the database user password is stored using sha-password encoder.now i want to use the same in my spring-security.xml.i tried this
<beans:bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.ShaPasswordEncoder"> <constructor-arg value="256"/> </beans:bean> <authentication-manager> <authentication-provider> <password-encoder ref="passwordEncoder"/> <jdbc-user-service data-source-ref="dataSource" users-by-username-query= "select email,password, 'true' as enabled from user_login where email=? limit 1" authorities-by-username-query= "select email, role from user_roles where email =? " /> </authentication-provider> </authentication-manager> </beans:beans>
i m getting error at
cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'constructor-arg'. - Security namespace does not support decoration of element [constructor-arg] - Configuration problem: Security namespace does not support decoration of element.
anyone help me for this,please.
-19253826 0I found the solution. If load following HTML in UIWebView in iOS 7 (not Safari), the onblur
event doesn't work:
<html> <head> <meta name='viewport' content='initial-scale=1.0,maximum-scale=10.0'/> </head> <body> <table style='height:80%'><tr><td> <select onblur="alert('blur')" > <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> </td></tr></table> </body> </html>
The important components: viewport, table with some height defined, select inside this table. If remove table OR remove height style OR remove viewport, then onblur
works.
I can't explain this effect, but I just remove table height style and it works. Maybe it helps somebody.
-16496963 0HKL9
(string) is greater than HKL15
, beacause they are compared as strings. One way to deal with your problem is to define a column function that returns only the numeric part of the invoice number.
If all your invoice numbers start with HKL
, then you can use:
SELECT MAX(CAST(SUBSTRING(invoice_number, 4, length(invoice_number)-3) AS UNSIGNED)) FROM table
It takes the invoice_number excluding the 3 first characters, converts to int, and selects max from it.
-24092656 0You can either use, but $('title') will fail in IE8
document.title="new title";
or
$('title').html('new title');
or
$(document).attr('title','new title');
-34736811 0 You can use the LIKE ability of mysql:
SELECT * FROM company WHERE country LIKE '%$country%';
-16013020 0 How use Video.js player via Flash fallback without CDN swf file IE8 or older automatically uses flash fallback player but the player is hosted in CDN.
I want to use hosted video-js.swf
file in my server instead of CDN contents. Because CDN swf file is not secured.
The Video.js version is 3.2, that is currently you can download from http://videojs.com/.
I tried this code but it does not work.
Can someone help me with the solution?
Thanks!
-9359946 0 Call user defined function on click in jQueryI have made a jQuery function and want to call it on click event. My code is like below:
<script type="text/javascript"> (function($){ $.fn.my_function = function(options){ return this.each(function(){ alert("Hello"); }); }; })(jQuery); $(document).ready(function(){ $('#submit_buttom').my_function(); }); </script>
Please help.
Thanks
-15148571 0You need to open the applications screen, in it to scroll right until you get to the widgets section. from there pull the widget that you want and add it to the desired desktop.
-8043579 0 How to strip path while archiving with TARI have a file that contain list of files I want to archive with tar. Let's call it mylist.txt
It contains:
/path1/path2/file1.txt /path1/path2/file3.txt ... /path1/path2/file10.txt
What I want to do is to archive this file into a tarball but excluding /path1/path2/
. Currently by doing this:
tar -cvf allfiles.tar -T mylist.txt
preserves the path after unarchiving.
I tried this but won't work too:
tar -cvf -C /path1/path2 allfiles.tar -T mylist.txt
It archives all the files in /path1/path2
even those which are not in mylist.txt
Is there a way to do it?
-38588513 0 Best practice to deploy wso2 esb policiesI have setup an ESB cluster using jdbc connections to ms sql databases for local and remotely mounted config and gov registries. 1x mgt and 2xworker
Our .car file contains some ws-security policy artifacts which go to config. When I deploy to mgt it deploys OK. I have SVN dep sync setup to the cluster and when it picks up the .car it starts to deploy on the worker but fails when loading the policy files into conf. It is trying to duplicate the policy in the shared conf and fails - of course that is right but; how should I deploy these 'shared' artifacts when a .car file is distributed by svn? I need to be able to control the deploy properly. The only way I can see is via the dev studio which is terrible for our change management practice.
Thanks for you help.
-2998841 0Use the application identifier in the .config file to differentiate between your applications. It's in the Membership Provider section. applicationName="MyApplication"
I have a reference to a MySQL.Data 5.2.3 assembly in a data layer, great. I currently I have small console app inteh same solution referencing JUST THIS data layer which connects just fine. I then created a unit test project (also in the same solution) and reference that same data layer project, and from that I get:
Test method LTTests.WrapperTest.LoginTest threw exception: System.IO.FileLoadException: Could not load file or assembly 'MySql.Data, Version=5.2.3.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d' or one of its dependencies. Strong name signature could not be verified. The assembly may have been tampered with, or it was delay signed but not fully signed with the correct private key. (Exception from HRESULT: 0x80131045).
So I'm trying to understand...I can do this for a console exe and it works but not a unit test? This makes me nervous to build on something apparently flawed, but I'm at a loss for what to do next. I'm lost, I've been re-adding various things looking for what the deal is and I have no clue.
The exception is from the data layer and not from the test (per the stack) so it's like the test is calling the layer's method (duh) and the data layer is puking but not for the console?
Thanks.
-35030093 0Is it crucial for it to have to equal -3.40282306e+38 for your algorithm to work? If nor try an inequality instead of equals. Equlaity works on floating point numbers if they are perfect integers such as 0,for numbers like youre using an inequality maybe the answer. Wont something like
-22829563 0(-3.40282306e+38-smallnumber) fix your problem?-You have to set small number to somthing in the context of your problem which I dont know what it is.
1. Can we get all field names of a collection with their data types?
mongodb collections are schema-less, which means each document
(row in relation database) can have different fields. When you find a document
from a collection
, you could get its fields names and data types.
2. Can we generate a random value of that data type in mongo shell?
3. how to set the values dynamically to store random data.
mongo shell use JavaScript, you may write a js script and run it with mongo the_js_file.js
. So you could generate a random value in the js script.
It's useful to have a look at the mongo JavaScript API documentation and the mongo shell JavaScript Method Reference.
Other script language such as Python can also do that. mongodb has their APIs too.
-11568153 0The useful difference between
data Point = Point Float Float data Radius = Radius Float data Shape = Circle Point Radius
and
data LengthQty = Radius Float | Length Float | Width Float
is the way Haskell's type system handles them. Haskell has a powerful type system, which makes sure that a function is passed data that it can handle. The reason you'd write a definition like LengthQuantity
is if you had a function which could take either a Radius
, Length
, or Width
, which your function can't do.
If you did have a function which could take a Radius
, Length
, or Width
, I'd write your types like this:
data Point = Point Float Float data Radius = Radius Float data Shape = Circle Point Radius data LengthQty = R Radius | L Length | W Width
This way, functions that can only take a Radius
benefit from that more specific type checking.
I have implemented a pull to refresh and now trying to add a timestamp showing "Last updated: "time""(4:50/tuesday etc). I have implemented a method for the same:
public void setLastUpdated(CharSequence lastUpdated) { if (!TextUtils.isEmpty(lastUpdated)) { eikonLastUpdated.setVisibility(View.VISIBLE); eikonLastUpdated.setText(lastUpdated); } else { eikonLastUpdated.setVisibility(View.GONE); } }
Does anyone know how I can add the same to an XML, and how do I go about it, do I also have to add the same to java by calling settext
method? example:
textView.setText("Last updated:");
How do I call the setlastupdated
method for the same?
Given a variadic macro of the form:
#define MY_CALL_RETURN_F(FType, FId, ...) \ if(/*prelude omitted*/) { \ FType f = (FType)GetFuncFomId(FId); \ if(f) { \ return f(__VA_ARGS__); \ } else { \ throw invalid_function_id(FId); \ } \ } \ /**/
-- how can this be rewritten to a variadic function template?
template<typename FType, typename ...Args> /*return type?*/ tmpl_call_return_f(MyFunId const& FId, /*what goes here?*/) { ... FType f = (FType)GetFuncFomId(FId); return f(/*what goes here?*/); ... }
Update: I'm specifically interested in how to declare the reference type for the Args
: &&
or const&
or what?
Update: Note that FType is supposed to be a "plain" function pointer.
-36067236 0did you try this
{% load games_tags %}
at the top instead of pygmentize?
-11765378 0Iterator<Integer> it=ar1.iterator(); Iterator<Integer> it2=ar2.iterator(); while(it.hasNext()&&it2.hasNext()) { result.add(new Integer(it.next().intValue()*it2.next().intValue())); }
will also work efficiently for any list.
-630955 0 How to implement dispose pattern with close method correctly (CA1063)The Framework Design Guidelines (2nd Ed., page 327) say:
CONSIDER providing method
Close()
, in addition to theDispose()
, if close is standard terminology in the area.When doing so, it is important that you make the Close implementation identical to
Dispose
and consider implementingIDisposable.Dispose
method explicitly.
So, following the provided example, I've got this class:
public class SomeClass : IDisposable { private SomeDisposable someInnerDisposable; public void Open() { this.someInnerDisposable = new SomeDisposable(); } void IDisposable.Dispose() { this.Close(); } public void Close() { this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { this.someInnerDisposable.Dispose(); this.someInnerDisposable = null; } } }
FxCop doesn't seem to like that:
CA1816 : Microsoft.Usage : 'SomeClass.Close()' calls 'GC.SuppressFinalize(object)', a method that is typically only called within an implementation of 'IDisposable.Dispose'. Refer to the IDisposable pattern for more information.
CA1816 : Microsoft.Usage : Change 'SomeClass.IDisposable.Dispose()' to call 'GC.SuppressFinalize(object)'. This will prevent unnecessary finalization of the object once it has been disposed and it has fallen out of scope.
CA1063 : Microsoft.Design : Modify 'SomeClass.IDisposable.Dispose()' so that it calls Dispose(true), then calls GC.SuppressFinalize on the current object instance ('this' or 'Me' in Visual Basic), and then returns.
CA1063 : Microsoft.Design : Rename 'SomeClass.IDisposable.Dispose()' to 'Dispose' and ensure that it is declared as public and sealed.
-or-
I tried
[SuppressMessage("Microsoft.Design", "CA1063:ImplementIDisposableCorrectly", Justification = "Framework Design Guidelines say it's ok.")] void IDisposable.Dispose() { this.Close(); }
but FxCop 1.36 still reports them.
EDIT: Changing it around as suggested eliminates all but this warning:
CA1063 : Microsoft.Design : Rename 'SomeClass.IDisposable.Dispose()' to 'Dispose' and ensure that it is declared as public and sealed.
EDIT 2: CODE_ANALYSIS was indeed missing. Thanks.
-3112665 0What about just using typedef
s?
typedef V& I; typedef const V& CI;
Edit:
No. See comments :)
-22119836 0 How to Implement a Class/Database Listener?I am using the Parse.com database service for a PhoneGap app we are creating. We have users that can mark themselves (First User) "Available" for their friends (Second User), and I need a way to listen for that toggle in availability on the second user's side, so their friends list can update without having the refresh the page.
With Parse, your interaction with the database is monitored by # API calls and Burst Limit (Number of API calls per second) so I need to only call the database for the change in status when it is actually changed, I can't keep a setInterval on otherwise it will make the burst limit too small for other user, or it will cause to many API calls for no reason if the status isn't changing.
How can I got about this?
-39015432 0 run Spark-Submit on YARN but Imbalance (only 1 node is working)i try to run Spark Apps on YARN-CLUSTER (2 Nodes) but it seems those 2 nodes are imbalance because only 1 node is working but another one is not.
My Script :
spark-submit --class org.apache.spark.examples.SparkPi --master yarn-cluster --deploy-mode cluster --num-executors 2 --driver-memory 1G --executor-memory 1G --executor-cores 2 spark-examples-1.6.1-hadoop2.6.0.jar 1000
I see one of my node is working but another is not, so this is imbalance :
Note : in the left is
namenode
, and datanode
is on the right...
Any Idea ?
-20764999 0As it turns out, there is a way to do this, but it's not pretty. It involves using the WinForms version of MessageBox
and passing an undocumented option as the last property.
var result = System.Windows.Forms.MessageBox.Show("Are you sure you want to exit this app?", "Exit", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Question, System.Windows.Forms.MessageBoxDefaultButton.Button2, (System.Windows.Forms.MessageBoxOptions)8192 /*MB_TASKMODAL*/);
Hopefully this is helpful to somebody else in the future!
-40907417 0 Why is infinity printed as "8" in the Windows 10 console?I was testing what was returned from division including zeroes i.e. 0/1
, 1/0
and 0/0
. For this I used something similar to the following:
Console.WriteLine(1d / 0d);
However this code prints 8
not Infinity
or some other string constant like PositiveInfinity
.
For completeness all of the following print 8
:
Console.WriteLine(1d / 0d); double value = 1d / 0d; Console.WriteLine(value); Console.WriteLine(Double.PositiveInfinity);
And Console.WriteLine(Double.NegativeInfinity);
prints -8
.
Why does this infinity print 8?
For those of you who seem to think this is an infinity symbol not an eight the following program:
Console.WriteLine(1d / 0d); double value = 1d / 0d; Console.WriteLine(value); Console.WriteLine(Double.PositiveInfinity); Console.WriteLine(8);
Outputs:
-10294436 0This code:
for(NSString *jidAct in occupantsArray){ if([jidAct isEqualToString:jid]){ [occupantsArray removeObjectAtIndex:i]; } i++; }
is probably causing your problems. You shouldn't be removing elements while enumerating the array. The way you avoid this is by using an NSMutableIndexSet:
NSMutableIndexSet *indexes = [NSMutableIndexSet set]; // assuming NSInteger i; for(NSString *jidAct in occupantsArray){ if([jidAct isEqualToString:jid]){ [indexes addIndex:i]; } i++; } [occupantsArray removeObjectsAtIndexes:indexes];
-29617983 0 Here's how I'd approach this:
combiner <- function(n, ...) { ## Capture the unevaluated calls and symbols passed via ... ll <- as.list(substitute(list(...)))[-1] ## Process each one in turn lapply(ll, FUN = function(X) { ## Turn any symbols/names into calls if(is.name(X)) X <- as.call(list(X)) ## Add/replace an argument named n X$n <- n ## Evaluate the fixed up call eval(X) }) } combiner(6, fun1(), fun2, rnorm(), fun4(y=8)) # [[1]] # [1] 3 8 9 7 4 7 # # [[2]] # [1] "Z" "M" "U" "A" "Z" "U" # # [[3]] # [1] 0.6100340 -1.0323017 -0.6895327 1.2534378 -0.3513120 0.3116020 # # [[4]] # [1] 112.31979 91.96595 79.11932 108.30020 107.16828 89.46137
-32262515 0 Yes:
Application.EnableEvents = False
Then when you are done with the procedure:
Application.EnableEvents = True
-32651039 0 If the client name section of the URL is after the access-guid/
and before the next /
:
http://www.disabledgo.com/access-guide/the-university-of-manchester/176-waterloo-place-2 |----------------------------|
you need to use a negated character class to only match university
before the regex reaches that rightmost /
boundary.
As per the Reference:
You can extract pages by Page URL, Page Title, or Screen Name. Identify each one with a regex capture group (Analytics uses the first capture group for each expression)
Thus, you can use
/access-guide/([^/]*(universit(y|ies)|colleges?)) ^^^^^
See demo.
The regex matches
/access-guide/
- leftmost boundary, matches /access-guide/
literally[^/]*
- any character other than /
(so we still remain in that customer section)(universit(y|ies)|colleges?)
- university
, or universities, or
collegeor
colleges` literally. Add more if needed.Position parameter of the getView() method gives the position of the newly created View (i.e the list item), it wont give the clicked item position.
Use listView.onClickListener
in the Activity instead of Adater.
You can make Django go back to the Poll instance by overriding the response_change
method on the full Choice admin:
from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect class ChoiceAdmin(admin.ModelAdmin): ''' To be called from the Poll choice inline. It will send control back to the Poll change form, not the Choice change list. ''' fields = [...] def response_change(self, request, choice): if not '_continue' in request.POST: return HttpResponseRedirect(reverse("admin:appname_poll_change", args=(choice.poll.id,))) else: return super(ChoiceAdmin, self).response_change(request, choice)
To address the second part of your question: I think you'll have to register a second, unmodified, admin on the model. You can do that using a proxy model. See Multiple ModelAdmins/views for same model in Django admin
-34755100 0 How to parse BigInt from the num crate?I am trying to use BigInt
. My code is like this:
extern crate num; use num::bigint::BigInt; ... println!("{}", from_str::<BigInt>("1")); //this is line 91 in the code
In my Cargo.toml file I have the following:
[dependencies] num = "0.1.30"
What I did seem to match what was said in this document, also this document and also an answer here on Stack Overflow.
However I got the following error:
Compiling example v0.1.0 (file:///C:/src/rust/example) src\main.rs:91:20: 91:38 error: unresolved name `from_str` [E0425] src\main.rs:91 println!("{}", from_str::<BigInt>("1"));
-14601824 0 While your pictures are fairly large and you should try to reduce the number and size, you can make gains through packaging the .png into pvr.ccz files. There are multiple different programs available to do this. I like to use Texture Packer which is available here: http://www.codeandweb.com/texturepacker
-20111762 0 Mysql date_add 1 yearCan someone help me figure out why adding 1 year doesn't work for me?
I have 6 other conditions (1 day, 1 week, 2 month, etc). The only one NOT working is the year.
Anyone see why? In case it matters, this is Perl.
elsif ($data{length} == "6month") { $store = qq(INSERT INTO main (creator_name,email2,relationship,reason,email1,name1,creator_email,email3,name2,name3,creator_url,victim_url,length_of_stay,release_date) VALUES("$data{creatorname}","$data{email2}","$data{relationship}","$data{reason}","$data{email1}","$data{person1}","$data{creatoremail}","$data{email3}","$data{person2}","$data{person3}", "$creatorURL", "$victimURL","$data{length}", DATE_ADD(NOW(), INTERVAL 6 MONTH)) ); } elsif($data{length} == "1year") { $store = qq(INSERT INTO main (creator_name,email2,relationship,reason,email1,name1,creator_email,email3,name2,name3,creator_url,victim_url,length_of_stay,release_date) VALUES("$data{creatorname}","$data{email2}","$data{relationship}","$data{reason}","$data{email1}","$data{person1}","$data{creatoremail}","$data{email3}","$data{person2}","$data{person3}", "$creatorURL", "$victimURL","$data{length}", DATE_ADD(NOW(), INTERVAL 1 YEAR)) ); } my $sth = $dbh->prepare($store); $sth->execute() or die $dbh->errstr;
-1154732 0 many domains = much memory usage? I would like to know if for example, I have about 80 domains on my projects, does it means that the 80 domains will be loaded into memory when I run the project or it will be loaded when I need that domain ...
It seems if I have many domains in one project, I have to disable auto compile and increase the perm gen space.
is there any solutions to load just when I need to acces those domain ? not all domain will be used ... sometimes it just small domain that almost never touched by users incase something happens (ie special cases)
I'm using grails 1.1.1 at the moment and have to disable the auto compile for domain or else it will stuck and depleted memory / memory gen space
-13831968 0You can use the http put method to handle the file upload. In this method the data is directly streamed to the PHP script and you can handle it using file functions:
<?php $f = fopen('php://input','r'); while(!feof($f)){ $chunk = fread($f,CHUNK_SIZE); [Handle the uploading file here] } fclose($f); ?>
(Replace CHUNK_SIZE with your value)
-13841315 0For valid xHTML it should have the alt attribute.
Something like this would work:
$xml = new SimpleXMLElement($doc); // $doc is the html document. foreach ($xml->xpath('//img') as $img_tag) { if (isset($img_tag->attributes()->alt)) { unset($img_tag->attributes()->alt); } } $new_doc = $xml->asXML();
-13799947 1 Python Filling Up Disk I need to setup some test conditions to simulate a filled up disk. I created the following to simply write garbage to the disk:
#!/usr/bin/python import os import sys import mmap def freespace(p): """ Returns the number of free bytes on the drive that ``p`` is on """ s = os.statvfs(p) return s.f_bsize * s.f_bavail if __name__ == '__main__': drive_path = sys.argv[1] output_path = sys.argv[2] output_file = open(output_path, 'w') while freespace(drive_path) > 0: output_file.write("!") print freespace(drive_path) output_file.flush() output_file.close()
As far as I can tell by looking at the return value from freespace, the write method does not write the file to until it is closed, thereby making the while condition invalid.
Is there a way I can write the data directly to the file? Or another solution perhaps?
-31752059 0The main issue you seem to be encountering is that the proxy example you're using requires a POST to update the destination URL you're trying to browse through the proxy. That's why you're not getting any content from the target page, and the error message
<div id="error">Hotlinking directly to proxied pages is not permitted.</div>
I don't know how your code looks like, but it seems like you could use the HttpWebRequest POST Method
WebRequest request = (HttpWebRequest)WebRequest.Create("http://www.glype-proxy.info/includes/process.php?action=update"); var postData = "url="+"http://www.example.com"; postData += "&allowCookies=on"; var data = Encoding.ASCII.GetBytes(postData); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = data.Length; using (var stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); } var response = (HttpWebResponse)request.GetResponse(); var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
You're going to need to find or host a proxy that returns the HTML of the page, such as http://www.glype-proxy.info/. Even so, in order for a proxy to function correctly, it must change the link to the page's resources to it's own "proxied" path.
http://www.glype-proxy.info/browse.php?u=https%3A%2F%2Fwww.example.com%2F&b=4&f=norefer
In the URL above, if you want the path to the original resources, you'll have to find all the resources that have been redirected and unencode the path passed in as the u=
parameter to this specific proxy. Also, you may wish to ignore additional elements injected by the proxy , in this case the <div id="include">
element.
I believe the proxy you're using works the same way as the "Glype" proxy I used in this example, but I do not have access to it at the time of posting. Also, if you want to use use other proxies, you may want to note that many proxies display the result in an iFrame (probably for XSS prevention, navigation, or skinning).
Note: Generally, using another service outside of a built-in API is a bad practice, since services often get a GUI update or some other change that could break your script. Also, those services could experiences interruptions or just be taken down.
-36406243 0 Spring-boot app not rendering war file in Tomcat 8I know by default Spring-Boot uses Tomcat 7. Therefore I have declared it in my POM file:
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.8</java.version> <tomcat.version>8.0.33</tomcat.version> </properties>
I confirm that that is the Tomcat version I am using.
I placed the War file in the webapps folder, it naturally unwrapped it but the path localhost:8080/personalsite gives me a 404.
If I run java -jar personalsite
it works fine. Now I am wondering what to do next or where to look.
My log file only outputs the following:
04-Apr-2016 10:16:47.834 INFO [http-nio-8080-exec-8] org.apache.catalina.core.ApplicationContext.log Spring WebApplicationInitializers detected on classpath: [org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration$JerseyWebApplicationInitializer@35a7f52a]
pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.personalsite</groupId> <artifactId>personalsite</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <name>PersonalSite</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.3.3.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.8</java.version> <tomcat.version>8.0.33</tomcat.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <scope>provided</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <configuration> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </build> </project>
-3668746 0 How do I move old content down in the search engine rankings? There is some precedent for search-engine-ranking-related questions on StackOverflow, so please don't close this question. It's programming-related to the extent that HTML META tags can be called "programming".
Here's the problem:
We make FogBugz, the software project planning and bug tracking suite.
Either we did a great job with our old documentation or a crummy job with our new documentation, but for most of the popular searches on FogBugz terms, documentation for our old versions comes up.
Here's an example. For context, our current FogBugz version is FogBugz 7. The top two results for that search are for FogBugz 5, which is positively ancient.
As best I can tell, there are several options for getting these results out of the top slots, but each has problems:
NOINDEX
tag, but what happens if someone is actually searching for help on an old version?NOFOLLOW
on them to deprive the old docs of PageRank. Problem here is that it's really fiddly to find the links to the content, rather than changing the content itself.unavailable_after
tag, which is just a time-delayed NOINDEX
, with the same problem of removal rather than demotion.I just want these old documentation versions to stop competing with our current versions, without being completely unavailable.
-9129513 0Try this:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <Button android:layout_width="100dip" android:layout_height="70dip" android:layout_gravity="center" android:text="111" /> <Button android:layout_width="100dip" android:layout_height="70dip" android:layout_gravity="center" android:text="111 222 333" /> <Button android:layout_width="100dip" android:layout_height="70dip" android:layout_gravity="center" android:text="111 222 333 444 555 666" /> <Button android:layout_width="100dip" android:layout_height="70dip" android:layout_gravity="center" android:text="111" /> </LinearLayout> </LinearLayout>
-33104604 0 You just need to add a "Add Row" button at the end and push a new value to your List1
like this in your controller. See an update to your fiddle here.
$scope.addRow = function(){ var len = $scope.List1.length; $scope.List1.push('product'+(len+1)); }
And right after your table, add a button that calls the above function:
</table> <button ng-click="addRow()">Add a row</button>
-8862508 1 iFrame within wxpython? Hi i am wondering if there is a widget or someway to put an iFrame in a program with wxpython. An iFrame with the same capabilities as the HTML one, (ability to see other websites).
Thanks.
-29542878 0 Excel VBA fill 100 x 100 martix based on value in a columnI would love to fill a spreadsheet with 100 columns and 100 rows. I used the analysis toolpack to create a column of 10,000 numbers from a distribution (using the discrete distribution options 1 variable, 10,000 numbers and the two columns below as values).
I want the columns to simulate 100 trials of 100 years using the column as the reproduction rates. The column created simulates the reproduction rates for each cell within the 100 x 100 matrix. I would like the initial row value for all columns to be 31.
For the first column, I would like the (2,1) to multiple 31 by the first value in the reproduction column. For (3,1) I would like the to multiple (2,1) by the second value in the reproduction column. I would like this to continue for all 100 cells in the first column. I would then like it to start over on the next column starting with (2,1) being 31 multiplied by the 101 value in the reproductive column.
Private Sub Code() Dim i As Long Dim j As Long Dim iCol Dim ws As Worksheet 'Set this to the source sheet (where your trial counts are) Set ws = ActiveWorkbook.Sheets(4) For i = 2 To 100 iCol = ws.Cells(i, 1) For j = 1 To 100 Cells(1, i).Value = 34 For k = 1 To iCol Cells(j + 1, i + 1).Value = Cells(j, i).Value * k Next k Next j Next i End Sub
Here is the distribution that I would like the random numbers to be generated from. If there is a way to use the analysis tool within the VBA to allow so the numbers are generated there instead of externally, that would be great!
Value, Probability -0.15,0 -0.125,0 -0.1,0.05 -0.075,0 -0.05,0.05 -0.025,0 0,0 0.025,0.05 0.05,0 0.075,0 0.1,0.15 0.125,0.15 0.15,0.3 0.175,0.05 0.2,0.15 0.225,0.05 0.25,0
Any help or advice is greatly appreciated!
Thank you!!
-34976274 0You have to create the table before Model from migration file check Documentation Creating tables section, then the model will use the plural name of the class as the table name.
NOTE : You have to set up your database configuration firstly and create database manually check Database: Getting Started section.
Hope this helps.
-14617635 0 php thumbnail organizerOk, i have this code and is working perfectly, but i need the order of the images to be by the date the image was created, can someone give me a hand?
$images=array(); $dir = @opendir('.') or die("Unable to open $path"); $i=0; while($file = readdir($dir)) { if(is_dir($file)) continue; else if($file != '.' && $file != '..' && $file != 'index.php') { $images[$i]=$file; $i++; } } sort($images); for($i=0; $i<sizeof($images); $i++) { echo "<a href=".chr(34).$path.$images[$i].chr(34)."><img style='border:1px solid #666666; width:200px; margin: 10px;' src='".$images[$i]."'/></a>"; } closedir($dir);
-38942937 0 df["dataset_code"]
is a Series
, not a DataFrame
. Since you want to append one DataFrame to another, you need to change the Series object to a DataFrame object.
>>> type(df) <class 'pandas.core.frame.DataFrame'> >>> type(df['dataset_code']) <class 'pandas.core.series.Series'>
To make the conversion, do this:
df = df["dataset_code"].to_frame()
-27532359 0 Spring-Boot : Referencing another Spring Boot Project I created two spring boot projects, one is with JPA and the other with Web. I initially combined both of them into one project and everything works perfectly.
I now want to separate the JPA portion from the Web. So I added the JPA project as a dependency of the Web. But spring-boot is unable to detect the beans on JPA.
Is there any examples on how to implement this?
I am getting the exception when I tried to autowire the beans from the JPA project.
BeanCreationException: Could not autowire field:
-39906977 0 OGNL allows execution of methods, but the static access is disabled by default, so you cannot use static method in expressions. However, you can teach OGNL which classes needs to access the static methods.
OGNL developer guide: Method Accessors
Method calls are another area where OGNL needs to do lookups for methods based on dynamic information. The
MethodAccessor
interface provides a hook into how OGNL calls a method. When a static or instance method is requested the implementor of this interface is called to actually execute the method.public interface MethodAccessor { Object callStaticMethod( Map context, Class targetClass, String methodName, List args ) throws MethodFailedException; Object callMethod( Map context, Object target, String methodName, List args ) throws MethodFailedException; }
You can set a method accessor on a class-by-class basis using
OgnlRuntime.setMethodAccessor()
. The is a default method accessor for Object (which simply finds an appropriate method based on method name and argument types and uses reflection to call the method).
You can code something
public class StringUtil extends StringUtils implements MethodAccessor { //implement above methods }
public static final String MESSAGE = "hello.message"; /** * Field for Message property. */ private String message; /** * Return Message property. * * @return Message property */ public String getMessage() { return message; } private StringUtil stringUtil = new StringUtil(); public StringUtil getStringUtil() { return stringUtil; } public String execute() throws Exception { setMessage(getText(MESSAGE)); OgnlRuntime.setMethodAccessor(StringUtil.class, stringUtil); return SUCCESS; }
<s:if test="!stringUtil.isEmpty(message)"> <h2><s:property value="message"/></h2> </s:if>
Try this:
> d <- as.Date("01-01-2013", "%d-%m-%Y") + 0:7 # first 8 days of 2013 > d [1] "2013-01-01" "2013-01-02" "2013-01-03" "2013-01-04" "2013-01-05" [6] "2013-01-06" "2013-01-07" "2013-01-08" > > ufmt <- function(x) as.numeric(format(as.Date(x), "%U")) > ufmt(d) - ufmt(cut(d, "year")) + 1 [1] 1 1 1 1 1 2 2 2
Note: The first Sunday in the year is defined as the start of week 1 by %U
which means that if the year does not start on Sunday then we must add 1 to the week so that the first week is week 1 rather than week 0. ufmt(cut(d, "year"))
equals one if d
's year starts on Sunday and zero otherwise so the formula above reduces to ufmt(d)
if d's year starts on Sunday and ufmt(d)+1
if not.
UPDATE: corrections so Jan starts at week 1 even if year starts on a Sunday, e.g. 2006.
-14660230 0I've spend many hours on that subject, one (working) thing I've found is this: https://github.com/jgallen23/OWAParser
My problem was, after testing many times with my company's Exchange server they've locked my account. And even thought it works, after changing something small in the server configuration it will stop working, and that wasn't an option for me.
Hope this helps you! :-)
-16314092 0have you tried like below one
Call below Method From the TableView DataSource Method (cellForAtIndexPath)
For Doing the same Task
- (void)setCellBGColorNormalAndSelectedForTableViewCell:(UITableViewCell*)cell cellForRowAtIndexPath:(NSIndexPath*)indexPath { UIImageView *normalCellBG = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, cell.frame.size.width, cell.frame.size.height)]; [normalCellBG setImage:[UIImage imageNamed:@"box_nonselected.png"]];//Set Image for Normal [normalCellBG setBackgroundColor:[UIColor clearColor]]; [cell setBackgroundView:normalCellBG]; UIImageView *selecetedCellBG = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, cell.frame.size.width, cell.frame.size.height)]; [selecetedCellBG setImage:[UIImage imageNamed:@"box_selected.png"]];//Set Name for selected Cell [selecetedCellBG setBackgroundColor:[UIColor clearColor]]; [cell setSelectedBackgroundView:selecetedCellBG ]; }
-3006440 0 Xcode File management. What is best practice? I've been using Xcode for a while now. One thing that always bugs me is the way it handles files. I like to have my files all in nested folders rather than one big physical folder, but when you create a group in Xcode by default it does not create a folder just a virtual folder within the project.
I can see that virtual folders are great for linking code in arbitrary places into your project but once you get beyond a few classes I find the one big folder approach really painful. And then if you try to fix it later it takes ages and is easy to break your build.
Is it possible to change this behaviour so that by default it creates a physical folder? Or am I doing it wrong and trying to cling to some other way of working? How do other people work with files in Xcode?
-38052724 0format
is a method of str
so you should call that from your string, then pass the result of that into print
.
print ("So you are {name} and you are{age}".format(name=my_name,age=my_age))
-3983809 0 If your goal is to make a game per se with the requirements of developing on OSX and running anywhere it's sounding a lot like Unity3D would be a good match. On this path you'll end up coding in UnityScript and or C# probably. It gives you a lot of tools in a package and it's popular in games development circles. So it sounds like a good match for you too me.
If you just want to learn, you can use whatever language you like. Something fairly popular if you want readily tranferrable skills. I wouldn't worry too much about performance if you're just learning concepts. Languages are a dime a dozen and most will teach you a strong basis to build on.
If you want to become a professional games developer for a big name studio working on consoles you might want to consider learning some C or C++ - particularly to understand memory management, pointers and some other low level concepts.
-14044514 0 Can't get data from a codeigniter function with ajaxThis is what I've got so far:
This function that returns data from the model:
function get_user2() { $this->load->model('my_model'); $id=$this->input->post('users1'); $users2=$this->my_model->get_relations($id); return $users2; }
the model function:
function get_relations($usr) { $this->db->where('id',$usr); $rel=$this->db->get('relacion'); if($rel->num_rows!=0) { $relacion=array(); foreach ($rel->result_array() as $row) { $relacion[]=array( 'id'=>$row['id'], 'username1'=>$row['username1'], 'username2'=>$row['username2'], ); } return $relacion; }else{ return false; } }
and in my view:
<select name="users1" id="drop1"> <?php if($opciones!=false){ foreach ($opciones as $row) { echo '<option value="'.$row['user_id'].'">'.$row['username'].'</option>'; } } ?> </select> <script src="jquery.js"></script> <script type="text/javascript"> $("#drop1").change(function(){ $.ajax({ type: "POST", url: "example.com/CI/index.php/evaluation/get_user2", data: "users1="+$('#drop1').val(), success: function(){ alert('it works!'); } }); }); </script>
I want to fill a second dropdown with the options returned by the controller function, but the ajax request doesn't do anything so I haven't even got to that part. Can someone help me spot what's wrong? I already tested the controller and model's function and they work. And could you tell me how to fill the second dropdown's options? Thank you very much!
-18947308 0 Horizontal manager alignment of its child view?How can I align a child view in the horizontal LinearLayout? I have two textviews (width height is wrap_content) in the horizontal manager. How I can align one to right and the other one to the left?
-3072316 0 how do i receive messages sent to gtalk?im making an application that needs to get received messages that were sent to google chat. is there an api for working with google chat?
can someone please give me an example in C# how do i receive gtalk messages? im sorry the xmpp documentation is too complex and i do not understand where to start
-32187702 0 How to call Pinch and Zoom class on am ImageView?I am a newbie to android development. Here I am trying to add pinch and zoom an image in my image view. The image is loaded on an activity called FullScreenView
Here is my FullScreenView.java file
public class FullScreenViewActivity extends Activity implements OnClickListener { private static final String TAG = FullScreenViewActivity.class .getSimpleName(); public static final String TAG_SEL_IMAGE = "selectedImage"; private Wallpaper selectedPhoto; private ImageView fullImageView; private LinearLayout llSetWallpaper, llDownloadWallpaper,btShare; private Utils utils; private ProgressBar pbLoader; InterstitialAd mInterstitialAd; // Picasa JSON response node keys private static final String TAG_ENTRY = "entry", TAG_MEDIA_GROUP = "media$group", TAG_MEDIA_CONTENT = "media$content", TAG_IMG_URL = "url", TAG_IMG_WIDTH = "width", TAG_IMG_HEIGHT = "height"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_fullscreen_image); //add code AdView mAdView = (AdView) findViewById(R.id.adView); AdRequest adRequest = new AdRequest.Builder().build(); mAdView.loadAd(adRequest); mInterstitialAd = new InterstitialAd(this); mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712"); requestNewInterstitial(); fullImageView = (ImageView) findViewById(R.id.imgFullscreen); llSetWallpaper = (LinearLayout) findViewById(R.id.llSetWallpaper); llDownloadWallpaper = (LinearLayout) findViewById(R.id.llDownloadWallpaper); btShare = (LinearLayout) findViewById(R.id.btShare); pbLoader = (ProgressBar) findViewById(R.id.pbLoader); // hide the action bar in fullscreen mode getActionBar().hide(); utils = new Utils(getApplicationContext()); // layout click listeners llSetWallpaper.setOnClickListener(this); llDownloadWallpaper.setOnClickListener(this); btShare.setOnClickListener(this); // setting layout buttons alpha/opacity llSetWallpaper.getBackground().setAlpha(70); llDownloadWallpaper.getBackground().setAlpha(70); btShare.getBackground().setAlpha(70); Intent i = getIntent(); selectedPhoto = (Wallpaper) i.getSerializableExtra(TAG_SEL_IMAGE); // check for selected photo null if (selectedPhoto != null) { // fetch photo full resolution image by making another json request fetchFullResolutionImage(); } else { Toast.makeText(getApplicationContext(), getString(R.string.msg_unknown_error), Toast.LENGTH_SHORT) .show(); } } private void requestNewInterstitial() { AdRequest adRequest = new AdRequest.Builder() .addTestDevice("PFSW5H65PRTS9TTO") .build(); mInterstitialAd.loadAd(adRequest); } /** * Fetching image fullresolution json * */ private void fetchFullResolutionImage() { String url = selectedPhoto.getPhotoJson(); // show loader before making request pbLoader.setVisibility(View.VISIBLE); llSetWallpaper.setVisibility(View.GONE); llDownloadWallpaper.setVisibility(View.GONE); btShare.setVisibility(View.GONE); // volley's json obj request JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Log.d(TAG, "Image full resolution json: " + response.toString()); try { // Parsing the json response JSONObject entry = response .getJSONObject(TAG_ENTRY); JSONArray mediacontentArry = entry.getJSONObject( TAG_MEDIA_GROUP).getJSONArray( TAG_MEDIA_CONTENT); JSONObject mediaObj = (JSONObject) mediacontentArry .get(0); final String fullResolutionUrl = mediaObj .getString(TAG_IMG_URL); // image full resolution widht and height final int width = mediaObj.getInt(TAG_IMG_WIDTH); final int height = mediaObj.getInt(TAG_IMG_HEIGHT); Log.d(TAG, "Full resolution image. url: " + fullResolutionUrl + ", w: " + width + ", h: " + height); ImageLoader imageLoader = AppController .getInstance().getImageLoader(); // We download image into ImageView instead of // NetworkImageView to have callback methods // Currently NetworkImageView doesn't have callback // methods imageLoader.get(fullResolutionUrl, new ImageListener() { @Override public void onErrorResponse( VolleyError arg0) { Toast.makeText( getApplicationContext(), getString(R.string.msg_wall_fetch_error), Toast.LENGTH_LONG).show(); } @Override public void onResponse( ImageContainer response, boolean arg1) { if (response.getBitmap() != null) { // load bitmap into imageview fullImageView .setImageBitmap(response .getBitmap()); adjustImageAspect(width, height); // hide loader and show set & // download buttons pbLoader.setVisibility(View.GONE); llSetWallpaper .setVisibility(View.VISIBLE); llDownloadWallpaper .setVisibility(View.VISIBLE); btShare .setVisibility(View.VISIBLE); } } }); } catch (JSONException e) { e.printStackTrace(); Toast.makeText(getApplicationContext(), getString(R.string.msg_unknown_error), Toast.LENGTH_LONG).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e(TAG, "Error: " + error.getMessage()); // unable to fetch wallpapers // either google username is wrong or // devices doesn't have internet connection Toast.makeText(getApplicationContext(), getString(R.string.msg_wall_fetch_error), Toast.LENGTH_LONG).show(); } }); // Remove the url from cache AppController.getInstance().getRequestQueue().getCache().remove(url); // Disable the cache for this url, so that it always fetches updated // json jsonObjReq.setShouldCache(false); // Adding request to request queue AppController.getInstance().addToRequestQueue(jsonObjReq); } /** * Adjusting the image aspect ration to scroll horizontally, Image height * will be screen height, width will be calculated respected to height * */ @SuppressWarnings("deprecation") @SuppressLint("NewApi") private void adjustImageAspect(int bWidth, int bHeight) { LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( LayoutParams.FILL_PARENT , LayoutParams.FILL_PARENT); if (bWidth == 0 || bHeight == 0) return; int sHeight = 0; if (android.os.Build.VERSION.SDK_INT >= 13) { Display display = getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); sHeight = size.y; } else { Display display = getWindowManager().getDefaultDisplay(); sHeight = display.getHeight(); } int new_width = (int) Math.floor((double) bWidth * (double) sHeight / (double) bHeight); params.width = new_width; params.height = sHeight; Log.d(TAG, "Fullscreen image new dimensions: w = " + new_width + ", h = " + sHeight); //fullImageView.setLayoutParams(params); // fullImageView.setAdjustViewBounds(true); fullImageView.setScaleType(ImageView.ScaleType.FIT_CENTER); } /** * View click listener * */ @Override public void onClick(View v) { if (mInterstitialAd.isLoaded()) { mInterstitialAd.show(); } //else //{ // beginPlayingGame(); // } Bitmap bitmap = ((BitmapDrawable) fullImageView.getDrawable()) .getBitmap(); File cache = getApplicationContext().getExternalCacheDir(); File sharefile = new File(cache, "toshare.png"); try { FileOutputStream out = new FileOutputStream(sharefile); bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out); out.flush(); out.close(); } catch (IOException e) { } switch (v.getId()) { // button Download Wallpaper tapped case R.id.llDownloadWallpaper: utils.saveImageToSDCard(bitmap); break; // button Set As Wallpaper tapped case R.id.llSetWallpaper: utils.setAsWallpaper(bitmap); break; case R.id.btShare: Intent share = new Intent(android.content.Intent.ACTION_SEND); share.setType("image/*"); share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + sharefile)); try { startActivity(Intent.createChooser(share, "Share photo")); } catch (Exception e) { } break; default: break; } } }
I also create the class for bringing pinch and zoom facility to this.
ZoomableImageView.java
public class ZoomableImageView extends View { //Code goes here }
How to call this ZoomableImageView java class file to FullScreenViewActivity so that,when i pinch and zoom, it get works...
-28844383 0 Deploy Node.js app to AWS elastic beanstalk that contains static assetsI'm having some trouble visualizing how I should handle static assets with my EB Node.js app. It only deploys whats committed in the git repo when you do eb deploy
(correct?) but I don't want to commit all our static files. Currently we are uploading to S3 and the app references those (the.s3.url.com/ourbucket/built.js
), but now that we are setting up dev, staging, and prod envs we can reference built.js
since there can be up to 3 versions of it.
Also, there's a timespan where the files are uploaded and the app is rolling out and the static assets don't work with the two versions up on the servers (i.e. built.js works with app version 0.0.2 but server one is deploy 0.0.1 and server two is running version 0.0.2)
How do keep track of these mismatches or is there a way to just deploy a static assets to the EB instance directly.
-37262091 0 Analog timepicker inside scrollView not displaying time chooserSo, in portrait mode is displayed correctly, no matter if timePicker is in scrollView or not.
Landscape mode when is inside scroolView.
Landscape mode when there is no scroolView.
[Edit] Code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.aapps.groupalarmclock.NewAlarmActivity"> <ImageView android:layout_width="match_parent" android:layout_height="match_parent" android:scaleType="centerCrop" android:src="@drawable/background" android:alpha="@dimen/background_transparency" android:layout_centerHorizontal="true" /> <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="@dimen/toolbar_height" android:layout_alignParentTop="true" android:weightSum="2" android:background="@color/colorToolbar" android:gravity="center_vertical" android:id="@+id/linearLayout"> <RelativeLayout android:layout_width="0dp" android:layout_height="match_parent" android:id="@+id/rl_cancle" android:layout_weight="1" android:background="@drawable/click_effect" android:gravity="center"> <ImageView android:layout_width="@dimen/toolbar_icon_size" android:layout_height="@dimen/toolbar_icon_size" android:id="@+id/iv_cancel" android:src="@drawable/cancel" android:layout_centerVertical="true" android:layout_centerHorizontal="true" android:layout_marginRight="@dimen/cancel_done_right_margin" android:layout_marginEnd="@dimen/cancel_done_right_margin"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:textColor="@color/colorText" android:id="@+id/tv_cancel" android:layout_centerVertical="true" android:layout_toRightOf="@+id/iv_cancel" android:layout_toEndOf="@+id/iv_cancel" /> </RelativeLayout> <View android:layout_width="1dp" android:layout_height="@dimen/separator_height" android:background="@color/colorLineSeparator" android:id="@+id/v_cancel_done"> </View> <RelativeLayout android:layout_width="0dp" android:layout_height="match_parent" android:id="@+id/rl_done" android:layout_weight="1" android:background="@drawable/click_effect" android:gravity="center"> <ImageView android:layout_width="@dimen/toolbar_icon_size" android:layout_height="@dimen/toolbar_icon_size" android:id="@+id/iv_done" android:src="@drawable/done" android:layout_centerVertical="true" android:layout_centerHorizontal="true" android:layout_marginRight="@dimen/cancel_done_right_margin" android:layout_marginEnd="@dimen/cancel_done_right_margin"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:textColor="@color/colorText" android:id="@+id/tv_done" android:layout_centerVertical="true" android:layout_toRightOf="@+id/iv_done" android:layout_toEndOf="@+id/iv_done" /> </RelativeLayout> </LinearLayout> <ScrollView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/scrollView" android:layout_below="@+id/linearLayout" android:layout_centerHorizontal="true" android:fillViewport="true"> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/lltp"> <TimePicker tools:targetApi="23" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/timePicker" android:timePickerMode="clock" android:background="#80FFFFFF"/> </RelativeLayout> </ScrollView>
Anyone know what is wrong?
-1274738 0You could use Traversing/contains also:
$('ul#accordion a').contains(bctext);
-37067215 0 Finally I managed to access it from my computer. I had to modify the configuration file for the operation center, located in /etc/opscenter/opscenterd.conf
(only for package installation):
[webserver] port = 8888 interface = 127.0.0.1
By default the webserver accepts requests only from the localhost. Probably it won't be the best option, but since the operation center allows to configure users, I set interface = 0.0.0.0
, allowing any host to contact it.
Your echos are failing;
echo(<p>test1</p>);
should be echo('<p>test1</p>');
and echo(<h1>fail</h1>);
should be echo('<h1>fail</h1>');
FYI: echo doesn't require brackets, you could do echo '<h1>fail</h1>';
product_size alone will not be a PK and so I cannot reference it
Imagine you have two rows in product_stock
table that have the same product_size
(and different product_code
). Now imagine one of these rows (but not the other) is deleted.
orderline
rows that reference it? product_stock
row, that orderline
rows also reference?(Similar problems exist for ON DELETE CASCADE / SET NULL and also when UPDATE-ing the PK.)
To avoid these kinds of ambiguities, the DBMS won't let you create a foreign key unless you can uniquely identify parent row, meaning you must use the whole key after the REFERENCES clause of your FK.
That being said, you could create both...
FOREIGN KEY (product_code) REFERENCES product (product_code)
...and...
FOREIGN KEY (product_code, product_size) REFERENCES product_stock (product_code, product_size)
Although, if you have the latter, the former is probably redundant.
In fact, (since you already have the FK product_stock -> product
), having both FKs would create a "diamond shaped" dependency. BTW, some DMBSes have restrictions on diamond-shaped FKs (MS SQL Server doesn't support cascading referential actions on them).
I just realized that if in eclipse i check "use system default php.ini
" under window->preferences->php->phpexecutables
it will magically work.
Does anyone know what is "system default php.ini"?
I do a a quick $php --ini
and it returns:
Configuration File (php.ini) Path: /etc/php5/cli Loaded Configuration File: /etc/php5/cli/php.ini Scan for additional .ini files in: /etc/php5/cli/conf.d Additional .ini files parsed: /etc/php5/cli/conf.d/05-opcache.ini, /etc/php5/cli/conf.d/10-mysqlnd.ini, /etc/php5/cli/conf.d/10-pdo.ini, /etc/php5/cli/conf.d/20-json.ini, /etc/php5/cli/conf.d/20-mysql.ini, /etc/php5/cli/conf.d/20-mysqli.ini, /etc/php5/cli/conf.d/20-pdo_mysql.ini, /etc/php5/cli/conf.d/20-readline.ini
-4078397 0 I found Scintilla to be very feature-packed, and covered everything I needed. You have to do a bit of work to get all the functionality out of it (ensuring that keyboard short-cuts perform the desired effect, etceteras), but it was incredibly easy to compile, include and get working, though as I said you have to do a bit of legwork to get everything out of it, but this is better than having to tear your hair out getting an "all-purpose" control to stop doing something you don't want to. It is as if the authors have given you a toolbox to work with.
-40079467 0First of all, to check if the number is even just check the modulus by 2, no need to check if the last digit is 2 or 4 or 6 or 8. I would substitute all your checks with next1%2==0
, next1%5==0
and next1%10==0
, also you need to change every cout<<next2
to cout<<next1
because next2
is modulus of 10 of next1
. Also as a good practice I suggest you to read Straustrup C++ book to get the basics of C++.
I want to do 2 things:
Learn how to resize the logo in case the screen is lower than a specific width (assuming that I know how to work with media-queries)
<div id="myLogo"> <a href="#"> <img src="css/img/my_logo.png" alt="My Logo"> </a> </div><!--End of #myLogo-->
What should I do to achieve them both? What should be my CSS and did I wrote the code correctly?
-26297202 0I had the same problem. The only workaround I found was to reduce the number of new Image() to use (ideally one):
function ImageLoader() { var img = new Image(); var queue = []; var lock = false; var lastURL; var lastLoadOk; return { load: load }; function load(url, callback, errorCallback) { if (lock) return queue.push(arguments); lock = true; if (lastURL === url) return lastLoadOk ? onload() : onerror(); lastURL = url; img.onload = onload; img.onerror = onerror; img.src = url; function onload() { lastLoadOk = true; callback(img); oncomplete(); } function onerror() { lastLoadOk = false; if (errorCallback) errorCallback(url); oncomplete(); } } function oncomplete() { lock = false; if (queue.length) load.apply(null, queue.shift()); } } var loader = new ImageLoader(); loader.load(url1, function(img) { // do something }); loader.load(url2, function(img) { // do something });
Note that images will be loaded in serie. If if want to load 2 images in parallel, you'll need to instantiate 2 ImageLoader.
-40266753 0 Multiple operations in ternary operatorIs it possible to have multiple operations within a ternary operator's if/else?
I've come up with an example below, probably not the best example but I hope you get what I mean.
var totalCount = 0; var oddCount = 0; var evenCount = 0; for(var i = 0; i < arr.length; i++) { if(arr[i] % 2 === 0) { evenCount ++; totalCount ++; } else { oddCount ++; totalCount ++; } }
into something like:
var totalCount = 0; var oddCount = 0; var evenCount = 0; for(var i = 0; i < arr.length; i++) { arr[i] % 2 === 0? evenCount ++ totalCount ++ : oddCount ++ totalCount ++; } }
-27196026 0 ALTER TABLE table_name ADD COLUMN column_name datatype
correct syntax
ALTER TABLE `WeatherCenter` ADD COLUMN BarometricPressure SMALLINT NOT NULL, ADD COLUMN CloudType VARCHAR(70) NOT NULL, ADD COLUMN WhenLikelyToRain VARCHAR(30) NOT NULL;
check syntax
-24260321 0 Work with version control Offline \ OnlineHow can I change the status from version control work offline to working online using the API?
Can I do it to all of the model or to a particular package?
-17908090 0 How to Validate Column with Same Value?How to validate the column with same value, i try with this code :
protected void ASPxGridView1_RowValidating(object sender, DevExpress.Web.Data.ASPxDataValidationEventArgs e) { XPQuery<Inventory_Library.Inventory.t_barang_master> q = new XPQuery<Inventory_Library.Inventory.t_barang_master>(ses); List<Inventory_Library.Inventory.t_barang_master> lst = (from o in q where (o.nama_barang == e.OldValues["nama_barang"] && o.kode_barang == e.OldValues["kode_barang"]) select o).ToList<Inventory_Library.Inventory.t_barang_master>(); if (lst.Contains(e.OldValues["nama_barang"])) { e.RowError = "Nama barang yang anda masukkan telah terdaftar dalam sistem"; } else if (lst.Contains(e.OldValues["kode_barang"])) { e.RowError = "Kode barang yang anda masukkan telah terdaftar dalam sistem"; } }
but that's not work, how to solve this problem, thanks for the answer
-34032027 0I would recommend that you look into breaking this down into parts. For example, do you have the login working on the web portion (rails)? If so then you can begin to try to get it to work on the iOS side. Next I would recommend you look into POST and GET requests as a basic way of talking to a back end. Once you have gotten simple apps to work with that then you might have a better idea of the path that lies ahead.
-19697644 0 Successful implementation of user online or notI have a Java EE 7 application with Spring MVC, which is a web service for mobile application as a final school project. I attribute a Calendar for the last request received and Boolean "Online" for each user. So here's my problem implementer how well a system will change the attribute of the user in my DB if the web service no longer get from the user's request after X minutes?
I need to make a class that implements Runnable and make an infinite loop on my DB looking the Online User and compares how long that has made a request?
If the answer is yes how to do a method that is still running?
Sorry for my english I'm not English.
-23498294 0 Linq to Entities SQL Multiple LIKE statementsI have to search an Entity by some values, the ones empty I don't have to consider them but the others I have to use a LIKE statement using Linq to Entities.
The result I want to obtain should be similar to this SQL,
... WHERE (@taxid = '' OR m.taxid LIKE @taxid + '%') AND (@personalid = '' OR m.personalid LIKE @personalid + '%') AND (@certificate = '' OR m.certificate LIKE @certificate + '%')
My Linq to Entities looks like:
persons = context.Persons.Where(e => e.TaxId.Contains(taxId) && e.PersonalId.Contains(personalId) && e.Certificate.Contains(certificate)).ToList();
Any clue?
-679088 0I would go with "from" + confirmation, to avoid forging.
I.e. receive the email, but send a response with auth token in the subject line (or in the body) back to the "from" address. The user either will need reply, or click a link to confirm the submission.
And you post the content only after confirmation.
-1688307 0Start the MonoDevelop program and select "New Solution" and then select the iPhone template.
There are a handful of walk through documents like: http://monotouch.net/Tutorials/MonoDevelop_HelloWorld
Or a complete step-by-step screencast here:
http://www.codesnack.com/blog/2009/9/20/getting-started-with-monotouch.html
Building Hello world: http://tv.falafel.com/iphone/09-09-18/Writing_your_First_IPhone_application_in_C_using_MonoTouch.aspx
-4802728 0Have you looked at ObjectDataSource
? You configure it by providing the the names of your C# methods responsible for the CRUD operations. Then in your methods you can do whatever you want.
I am getting an error at position 1996250 in my mysql replication. How can I find out what table/row is at that position?
-34958453 0Try to perform the action in a background-queue using the following code:
SwiftSpinner.show("Generating new calendar for \(forYear)", animated: true) dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), { let calendar = generateCalendarFor(forYear) print("GENERATED NEW calendar for \(forYear)") dispatch_async(dispatch_get_main_queue(), { SwiftSpinner.show("Saving calendar", animated: false) }) saveNew(calendar, year: forYear) dispatch_async(dispatch_get_main_queue(), { SwiftSpinner.hide() onCompletion(calendar) }) })
What you do here:
dispatch_async(dispatch_get_main_queue(), { SwiftSpinner.show("Saving calendar", animated: false) })
(main-queue is important because the UI shpuld only be modified from the main-queue)onCompletion
in the main-queue which does something with the calendar (replaces return calendar
)You should make sure that your UI-buttons etc. are disabled before dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), { ... })
gets called and enabled again in onCompletion
else the user would be able to press some buttons while your app is working (and maybe change some data used by the queue -> not good).
Why: The UI is updated from the main-queue, but usually not immediately after you call the code to update it; if you block the main-queue, your UI cannot be updated. So we do the work in a background-queue so your main-queue can update the UI.
In detail: You call dispatch_async
(from GrandCentralDispatch) which creates a new queue with the priority QOS_CLASS_USER_INITIATED
(~normal priority). Then it passes the code in the curly braces to this queue; the OS will execute the queue in a separate thread. Because the UI must only be modified from the main-queue, we pass the code that updates the UI (SwiftSpinner.show("Saving calendar", animated: false)
) to the main-queue by using dispatch_async
again.
The use of a completion-function is necessary because the code/queue is executed in the background and independently from getOrCreateCalendar
; your function probably returns before the queue is completed and the calendar created and saved.
A lot of times I see people splitting up a Project into 2 separate projects, like in this screenshot:
What is the point of seperating Ingot and IngotAPI instead of putting them both in the same project because they get compiled together anyways?
-15133470 0You can have 6 unique games between 4 teams. There are 7 possible pairing hence 42 unique games.
Each player pairs up with every other player only once and play against each one of them 6 times exactly.
List:
Pairs 01: (1,2),(3,4),(5,6),(7,8) PairRound 1: GameRound 01: (1,2) - (3,4) | (5,6) - (7,8) GameRound 02: (1,2) - (7,8) | (3,4) - (5,6) GameRound 03: (1,2) - (5,6) | (3,4) - (7,8) Pairs 02: (1,3),(2,4),(5,7),(6,8) PairRound 2: GameRound 04: (1,3) - (2,4) | (5,7) - (6,8) GameRound 05: (1,3) - (6,8) | (2,4) - (5,7) GameRound 06: (1,3) - (5,7) | (2,4) - (6,8) Pairs 03: (1,4),(2,3),(5,8),(6,7) PairRound 3: GameRound 07: (1,4) - (2,3) | (6,7) - (5,8) GameRound 08: (1,4) - (5,8) | (2,3) - (6,7) GameRound 09: (1,4) - (6,7) | (2,3) - (5,8) Pairs 04: (1,5),(2,6),(3,7),(4,8) PairRound 4: GameRound 10: (1,5) - (2,6) | (3,7) - (4,8) GameRound 11: (1,5) - (4,8) | (2,6) - (3,7) GameRound 12: (1,5) - (3,7) | (2,6) - (4,8) Pairs 05: (1,6),(2,5),(3,8),(4,7) PairRound 5: GameRound 13: (1,6) - (2,5) | (3,8) - (4,7) GameRound 14: (1,6) - (4,7) | (2,5) - (3,8) GameRound 15: (1,6) - (3,8) | (2,5) - (4,7) Pairs 06: (1,7),(2,8),(3,5),(4,6) PairRound 6: GameRound 16: (1,7) - (2,8) | (3,5) - (4,6) GameRound 17: (1,7) - (4,6) | (2,8) - (3,5) GameRound 18: (1,7) - (3,5) | (2,8) - (4,6) Pairs 07: (1,8),(2,7),(3,6),(4,5) PairRound 8: GameRound 19: (1,8) - (2,7) | (3,6) - (4,5) GameRound 20: (1,8) - (4,5) | (2,7) - (3,6) GameRound 21: (1,8) - (3,6) | (2,7) - (4,5)
-26053837 0 ajax function not opening a page i don't understand why ajax is not working. my code:
<script type="text/javascript" src="js/jquery-1.9.1.js"></script> <script type="text/javascript"> function edit_row(id) { $.ajax({ method:'get', url:'form.php', success:function(data) { $('#form_div').html(data); } }); }
<?php echo '<td style='.$style.'>'.$status.'<a href="" title="Edit" onClick=edit_row('.$data['type_id'].')><img src="images/pencil.png" width="30px" height="30px"></a></td></tr>'; ?>
its not opening form.php onclick what is the problem please help me!!!
-35972058 0class Letter { char c; boolean isRevealed; //... getters and setters } Letter[] word = new Letter[MAX_WORD_LENGTH]; private boolean isGuessRight(char chr){ for (int i = 0 ; i < word.length ; i++){ if (word[i].getChar() == chr && word[i].getRevealed() == false){ word[i].reveal(); return true; } else if (word[i] == chr && word[i].getRevealed()){ return false; } } }
-15119711 0 Let's say branches A
and B
, standing on A
, file f
was modified (and not checked into A
), while B
contains another version. If I try to rebase B
onto A
, the local changes for f
are lost. Solution: Commit the changes to f
, or stash them away for later, or perhaps discard them by git checkout f
.
That is what the message says, in a nutshell.
If you "tried again until it worked", you probably lost changes like the above.
Morals of the story: If you want to do any more complex operation with git
(like pulling from upstream, rebasing, changing last commit, ...) make sure everything is tidy. I.e., git status
says it is clean, and hopefully no untracked files.
Trying to use Spring security for authentication process, but getting Bad credentials
exception.here is how I have defined things in my spring-security.xml
file
<beans:bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.ShaPasswordEncoder"> </beans:bean> <beans:bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.ShaPasswordEncoder"> </beans:bean> <authentication-manager id="customerAuthenticationManager"> <authentication-provider user-service-ref="customerDetailsService"> <password-encoder hash="sha" /> </authentication-provider> </authentication-manager>
customerDetailsService
is our own implementation being provided to spring security.In my Java code while registering user, I am encoding provided password before adding password to Database something like
import org.springframework.security.authentication.encoding.PasswordEncoder; @Autowired private PasswordEncoder passwordEncoder; customerModel.setPassword(passwordEncoder.encodePassword(customer.getPwd(), null));
When I tried to debug my application, it seems Spring is calling AbstractUserDetailsAuthenticationProvider
authenticate method and when its performing additionalAuthenticationCheck with additionalAuthenticationChecks(user, (UsernamePasswordAuthenticationToken) authentication);
of DaoAuthenticationProvider
, it throwing Bad credential exception at following point
if (authentication.getCredentials() == null) { logger.debug("Authentication failed: no credentials provided"); throw new BadCredentialsException(messages.getMessage( "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"), userDetails); }
I am not sure where I am doing wrong and what needs to be done here to put things in right place, I already checked customer is there in database and password is encoded.
-12095153 0Is there any way to check a user has like a facebook page without permission request?
Only if your app is running as a page tab app on that Facebook page.
If so, the info is contained inside the signed_request
parameter.
following query works fine for delete the record based on current timestamp.
-26311715 0 Solving a difficult compilation issueDELETE FROM table WHERE datecolumn = date('Y-m-d h:i A'); //'2012-05-05 10:00PM'
Good day,
First up, I have a mac running Mavericks, and I am attempting to build PCL (Point Cloud Library) as part of ROS.
This is the command that fails:
cd /Users/X/ros_catkin_ws/build_isolated/pcl_ros && /Users/X/ros_catkin_ws/install_isolated/env.sh cmake -vd /Users/X/ros_catkin_ws/src/perception_pcl/pcl_ros -DCATKIN_DEVEL_PREFIX=/Users/X/ros_catkin_ws/devel_isolated/pcl_ros -DCMAKE_INSTALL_PREFIX=/Users/X/ros_catkin_ws/install_isolated -DCMAKE_BUILD_TYPE=Release
With:
CMake Error at /usr/local/share/pcl-1.8/PCLConfig.cmake:47 (message): simulation is required but glew was not found Call Stack (most recent call first): /usr/local/share/pcl-1.8/PCLConfig.cmake:500 (pcl_report_not_found) /usr/local/share/pcl-1.8/PCLConfig.cmake:663 (find_external_library) CMakeLists.txt:8 (find_package)
Now, I have done what I can to debug this. Looking up online, I notice this is happening due to the fact that in Mavericks, there is no longer the GLEW.framework https://github.com/PointCloudLibrary/pcl/issues/492
Hence, I installed it via brew, and yet I still get the same issue. Now, I'm thinking, perhaps cmake cannot find it, so I created my own cmake project, and attempted to add find_package(glew). It seems to have found the package here:
-- Found GLEW: /usr/local/include
Hence, I included /usr/local/include in my $PATH variable. Yet once again, it seems to fail with the same error. I am kind of at a lost here, and am not sure how to continue. I am speculating that in the command above, it seems that somehow the env.sh there seems to change the environmental variables such that it can't find glew.
Any thoughts?
EDIT: More absurdity. I create a CMake file and included find_package(PCL). It works perfectly. WTF? It even says it found glew
Found Glew: -framework GLEW;-framework Cocoa
How come it works in my Cmake file, but not in theirs? What might cause this
-27850563 0 Call new parameters on a jQuery slider depending on window sizeI am using bxslider.js to make a slider on my page. Since my site is responsive, the code I have allows different parameters for the slider depending on the size of the window. For example, when the window is over 768px the slider shows 2 slides. When it is under 768 it shows 1 slide and when it's under 480, the slider function stops completely. All this works fine. However it only works on load. I want it to work on resize too. I've played around the the window.resize function, but I don't have enough of a programing background to really know what I am doing or what the best way to do this is. Can anyone tell me how to get this to work both on load and on resize?
var sliderWidth = $('#testimonialSlider').width(); if ($(window).width() > 768) { doubleslider = $('#testimonialSlider').bxSlider({ minSlides: 2, maxSlides: 2, slideWidth: sliderWidth / 2, auto: false, moveSlides:2, autoHover:true, pager:true }); } else if ($(window).width() < 480) { singleslider.destroySlider(); } else{ singleslider = $('#testimonialSlider').bxSlider({ minSlides: 1, maxSlides: 1, slideWidth: sliderWidth, auto: false, moveSlides:1, autoHover:true, pager:true }); }
-6017914 0 There's no guarantee, but one thing you can do to protect yourself is hide the persistence implementation details behind a well-designed interface. It won't keep you from having to rewrite implementation if you switch, but it will isolate clients from the changes. You'll be able to test implementations separately and swap them in and out in a declarative fashion if you're using a dependency injection engine.
-27599571 0 white space below footerThere seems to be random white space after the footer at the bottom of the site. When I try to use inspect element, the white space doesn't seem to fall under any tags. It doesn't seem tied to any footer tags either as removing them didn't change anything.
I'm using Ryan Fait's Sticky Footer solution for my footer.
You can test it at: http://www.edmhunters.com/martin-garrix/
Any ideas what I'm doing wrong?
-27513335 0use this method this vl definitely work 100%.
- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath; { GalleryCell *cell1 = (GalleryCell*)[_resumeCollectionView cellForItemAtIndexPath:indexPath]; cell1= nil; }
-14085705 0 The message is just a warning. You can ignore it. If you're using Xcode, it won't even show you the warning in its Issue Navigator.
Rename your Bison input file to have a .ym
extension instead of a .y
extension. That tells Xcode that it's a grammar with Objective-C actions.
The version will start after you send it the first request (unless you use Managed VM - https://cloud.google.com/appengine/docs/managed-vms).
-29800656 0The break
keyword will always "break-out" of the current block of code. In this case, it is your inner for-loop.
I think you looking for the continue
keyword.
This immmediate thing that jumps out at me: this is wrong:
if (section._isInViewport) {
_isInViewport
requires you to pass the element in as an argument, like so:
if (_isInViewport(section)) {
You also don't need to check the event type in the event handler. Since you're only calling that on scroll, you already know the event type is a scroll event. Instead of thing:
if (event.type === 'scroll') { _getSections(); }
You want this:
_getSections();
-32915370 0 This is typically what I do when I want to convert many columns in a data.frame to a different data type:
convNames <- c("NY", "CHI", "LA", "ATL", "MIA") for(name in convNames) { city1[, name] <- as.numeric(as.character((city1[, name])) }
It's a nice two lines and you just have to add the names of whatever columns you want to coerce to the convNames vector to add a new column to the coercing loop below.
EDIT: Do to a factor issue, do the lapply method above.
-19539822 0 Exclude items of one list in another with different object data types, LINQ?I have two lists filled with their own data. lets say there are two models Human
and AnotherHuman
. Each model contains different fields, however they have some common fields like LastName, FirstName, Birthday, PersonalID
.
List<Human> humans = _unitOfWork.GetHumans(); List<AnotherHuman> anotherHumans = _unitofWork.GetAnotherHumans();
I would like to exclude the items from list anotherHumans
where LastName, FirstName, Birthday
are all equal to the corresponding fields of any item in list humans
.
However if any item in anotherHumans
list has PersonalID
and item in list humans
have the same PersonalID
, then it is enough to compare Human
with AnotherHuman
only by this PersonalID
, otherwise by LastName, FirstName and Birthday
.
I tried to create new list of dublicates and exclude it from anotherHumans
:
List<AnotherHuman> duplicates = new List<AnotherHuman>(); foreach(Human human in humans) { AnotherHuman newAnotherHuman = new AnotherHuman(); newAnotherHuman.LastName = human.LastName; newAnotherHuman.Name= human.Name; newAnotherHuman.Birthday= human.Birthday; duplicates.Add(human) } anotherHumans = anotherHumans.Except(duplicates).ToList();
But how can I compare PersonalID
from both lists if it presents (it is nullable). Is there any way to get rid from creating new instance of AnotherHuman and list of duplicates and use LINQ only?
Thanks in advance!
-12917807 0 Simple request using googleapis to freebaseI would like to query freebase, to get some basic information about a celebrity. For example, I would like to get the place of birth, and the gender of Madonna.
I achieved to get Madonna's friends by using:
https://www.googleapis.com/freebase/v1/mqlread?&query={"id":"/en/madonna","name":null,"type":"/base/popstra/celebrity","/base/popstra/celebrity/friendship":[{"participant":[]}]}
But, I'm understanding this request pretty badly. How can I change it to get the information I talked above ?
I was thinking about :
https://www.googleapis.com/freebase/v1/mqlread?&query={"id":"/en/madonna","name":null,"type":"/base/popstra/celebrity","/base/popstra/celebrity/gender":[{"gender":}], "/base/popstra/celebrity/place_of_birth":[{"place of birth":}]}
but it's not working ofc.
-12107726 0Either make the selector more specific:
ul li ul li:first-child{background-color:transparent}
Or add a class to the UL And select the first child there:
ul.nested li:first-child{background-color: #fff;} ... <li>one <ul class="nested"> <li>two</li> ...
http://jsfiddle.net/Kyle_Sevenoaks/fX9Gy/15/
-1857815 0You can't use REPLACE to create a comma delimited list for use in an IN
clause. To use that as-is, you'd have to utilize MySQL's Prepared Statements (effectively dynamic SQL) - creating the comma separated list first, and inserting that into the SQL query constructed as a string before executing it.
SELECT a.category_id, a.yyyymm, a.cat_balance_ytd FROM GL_VIEW_CAT_BALANCES a JOIN GL_OPTIONS o ON INSTR(o.detail2, a.category_id) AND o.option_id = 'GLREPFUNCJOB01' JOIN (SELECT b.category_id, b.gl_unique_id, MAX(b.yyyymm) 'yyyymm' FROM GL_REPCAT_BALSs b WHERE b.yyyymm <= 200910 GROUP BY b.category_id, b.gl_unique_id) x ON x.category_id = a.category_id AND x.gl_unique_id = a.unique_id AND x.yyyymm = a.yyyymm WHERE a.gl_id = '/JOB//9' AND a.fin_years_ago = 0
Here's an untested, possible non-dynamic SQL alternative, using FIND_IN_SET
:
SELECT a.category_id, a.yyyymm, a.cat_balance_ytd FROM GL_VIEW_CAT_BALANCES a JOIN (SELECT REPLACE(o.detail_2, ' ', ', ') 'detail2_csv' FROM GL_OPTIONS o WHERE o.option_id = 'GLREPFUNCJOB01') y ON FIND_IN_SET(a.category, y.detail2_csv) > 0 JOIN (SELECT b.category_id, b.gl_unique_id, MAX(b.yyyymm) 'yyyymm' FROM GL_REPCAT_BALSs b WHERE b.yyyymm <= 200910 GROUP BY b.category_id, b.gl_unique_id) x ON x.category_id = a.category_id AND x.gl_unique_id = a.unique_id AND x.yyyymm = a.yyyymm WHERE a.gl_id = '/JOB//9' AND a.fin_years_ago = 0
-11582627 1 Python get micro time from certain date I was browsing the Python guide and some search machines for a few hours now, but I can't really find an answer to my question.
I am writing a switch where only certain files are chosen to be in the a file_list (list[]) when they are modified after a given date.
In my loop I do the following code to get its micro time:
file_time = os.path.getmtime(path + file_name)
This returns me a nice micro time, like this: 1342715246.0
Now I want to compare if that time is after a certain date-time I give up. So for testing purposes, I used 1790:01:01 00:00:00.
# Preset (outside the class/object) start_time = '1970-01-01 00:00:00' start_time = datetime.datetime.strptime(start_time, '%Y-%m-%d %H:%M:%S') start_time = start_time.strftime("%Y-%m-%d %H:%M:%S") # In my Method this check makes sure I only append files to the list # that are modified after the given date if file_time > self.start_time: file_list.append(file_name)
Of course this does not work, haha :P. What I'm aiming for is to make a micro time format from a custom date. I can only find ClassMethods online that make micro time formats from the current date.
-4317703 0Seems it can't be done with the C preprocessor, at least the gcc docs states it bluntly:
-5326377 0There is no way to convert a macro argument into a character constant.
Using a bit of psychic debugging, I'm going to guess that the strings in your application are pooled in a read-only section.
It's possible that the CreateSysWindowsEx is attempting to write to the memory passed in for the window class or title. That would explain why the calls work when allocated on the heap (SysAllocString) but not when used as constants.
The easiest way to investigate this is to use a low level debugger like windbg - it should break into the debugger at the point where the access violation occurs which should help figure out the problem. Don't use Visual Studio, it has a nasty habit of being helpful and hiding first chance exceptions.
Another thing to try is to enable appverifier on your application - it's possible that it may show something.
-3893509 0My only current solution uses reflection to build the string
or paths for the .Expand
method.
foo_entitiesctx = new foo_entities(new Uri("http://url/FooService.svc/")); ctx.MergeOption = MergeOption.AppendOnly; var collections = from pi in typeof(TestResult).GetProperties() where IsSubclassOfRawGenericCollection(pi.PropertyType) select pi.Name; var things = ctx.Things.Expand(string.Join(",", collections)); foreach (var item in things) { foreach (var child in item.ChildCollectionProperty1) { //do thing } }
(The IsSubclassOfRawGenericCollection
method is a wrapper around the IsSubclassOfRawGeneric
method from Jared Par on SO)
something like this? http://jsfiddle.net/93zb8Lzs/6/
<img src="https://www.google.at/images/srpr/logo11w.png" width="368" height="138" alt="Logo" /> <!-- Nvigationselemente --> <div class="nav"> </div> img { display:block; margin:auto; }
-29633777 0 Syntax Error OledbException delete statement I can't fugure out what my syntax error is here. Anyone spot it? Or am I going about this all wrong?
Dim myCommand As New OleDb.OleDbCommand("delete * from Team where intPlayerNo='" & txtUniformNo.Text & "'_ strFirstName='" & txtFirstName.Text & "'_ strLastName='" & txtLastName.Text & "'_ strParentName='" & txtParent.Text & "'_ strAddress='" & txtAddress.Text & "'_ strCity='" & txtCity.Text & "'_ strState='" & txtState.Text & "'_ strZipCode='" & txtZip.Text & "'_ strPhone='" & txtPhone.Text & "'_ intAge='" & txtAge.Text & "'", myConnection)
-30484473 0 The error can occur only if there exists a document in the database with some _id
, say ID1
, and you are trying to insert a new document which has ID1
as its value for _id
field.
This can be because of the following:
_id
_id
If the value of _id
field is not critical for you, you can just remove that attribute from your objects read from CSV right in your JavaScript code using delete
.
Otherwise, you have a conflict, and need to decide what you want to do with duplicate _id
documents. If you are ok with overwriting, you can achieve that by having {upsert: 1}
option, which will update the document with new values in case if there is one existing with the same _id
.
You're passing self
twice in the super call. The call to post
is a standard method call, so self is always included automatically. It should be:
super(ClassA, self).post(request, *args, **kwargs)
-2319872 0 Many folks, including Zend, tell programmers to use camel case, but personally I used underscores as word separators for variable names, array keys, class names and function names. Also, all lowercase, except for class names, where I will use capitals.
For example:
class News { private $title; private $summary; private $content; function get_title() { return $this->title; } } $news = new News;
-15356416 0 After I install Wampserver2, while opening phpmyadmin i got error Firefox can't establish a connection to the server at localhost After I install Wampserver2,
Apache > Service > Test port 80 : Your port 80 is not actually used. also tried Apache > Service > install service : But Apache > Service > Start/resume service is still disabled.
C:\WINDOWS\system32\drivers\etc\host file has the statement 127.0.0.1 localhost
getDefaultSharedPreferences(Context) in the type PreferenceManager is not applicable for the arguments (DBTools)
Because getDefaultSharedPreferences
takes Context object as parameters instead of DBTools.this
or any other class context.
To fix this issue create a private Context object as assign value in object inside DBTools
class constructor in which you are passing context when creating object of DBTools
class:
private Context mContext; public DBTools(Context applicationContext){ super(applicationContext, "contactbook.db", null, 1); this.mContext=applicationContext; }
Now, use mContext
as parameter to getDefaultSharedPreferences
method:
SharedPreferences sp = PreferenceManager .getDefaultSharedPreferences(mContext);
-14504560 0 What you are understanding is correct. Here is an example:
string* str_rptr = new string("hello"); string* str2_rptr = str_rptr; str2_rptr->replace(0,5,"goodbye"); std::cout << *str_rptr << std::endl;
The output of this fragment would print "goodbye" rather than "hello". After the "perfect int" example you gave, this code:
y = 400; std::cout << x << std::endl;
will print out "200". The important point is that copying a variable does not prevent changes to one from changing the other.
-33725788 0 C# Ask user another inputI am creating a soundDex application and I need to ask the user for a second name after they have inputted the first one. I also want "error no input" if the user does not input a second name. How would I do this within my soundDex?
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SoundDexFinal { class Program { static void Main(string[] args) { string input = null; bool good = false; Console.WriteLine("SoundDex is a phonetic algorithm which allows a user to encode words which sound the same into digits." + "The program allows the user essentially to enter two names and get an encoded value."); while (!good) // while the boolean is true { Console.WriteLine("Please enter a name -> "); // asks user for an input input = Console.ReadLine(); // Make sure the user entered something good = !string.IsNullOrEmpty(input); // if user enters a string which is null or empty if (!good) // if boolean is true Console.WriteLine("Error! No input."); // displays an error to the user } soundex soundex = new soundex(); // sets new instance variable and assigns from the method Console.WriteLine(soundex.GetSoundex(input)); // gets the method prior to whatever the user enters Console.ReadLine(); // reads the users input } class soundex { public string GetSoundex(string value) { value = value.ToUpper(); // capitalises the string StringBuilder soundex = new StringBuilder(); // Stringbuilder holds the soundex code or digits foreach (char ch in value) // gets the individual chars via a foreach which loops through the chars { if (char.IsLetter(ch)) AddChar(soundex, ch); // When a letter is found this will then add a char } // soundex in (parameter) is for adding the soundex code or digits return soundex.ToString(); //return the value which is then converted into a .String() } private void AddChar(StringBuilder soundex, char character) //encodes letter as soundex char and this then gets appended to the code { string code = GetSoundexValue(character); if (soundex.Length == 0 || code != soundex[soundex.Length - 1].ToString()) soundex.Append(code); } private string GetSoundexValue(char ch) { string chString = ch.ToString(); if ("BFPV".Contains(chString)) // converts this string into a value returned as '1' return "1"; else if ("CGJKQSXZ".Contains(chString)) // converts this string into a value returned as '2' return "2"; else if ("DT".Contains(chString)) // converts this string into a value returned as '3' return "3"; else if ("L".Contains(chString)) // converts this string into a value returned as '4' return "4"; else if ("MN".Contains(chString)) // converts this string into a value returned as '5' return "5"; else if ("R".Contains(chString)) // converts this string into a value returned as '6' return "6"; else return ""; // if it can't do any of these conversions then return nothing } } } }
-1724872 0 The problem was related to the version of the NVelocity assembly I was using.
-16746227 0 Generate a random number from another numberIn JavaScript, is it possible to generate a random number from another number?
I'm trying to implement a predictable random number generator for one of my fractal terrain generators. I already know that it's possible to generate a random number using Math.random(), but I want to create a random number generator that produces exactly one output for every input. (For example, predictableRandomGenerator(1)
would always produce the same result, which would not necessarily be the same as the input.)
So is it possible to generate a random number from another number, where the output is always the same for each input?
-32773409 0Here's a quick function:
myfun <- function(df){ z <- colSums(df) matrix(rowSums(expand.grid(z, z)), ncol = ncol(df)) }
It first takes the colSums
as z
. Then we use expand.grid
to take all combinations of z
to z
and takes the rowSums
. The output is coerced to a matrix with the correct number of columns.
myfun(df) [,1] [,2] [,3] [,4] [1,] 16 17 19 13 [2,] 17 18 20 14 [3,] 19 20 22 16 [4,] 13 14 16 10
-3791466 0 How do I know if the user clicks the "back" button? I'm using anchors for dealing with unique urls for an ajaxy website. However, I want to reload the content when the user hits the Browser's "back" button so the contents always matches the url.
How can I achieve this? Is there a jQuery event triggering when user clicks "Back"?
-5737426 0RabbitMQ should fit your bill. The server is free and ready to use. You just need a client side to connect, push/send out message and get/pull notified message
Server: http://www.rabbitmq.com/download.html Do a google for client or implement yourself
Cheers
-13673443 0OpenCV is bar-none the defacto computer vision library. It is packed full of functions to make your life easier.
With respect to image stabilization, Stackoverflow has answered possible approaches to this. Most of the time, you want to extract robust local feature descriptors and use them to perform registration on consecutive image frames.
-25982811 0 "No XLIFF language files were found." After updating to MAT 3.1I have a Windows Store project that I've been developing for quite some time. The Multilingual App Toolkit has been amazing so far. Recently I updated to version 3.1. Unfortunately, this caused the build process to not process my .xlf
files that I've been using for a year now.
Based on this entry I took a look at my project file. The resources were defined similarly to how the blog entry suggested they should be. Similar to this:
<ItemGroup> <XliffResource Include="MultilingualResources\MyProject.WinRT_ar.xlf" /> <XliffResource Include="MultilingualResources\MyProject.WinRT_bg-BG.xlf" /> <XliffResource Include="MultilingualResources\MyProject.WinRT_ca-ES.xlf" /> ...
I tried many things, including adding <Generator>
tags. None of it seemed to be working. How can I get the project to see my .xlf
s?
I have a SaaS platform that I am working on; written in PHP and using a MySQL database (using the PHP PDO class).
The application is already functional and I have decided to use a separate database for each instance.
One of the reasons for using multiple databases is to ensure that client data is separated (and hopefully secure). This also allows us to easily transfer their instance into the on-premise version.
Security is always something that I worry about. I want to ensure this system is as secure as possible before it goes live.
Currently we are using a single MySQL username & password that has access to every database (on that specific MySQL Farm).
Theoretically if there was a security breach then the attacker might be able to access a different database (username & password is unset after the PDO/Database connection is made, but they might be able to run a query such as "use databaseB").
Is this something that I should be concerned about? For example a SaaS platform that simply uses database partitioning is already less secure as a simple SQL error could expose client data.
I've already started looking into using different database usernames & passwords, but it does add to the complexity of the SaaS platform, and keeping things simple is always a good idea.
Thanks!
I have decided to go with different usernames and password for each instance.
This is another layer of security and that cannot hurt.
-7180829 0 Generate Multiples XML with PHPI have a PHP script that is generating an XML file. He reads the contents of the subfolders in the folder X, and generates only one XML with all subfolders and their contents. I'm wanting the same script generates an XML for each subfolder to find it, would someone help me?
<?php $sortorder = $_REQUEST['sortorder']; $indir = '../galleries'; $files = opendir($indir); $outxml = <'xml version=\'1.0\' encoding=\'utf-8\'?>\n\n'; $outxml .= '<galleries>\n\n'; while ($file = readdir($files)) { if(is_dir($indir.'/'.$file)){ if ($file != '.' && $file != '..') { $tmp_outxml[] = $file; } } } if ($sortorder == 'date') { foreach ($tmp_outxml as $k => $v) { $modified = filemtime ($indir.'/'.$v); $moddate[$k] = $modified; } array_multisort ($moddate, $tmp_outxml); } else if ($sortorder == 'random') { shuffle ($tmp_outxml); } else { sort ($tmp_outxml); } foreach ($tmp_outxml as $v) { $outxml .= get_folder_xml($indir.'/'.$v,$v); } $outxml .= "</galleries>"; closedir($files); $fp = fopen('../xml/gallery.xml', 'w'); fwrite($fp, $outxml); fclose($fp); function get_folder_xml($imageDir,$title) { $extensions = array('.jpg', '.jpeg', '.JPG','.JPEG','.gif','.GIF','.swf','.SWF'); $output = ''; if($folder = opendir($imageDir)) { $filenames=array(); while (false !== ($file = readdir($folder))) { $dot = strrchr($file, '.'); if(in_array($dot, $extensions)) { array_push($filenames, $file); } } $spaceTitle = str_replace('_',' ',$title); $newPath = str_replace('../','',$imageDir); $output .= '<gallery>\n'; $output .= '<title>$spaceTitle</title>\n'; $output .= ' <images>\n'; foreach ($filenames as $source) { $imageName = str_replace('mainThumb_','',$source); $finalName = str_replace('_',' ',$imageName); $imageName = str_replace($extensions,'',$finalName); $output .= '\t <image src=\'$newPath/$source\' thumb=\'$newPath/thumbs/$source\'>$imageName</image>\n'; } $output .= ' </images>\n'; $output .= '</gallery>\n\n'; return $output; closedir($folder); } } ?>
i think i need to modify on this line, but i dont know how...
$fp = fopen('../xml/gallery.xml', 'w'); fwrite($fp, $outxml); fclose($fp);
ty for help!!
-28100899 0 how do i fit unique curves on each unique plot in a for loopI have written this code (see below) for my data frame kleaf.df
to combine multiple plots of variable press_mV
with each individual plot for unique ID
I need some help fitting curves to my plots. when i run this code i get the same fitted curve (the curve fitted for the first plot) on ALL the plots where i want each unique fitted curve on each unique plot.
thanks in advance for any help given
f <- function(t,a,b) {a * exp(b * t)} par(mfrow = c(5, 8), mar = c(1,1,1,1), srt = 0, oma = c(1,6,5,1)) for (i in unique(kleaf.df$ID)) { d <- subset(kleaf.df, kleaf.df$ID == i) plot(c(1:length(d$press_mV)),d$press_mV) #----tp:turning point. the last maximum value before the values start to decrease tp <- tail(which( d$press_mV == max(d$press_mV) ),1) #----set the end points(A,B) to fit the curve to A <- tp+5 B <- A+20 #----t = time, p = press_mV # n.b:shift by 5 accomadate for the time before attachment t <- A:B+5 p <- d$press_mV[A:B] fit <- nls(p ~ f(t,a,b), start = c(a=d$press_mV[A], b=-0.01)) #----draw a curve on plot using the above coefficents curve(f(x, a=co[1], b=co[2]), add = TRUE, col="green", lwd=2) }
-7542409 0 C# Linq Expressions - Use String functions for all EF4 class attributes I have this EF class called COMPONENT
public partial class COMPONENT : INotifyPropertyChanging, INotifyPropertyChanged { private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty); private int _ID; private string _NAME; private string _BRAND; private string _IMAGE; private System.Nullable<double> _PRICE; private string _OBSERVATION; private int _COMPONENT_TYPE_ID; private string _USERNAME; private System.DateTime _CREATE_DATE;
I want to treat all it's attributes like strings in the predicates of a generic query function using LinqKit PredicateBuilder.
The function is something like this:
public static List<TEntity> getResults<TEntity>(IList<PredicateFilter> conditions) where TEntity: class { var predicate = PredicateBuilder.True<TEntity>(); foreach (var condition in conditions) { var lambda = createPredicateLambda<TEntity>(condition); predicate = predicate.And(lambda); } DataClassesDataContext db = new DataClassesDataContext(); var components = from com in db.GetTable<TEntity>().Where(predicate) select com; return components.AsExpandable().ToList(); }
The class PredicateFilter look like this:
public class PredicateFilter { public string attribute; public string logicOperator; public object value; }
The problem became in the function createPredicateLambda(condition). This function returns a Expression>. In it's body calls another function called createLambdaExpression
createLambdaExpression<TEntity>(string methodOperator, ParameterExpression param, MemberExpression attribute, ConstantExpression value) where TEntity : class
This function, in certain conditions, try to generate a expression where the attribute contains the value (no matter the Type of both the parameter) I want to do something like this but i don't see the solution:
return Expression.Lambda<Func<TEntity, bool>>(Expression.Contains(Expression.Convert(attribute,typeof(string)),value),param);
Obviously this wont's compile (The Expression.Convert it's not implemented). However, if i use
Expression.Lambda<Func<TEntity, bool>>(Expression.Equal(Expression.Convert(attribute,typeof(string)),value),param);
i get an exception in runtime: "The binary operator Equal is not defined for the types 'System.Int32' and 'System.String'".
Like i said later, i want to compare different data types or use (in certain conditions) the method String.Contains in all the data types. I've tried without any luck... Anyone knows if this can be done?
Thanks in advance!
-1389139 0Compiling MSIL to Native Code Ngen.exe
SUMMARY:
The runtime supplies another mode of compilation called install-time code generation. The install-time code generation mode converts MSIL to native code just as the regular JIT compiler does, but it converts larger units of code at a time, storing the resulting native code for use when the assembly is subsequently loaded and run. When using install-time code generation, the entire assembly that is being installed is converted into native code, taking into account what is known about other assemblies that are already installed.
Take look at - How to compile a .NET application to native code?
-3021636 0 how can i execute large mysql queries fastI have 4 mysql tables and have a single query with JOIN on multiple tables and I am requesting it via jquery ajax, but it takes much too long, from about 1-3 minutes while I want to execute them on average 2-5 seconds.
Is there any special way to execute the queries fast?
-35044770 0I ended up using some jquery in my change events.
'change .edit-status': function(event, template){ var status = event.target.value; if (status === "UnAssigned") { $(".edit-assigned-to").val(""); } return false; }, 'change .edit-assigned-to': function(event, template){ var assignedTo = event.target.value; if (!template.data.assignedTo && assignedTo !== "") { $(".edit-status").val("Not Started"); } if (assignedTo === "") { $(".edit-status").val("UnAssigned"); } return false; }
I'm not sure if there are better approaches or pitfalls to this solution, but it seems to be meeting my needs.
-10788749 0The NSMutableSet
class declares the programmatic interface to an object that manages a mutable set of objects. NSMutableSet
provides support for the mathematical concept of a set.
NSMutableSet
is “toll-free bridged” with its Core Foundation counterpart, CFMutableSetRef
.
Actually, I still don't know, why code works as described above. But I have found acceptable method to solve task other way.
Looks like "put a needle into egg, egg into duck, duck into rabbit": ScrollView must contain a ListView component which has a corresponding ListModel and a custom component should act as delegate. Only with ListModel I've got correct automatic scrolling and relative emplacement support.
ScrollView { id: id_scrollView anchors.fill: parent objectName: "ScrollView" frameVisible: true highlightOnFocus: true style: ScrollViewStyle { transientScrollBars: true handle: Item { implicitWidth: 14 implicitHeight: 26 Rectangle { color: "#424246" anchors.fill: parent anchors.topMargin: 6 anchors.leftMargin: 4 anchors.rightMargin: 4 anchors.bottomMargin: 6 } } scrollBarBackground: Item { implicitWidth: 14 implicitHeight: 26 } } ListView { id: id_listView objectName: "ListView" anchors.top: parent.top anchors.left: parent.left anchors.right: parent.right anchors.rightMargin: 11 flickableDirection: Flickable.VerticalFlick boundsBehavior: Flickable.StopAtBounds delegate: view_component model: id_listModel ListModel { id :id_listModel objectName: "ListModel" } //delegate: View_item2.Item Component { id: view_component View_item2 { objectName: name } } }
-30023758 0 Trailing space while using "headertemplate" in asp gridview I have a gridview which is bounded as
<asp:GridView runat="server" ID="gvShipDetails" AutoGenerateColumns="false" OnRowDataBound="gvShipDetails_RowDataBound"> <Columns> <asp:TemplateField> <HeaderTemplate> Ship name <br /> <asp:TextBox class="search_textbox" runat="server" BorderStyle="None" Width="100%"> </asp:TextBox> </HeaderTemplate> <ItemTemplate> <%#Eval("VesselName")%> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView>
The problem is the finally rendered html table td is rendered as
<td> sample vessel name </td>
A lot of spaces inside td.How is this possible.
If I replace this bound code as
<asp:BoundField HeaderText="vessel name" DataField="vesselname" />
Then html is renderd as <td>sample vessel name<td>
Why is it so? I wanted to use headertemplate and i wanted to avoid these trailing spaces. How to do it
Any help will be appreciated
-13211993 0 Estimating the variance of eigenvalues of sample covariance matrices in MatlabI am trying to investigate the statistical variance of the eigenvalues of sample covariance matrices using Matlab. To clarify, each sample covariance matrix is constructed from a finite number of vector snapshots (afflicted with random white Gaussian noise). Then, over a large number of trials, a large number of such matrices are generated and eigendecomposed in order to estimate the theoretical statistics of the eigenvalues.
According to several sources (see, for example, [1, Eq.3] and [2, Eq.11]), the variance of each sample eigenvalue should be equal to that theoretical eigenvalue squared, divided by the number of vector snapshots used for each covariance matrix. However, the results I get from Matlab aren't even close.
Is this an issue with my code? With Matlab? (I've never had such trouble working on similar problems).
Here's a very simple example:
% Data vector length Lvec = 5; % Number of snapshots per sample covariance matrix N = 200; % Number of simulation trials Ntrials = 10000; % Noise variance sigma2 = 10; % Theoretical covariance matrix Rnn_th = sigma2*eye(Lvec); % Theoretical eigenvalues (should all be sigma2) lambda_th = sort(eig(Rnn_th),'descend'); lambda = zeros(Lvec,Ntrials); for trial = 1:Ntrials % Generate new (complex) white Gaussian noise data n = sqrt(sigma2/2)*(randn(Lvec,N) + 1j*randn(Lvec,N)); % Sample covariance matrix Rnn = n*n'/N; % Save sample eigenvalues lambda(:,trial) = sort(eig(Rnn),'descend'); end % Estimated eigenvalue covariance matrix b = lambda - lambda_th(:,ones(1,Ntrials)); Rbb = b*b'/Ntrials % Predicted (approximate) theoretical result Rbb_th_approx = diag(lambda_th.^2/N)
References:
[1] Friedlander, B.; Weiss, A.J.; , "On the second-order statistics of the eigenvectors of sample covariance matrices," Signal Processing, IEEE Transactions on , vol.46, no.11, pp.3136-3139, Nov 1998 [2] Kaveh, M.; Barabell, A.; , "The statistical performance of the MUSIC and the minimum-norm algorithms in resolving plane waves in noise," Acoustics, Speech and Signal Processing, IEEE Transactions on , vol.34, no.2, pp. 331- 341, Apr 1986
-3879203 0 Tab focus granting eventI need to capture tab focus granting event in Firefox browser. Is there any type of listener implement for this event?
-24045360 0Think about what the compiler would have to do to catch the problem you're demonstrating. It would have to look at all callers of test1 to see whether they're passing it a local. Perhaps easy enough, but what if you insert more and more intermediate functions?
int & test1(int & x) { return x; } int & test2(int & x) { return test1(x); } int & test3() { int x = 0; return test2(x); } int main(void){ int & r = test3(); return r; }
The compiler would have to look not only at all callers of test1, but then also all callers of test2. It would also have to work through test2 (imagine that it's more complex than the example here) to see whether it's passing any of its own locals to test1. Extrapolate that to a truly complex piece of code--keeping track of that sort of thing would be prohibitively complex. The compiler can only do so much to protect us from ourselves.
-29159691 0There are 2 delegate methods of FBLoginView
-(void)loginViewShowingLoggedOutUser:(FBLoginView *)loginView -(void)loginViewShowingLoggedInUser:(FBLoginView *)loginView
The first method would inform you whether the user is logged out and the second method would inform you whether the user is logged in and you can perform your action on the basis of that.
For getting the image of the Profile picture u can use users id or objectID from this delegate method which contains all the user information.
-(void)loginViewFetchedUserInfo:(FBLoginView *)loginView user:(id<FBGraphUser>)user { NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://graph.facebook.com/%@/picture?type=normal",user.id]]; NSData *data = [NSData dataWithContentsOfURL:url]; UIImage *profileImage = [UIImage imageWithData:data]; }
where the profileImage would contain the user profile Image and you can use that image to show on your custom button.
-29595534 0First of all, your question is too-broad, and you haven't provided much info, but if you make vague questions, you'll get vague answers, so here we go.
I also developed an app with Laravel 5, and had a pagination with next / previous links. I used AJAX to make a call to the next page, and return the HTML into the current page.
$(document).on("click", ".pagination a", function(e) { e.preventDefault(); url = $(this).attr('href') + " #search_results-listing"; $("#search_results").load(url, function() { setGetParameter('page', '2'); }); });
-22882485 0 Plot two conditions in one plot i'm sorry to ask such a dumb question, but i can't find an answer ...
So i have this table called : "linearsep" :
color x y 1 red 1 1 2 red 1 3 3 red 3 3 4 red 2 4 5 blue 4 1 6 blue 6 3 7 blue 2 -2 8 blue 6 -1
each line corresponds to a points (1,1 ; 1,3 etc...) , I just want to plot the ''red'' points in red , and the "blue" points in blue.
I know this is pretty dumb : but i just can't find a way to get a vector with the first four line.
I thought it was something like that:
plot(linearsep$color~x, linearsep$color~y)
but obviously it doesn't work ... I've tested some stuff with ggplot:
ggplot(data=a, + aes(x=x, y=y, colour=color)) + geom_point()
Which works, but seems like a 'hack' , how can i just get the vector i want ? Someone could please help me ... Again sorry for such a dumb question
-18644597 0I'm an FPDF noob myself but have you tried the AcceptPageBreak function?
Something like this (copied from fpdf website):
function AcceptPageBreak() { // Method accepting or not automatic page break if($this->col<2) { // Go to next column $this->SetCol($this->col+1); // Set ordinate to top $this->SetY($this->y0); // Keep on page return false; } else { // Go back to first column $this->SetCol(0); // Page break return true; } }
As a reference, the fpdf tutorials are really helpful. I suspect this one in particular would help you for what you're doing.
-34195319 0 "Warning:mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in?"And after searching I rectified my code as belowDisplayLandlord PHP: I couldn't get the output.The query is not fetching the result
<?php include("dbconfig.php"); ?> <?php $query = "SELECT * FROM rmuruge4_landlord"; $result = mysqli_query(mysqli_connect(),$query); if ($result === false) {die(mysqli_error(mysqli_connect())); } echo "<div class='bs-example'>"; echo "<table class='table table-striped'>"; echo "<tr><th>LLID</th><th>LName</th><th>Phone</th><th>Address</th></td>"; while($row = mysqli_fetch_array($result)){ echo "<tr><td>" . $row['LLID'] . "</td><td >" . $row['LName'] . "</td><td >". $row['Phone'] . "</td><td >" . $row['Address'] . "</td></tr>"; } echo "</table>"; echo "</div>"; mysqli_close(mysqli_connect()); ?> dbconfig.php: Connection is successful
-25811244 0 These redirects follow your route configuration. The default route is {siteUrl}/{controller}/{action}, which is why when you give it the "Index" action and the "Home" controller, you get the URL you're seeing.
You need to specify a new route similar to this:
MapRoute("CustomRoute", "MyApp/{controller}/{action}";
You can then redirect to it like this:
RedirectToRoute("CustomRoute", new {Controller = "Home", Action = "Index" });
EDIT to clarify for the comments -
It is also possible to solve this using IIS to make MyApp an application. This is the right solution only if MyApp is the only value you ever want at the beginning of your route for this site. If, for example, you sometimes need MyApp/{controller}/{action} and other times you need OtherSubfolder/{controller}/{action}, you need to use the routes as I have outlined above (or use areas) instead of just updating IIS.
I am assuming you want the solution using MVC, so that is what is here, but you should also consider the IIS application if that's the right solution for you.
-7946771 0 UIDocumentInteractionController or QLPreviewController can't zoom PDF on iOS5?I use QLPreviewController to view PDF files in one of my apps. However, ever since iOS5, users can no longer pinch to zoom in/out of the PDF. This is terrible for iPhone users, as they can't read anything.
I have also tried using UIDocumentInteractionController but have had the same problem.
Anyone know what's going on with this?
-29846864 0 Change the app-name sent by docker's syslog driverI'm using Papertrail to collect my Docker container's logs. Do to that, I used the syslog driver when I created the container:
sudo docker run --name my_container --log-driver=syslog ...
... and added the following line to my /etc/rsyslog.conf
*.* @logsXXX.papertrailapp.com:YYYY
At the end, I get on Papertrail logs like this:
Apr 24 13:41:55 ip-10-1-1-86 docker/3b00635360e6: 10.0.0.5 - - [24/Apr/2015:11:41:57 +0000] "GET /healthcheck HTTP/1.1" 200 0 "-" "" "-"
The problem is that the app-name (see syslog RFC) is docker/container_id
I would rather have the container name (or host). But I don't know how to do. I tried to set a specific hostname to my container like below, but it didn't work better:
sudo docker run --name my_container -h my_container --log-driver=syslog ...
-29411338 0 How to handle OVER_QUERY_LIMIT I am using google maps to draw the path among various location which are stored in database.
While passing 15 geopoints(anything more than 10) am getting status as OVER_QUERY_LIMIT.
I understand that we need to give some milliseconds of time gap when we pass more than 10 geopoints per seconds.
My question is HOW TO DO THAT..Where to add sleep() or setTimeout() or any other time delay code
I've tried all,maximum all possibilities provided at SO but failed.As because they are just saying give some time gap between request but how to do that?
Code Snippet:
var markers = [ { "title": 'abc', "lat": '17.5061925', "lng": '78.5049901', "description": '1' }, { "title": 'abc', "lat": '17.50165', "lng": '78.5139204', "description": '2' }, . . . . . { "title": 'abc', "lat": '17.4166067', "lng": '78.4853992', "description": '15' } ]; var map; var mapOptions = { center: new google.maps.LatLng(markers[0].lat, markers[0].lng), zoom: 15 , mapTypeId: google.maps.MapTypeId.ROADMAP }; var path = new google.maps.MVCArray(); var service = new google.maps.DirectionsService(); var infoWindow = new google.maps.InfoWindow(); var map = new google.maps.Map(document.getElementById("map"), mapOptions); var poly = new google.maps.Polyline({ map: map, strokeColor: '#000000' }); var lat_lng = new Array(); for (var i = 0; i <= markers.length-1; i++) { var src = new google.maps.LatLng(markers[i].lat, markers[i].lng); var des = new google.maps.LatLng(markers[i+1].lat, markers[i+1].lng); poly.setPath(path); service.route({ origin: src, destination: des, travelMode: google.maps.DirectionsTravelMode.DRIVING }, function (result, status) { if (status == google.maps.DirectionsStatus.OK) { for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) { path.push(result.routes[0].overview_path[i]); } } else{ if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) { document.getElementById('status').innerHTML +="request failed:"+status+"<br>"; } } }); } });
RESULT MAP(OVER_QUERY_LIMIT):
I got this hover card and I want to display it inside a sub-menu. It works int the header, but somehow the hover effect does not kick in when inside the sub-menu "with:$root.chosenMenu"-bindings.
This is my code:
HTML:
<div> <span class="previewCard"> <label class="hovercardName" data-bind="text: displayName"></label> <span class="hovercardDetails"> <span data-bind="text: miniBio"></span>.<br/> <a data-bind="attr: { href: webpage, title: webpage }, text: webpage">My blog</a> </span> </span> <br/><br/> <div class="wysClear wysLeft buttonRow"> <a href="#pid1" data-bind="click: function(){$root.chosenMenu('a');return false;}">Panel A</a> <a href="#pid2" data-bind="click: function(){$root.chosenMenu('b');return false;}">Panel B</a> </div> </div> <hr/> <div data-bind="with: $root.chosenMenu"> <div id="pid1" data-bind="visible: $root.chosenMenu() === 'a'"> panel A: <br/><br/> <span class="previewCard"> <label class="hovercardName" data-bind="text: $root.displayName"></label> <span class="hovercardDetails"> <span data-bind="text: $root.miniBio"></span>.<br/> <a data-bind="attr: { href: $root.webpage, title: $root.webpage }, text: $root.webpage">My blog</a> </span> </span> </div> <div id="pid2" data-bind="visible: $root.chosenMenu() === 'b'"> panel B: <br/><br/> <span class="previewCard"> <label class="hovercardName" data-bind="text: $root.displayName"></label> <span class="hovercardDetails"> <span data-bind="text: $root.miniBio"></span>.<br/> <a data-bind="attr: { href: $root.webpage, title: $root.webpage }, text: $root.webpage">My blog</a> </span> </span> </div> </div>
Javascript:
viewModel = function(){ var self = this; self.chosenMenu = ko.observable(); self.displayName = ko.observable("Asle G"); self.miniBio = ko.observable("Everywhere we go - there you are!"); self.webpage = ko.observable("http://blog.a-changing.com") }; ko.applyBindings( new viewModel() ); // hovercard $(".previewCard").hover(function() { $(this).find(".hovercardDetails").stop(true, true).fadeIn(); }, function() { $(this).find(".hovercardDetails").stop(true, true).fadeOut(); });
CSS:
.previewCard { position:relative; } .hovercardName { font-weight:bold; position:relative; z-index:100; /*greater than details, to still appear in card*/ } .hovercardDetails { background:#fff ; border:solid 1px #ddd; position:absolute ; width:300px; left:-10px; top:-10px; z-index:50; /*less than name*/ padding:2em 10px 10px; /*leave enough padding on top for the name*/ display:none; }
Fiddle: http://jsfiddle.net/AsleG/jb6b61oh/
-24731408 0Filed an issue at jboss jira and the issue is fixed in upcoming release.
A work-around currently is to have the following in your jboss-web.xml:
<?xml version="1.0"?> <jboss-web> <session-config> <cookie-config> <path>/</path> </cookie-config> </session-config> </jboss-web> <xml>
-34895249 0 If you must use a loop, you can do something like
uint64_t text = 0; for (int i = 15; i >= 0; --i) { text <<= 4; text |= a[i] & 0x0f; // Masking in case a[i] have more than the lowest four bits set }
-27795202 0 It's not flushed at this moment, changes kept in memory for a while. If you need to force Grails to update DB exactly at this moment, add flush: true
parameter:
person.save(flush: true)
-32102014 0 Yeah, You can use SHOW CREATE TABLE to display the CREATE VIEW statement that created a view.
Link for reference: Hive CREATE VIEW
-16393853 0You don't initialize array
and s
in the copy constructor.
Here is the problem. I have a radiobutton group (two radiobuttons).
These guys are initialy disabled. When the user clicks a checkbox, I dynamically enable radiobuttons in javascript by setting rbtn.disabled = false;
and doing the same for it's parent (span element) so it correctly works in IE. The problem is that these dynamically enabled radiobuttons are not returned on postback (I see rbtn.Checked == false
on serverside and request.form
does not contain proper value).
Why is this happening? Is there another fix except for a workaround with hidden fields?
Expected answer decribes post-back policy, why/how decides which fields are included in postback and fix to this problem.
-21883693 0Try This:
int maxNo = 4; //you can change this no and logic works till 9 comboboxes void clearPreceding(ComboBox cmbBox) { int cmbBoxNo = Convert.ToInt32(cmbBox.Name.Substring(cmbBox.Name.Length - 1)); for (int i = cmbBoxNo; i <= maxNo; i++) { ((ComboBox)this.Controls.Find("comboBox" + i, true)[0]).Text = ""; } }
You can Subscribe to One EventHandler for all Combobox's SelectedIndexChanges
Event as below:
comboBox1.SelectedIndexChanged += AllCombobox_SelectedIndexChanged; comboBox2.SelectedIndexChanged += AllCombobox_SelectedIndexChanged; comboBox3.SelectedIndexChanged += AllCombobox_SelectedIndexChanged; comboBox4.SelectedIndexChanged += AllCombobox_SelectedIndexChanged;
and the EventHandler is:
private void AllCombobox_SelectedIndexChanged(object sender, EventArgs e) { clearPreceding((ComboBox)sender); }
Complete Code:
public partial class Form1 : Form { int maxNo = 4; public Form1() { InitializeComponent(); comboBox1.SelectedIndexChanged+=AllCombobox_SelectedIndexChanged; comboBox2.SelectedIndexChanged += AllCombobox_SelectedIndexChanged; comboBox3.SelectedIndexChanged += AllCombobox_SelectedIndexChanged; comboBox4.SelectedIndexChanged += AllCombobox_SelectedIndexChanged; } private void AllCombobox_SelectedIndexChanged(object sender, EventArgs e) { clearPreceding((ComboBox)sender); } void clearPreceding(ComboBox cmbBox) { int cmbBoxNo = Convert.ToInt32(cmbBox.Name.Substring(cmbBox.Name.Length - 1)); for (int i = cmbBoxNo; i <= maxNo; i++) { ((ComboBox)this.Controls.Find("comboBox" + i, true)[0]).Text = ""; } } }
-16844290 0 Excel Loading via c# Try to Load an excel file using this code below gives me this error
The Microsoft Access database engine could not find the object 'Sheet Name'. Make sure the object exists and that you spell its name and the path name correctly. If 'Sheet Name' is not a local object, check your network connection or contact the server administrator.
i am sure the Sheet Name is correct.
Any suggestions?
if (strFile.Trim().EndsWith(".xlsx")) { strConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", strFile); } else if (strFile.Trim().EndsWith(".xls")) { strConnectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";", strFile); } OleDbConnection SQLConn = new OleDbConnection(strConnectionString); SQLConn.Open(); OleDbDataAdapter SQLAdapter = new OleDbDataAdapter(); string sql = "SELECT * FROM [" + sheetName + "]"; OleDbCommand selectCMD = new OleDbCommand(sql, SQLConn); SQLAdapter.SelectCommand = selectCMD; ///error in this line SQLAdapter.Fill(dtXLS); SQLConn.Close();
-38319846 0 You can use the code like this. I done for you..
editText.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View arg0, boolean hasFocus) { // TODO Auto-generated method stub if(hasFocus){ spinner.setVisibility(View.VISIBLE); } } }); spinner.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view,int position, long id) { editText.setText(spinner.getSelectedItem().toString()); //this is taking the first value of the spinner by default. } @Override public void onNothingSelected(AdapterView<?> parent) { // TODO Auto-generated method stub } });
You can only use OnItemSelectedListener on spinner in android.Red more from Android Developers. Good luck..
-17545781 0As others have said, IE8 does not support the nth-child()
selector in CSS.
You have the following options:
Refactor your code to use an alternative method rather than nth-child()
. Maybe just add a class to the relevant elements.
Use a javascript polyfill such a IE9.js or Selectivizr, which back-ports the nth-child()
selector (and others) to IE8.
Use jQuery or a similar library that supports nth-child()
to set the styles rather than doing it in CSS.
Drop support for IE8.
Which of those options you decide to use will depend on what matters to you.
If you've got code that works in other browsers and you need it to work in IE8 with the least amount of additional work, then I would suggest trying out the Selectivizr library. Or IE9.js. But I'd suggest trying Selectivizr first, as IE9.js does a lot of other stuff to the browser that may or may not affect your site.
If you don't want to have to use a Javascript library for this but you still need IE8 support, then you'll need to take option 1, and refactor your code. That may or may not be a lot of work, depending how your code is structured and how much code there is. Bit of a shame to have to make a backward step when the CSS is there.
Option 4 sounds like the worst option, but might be more suitable than it sounds. If the nth-child
styling is being used for something like zebra striping, it may not be the end of the world for IE8 users just to not get the stripes. If everything else in the site works okay, they may not even miss it. And if they do miss it, you can tell them to upgrade their browser.
I have created a column binding in a report(datetime column) using birt. The datetime value that the column binding fetches based on the value of another string type column. Now when I'm sorting the report based on the column binding, the result that I'm getting is initially sorted on the basis of the string column and then on the basis of the column binding.
I want the report to be sorted only on the basis of column binding (datetime) value.
-26497171 0Check if your version of Vim has support for client-server functionality: :echo has('clientserver')
If so, you can write an alias to tell Vim to change its cwd:
In your .bashrc:
alias fg="$VIM --remote-send ':cd $PWD<CR>'; fg"
Where $VIM is vim
or gvim
or macvim
.
You need the colon and the <CR>
because you're sending Vim keystrokes rather than commands (<CR>
is a special notation for "Enter")
I'm not sure whether --remote-send
works when Vim is suspended - this approach might be better if you use something like screen or tmux to run vim and your shell at the same time.
Otherwise, it's a bit trickier.
There's a :shell command that is similar to suspending and resuming, but I'm assuming it forks a child process instead of returning you to Vim's parent process. If you're ok with that, there's a ShellCmdPost autocmd you can attach to to load information. You can use that in association with an alias that writes the $CWD to a file to load the required directory and change to it.
In your .bashrc:
alias fgv="echo $PWD > ~/.cwd; exit"
In your .vimrc:
autocmd ShellCmdPost * call LoadCWD() function! LoadCWD() let lines = readfile('~/.cwd') if len(lines) > 0 let cwd = lines[0] execute 'cd' cwd endif endfunction
Looking through the list of autocommands, I was not able to find any that detect when Vim has been suspended and has just been resumed. You could remap ctrl-z to first set a flag variable then do an unmapped ctrl-z. Then write a shell script like before that writes its $CWD to a specific file. Then you can set up an autocmd to watch that file for modification and in the handler, check the flag variable, and if it's set, reset it, read the file, and change to that directory. A bit complex, but it would work.
That would look like this. You'll have to load the file when you start Vim so that it can monitor it for changes. You may want to set hidden
so that you can keep the buffer open but hide it.
In your .bashrc:
alias fg="echo $PWD > ~/.cwd; fg"
In your .vimrc:
set hidden edit ~/.cwd enew nnoremap <C-Z> :let g:load_cwd = 1<CR><C-Z> autocmd FileChangedShell ~/.cwd call LoadCWD() function! LoadCWD() if g:load_cwd let g:load_cwd = 0 let lines = readfile('~/.cwd') if len(lines) > 0 let cwd = lines[0] execute 'cd' cwd endif endif endfunction
-34993478 0 This is probably late, but editing the permission levels on the site might be easier than removing users access, and your SC admins will still have access.
-7231546 0 How to pass Arraylist of Objects to a Procedure using spring mybatisI want to pass an Arraylist of Objects for e.g.
Arraylist <SomeObject> listOFSomeObject
Where SomeObject is having two attributes key and value.
On DB side i have a table type of variable i.e.
create or replace type tableTypeVariable is table of SomeType; CREATE OR REPLACE TYPE SomeTypeAS OBJECT (key VARCHAR2(50),value VARCHAR2(50))
Now i want to map my each object of type SomeObject from a listOFSomeObject to the tableTypeVariable.
Can any body help me with that ?
-30910328 0The vector handles its memory outside of the structure, in the heap as mentioned in another answer. So resizing or reallocating the vector inside the structure won't change the structure's size at all, not even the vector containing that structure.
http://www.cplusplus.com/reference/vector/vector/
The vector handles its own memory dynamically ( in the heap ).
-20334365 0The problem with your code is that you’re only ever removing one character at a time, and so repeated sequences will be reduced to a single character, but that single character will stick around at the end. For example, your code goes from “xxx” to “xx” to “x”, but since there’s only a single “x” left that “x” is not removed from the string. Adapt your code to remove all of the consecutive repeated characters and your problem will be fixed.
-18000537 0You could use the function eval, but this is very dangerous !
This class might help you : http://www.phpclasses.org/browse/package/2695.html
Given the following two (simplified) models:
class Customer < ActiveRecord::Base # finder sql to include global users in the association has_many :users, :dependent => :destroy, :finder_sql => 'SELECT `u`.* FROM `users` `u` WHERE (`u`.`customer_id` = "#{id}" OR `u`.`customer_id` IS NULL)' validates_presence_of :name end class User < ActiveRecord::Base # most users belong to a customer. # however, the customer_id may be NULL # to implement the concept of "global" users. belongs_to :customer validates_presence_of :email end
At first, this seems to work just fine:
>> Customer.first.users # => Array of users including global users
But when i try following i get an mysql error:
>> Customer.first.users.find_by_email("test@example.com") ActiveRecord::StatementInvalid: Mysql::Error: Operand should contain 1 column(s): SELECT * FROM `users` WHERE (`users`.`email` = 'test@example.com') AND ( SELECT `u`.* FROM `users` `u` WHERE (`u`.`customer_id` = "1" OR `u`.`customer_id` IS NULL) ORDER BY u.nickname ) LIMIT 1 from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/connection_adapters/abstract_adapter.rb:188:in `log' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/connection_adapters/mysql_adapter.rb:309:in `execute' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/connection_adapters/mysql_adapter.rb:563:in `select' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/connection_adapters/abstract/database_statements.rb:7:in `select_all_without_query_cache' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/connection_adapters/abstract/query_cache.rb:62:in `select_all' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/base.rb:635:in `find_by_sql' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/base.rb:1490:in `find_every' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/base.rb:1452:in `find_initial' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/base.rb:587:in `find' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/base.rb:1812:in `find_by_email' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/base.rb:1800:in `send' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/base.rb:1800:in `method_missing' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/associations/association_collection.rb:370:in `send' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/associations/association_collection.rb:370:in `method_missing' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/base.rb:2003:in `with_scope' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/associations/association_proxy.rb:202:in `send' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/associations/association_proxy.rb:202:in `with_scope' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/associations/association_collection.rb:366:in `method_missing'
So, Rails is generating an invalid SQL Statement. The reason for that is probably my finder_sql, because the association without finder_sql works as expected.
I've already tried to remove all optional plugins (will_paginate). The thing I'm trying to achieve is actually quite simple: Include all User Models matching the following the condition (users.customer_id = 1 OR users.customer_id IS NULL)
in my association.
Appreciate any help!
-33034773 0public class GuessingGame { public static void main(String[] args) { int NumberGuess = 0; Random randomNumber = new Random(); int randomInt = randomNumber.nextInt(51); System.out.println("Guess the number between 0 -50:"); int i = 1; Scanner UserGuess = new Scanner(System.in); while (i <= 7) { NumberGuess = UserGuess.nextInt(); if (NumberGuess == randomInt) { System.out.println("Correct! You win!"); System.out.println("It took you " + i + " guesses."); System.exit(0); } else if (NumberGuess < 0 || NumberGuess > 50) { System.out.println("Invalid Input, please enter numbers between 0 and 50"); } else if (NumberGuess < randomInt) { System.out.println("Guess is too small."); } else if (NumberGuess > randomInt) { System.out.println("Guess is too big."); } System.out.println("You have made " + i + " guesses out of 7"); i++; } System.out.println("Game over!"); System.out.println("All 7 Guesses used!"); System.exit(0); } }
Also you should not Scanner UserGuess = new Scanner(System.in);
use this statement inside the loop. Only one copy of the scanner should be created, outside the loop.
i am trying to find a way to get the tag from a string and remove the style attribute . After that i want to add my own style and keep the following text.. For example, i have:
<p><img alt="" src="images/epsth/arismagnisiakos.jpg" style="width: 600px; height: 405px;" /></p><p> </p><p>
end the endresult should be:
<p><img alt="" src="images/epsth/arismagnisiakos.jpg" style="width: 100%;" /></p><p> </p><p>
I have unsuccesfully tried regex but it seems like i am too dumb to understand its functionality...
Every help would be appreciated! Greetings from Greece Jim
-24452117 0I just ran into this issue myself, the problem was that syntax coloring was set to C instead of Objective-C.
Click Editor->Syntax Coloring->Objective-C
-16701980 0Please make sure you have the same settings for ansi_null
for both your local DB settings and your clients. style like "name is not null" will return the desired result, not like "name =/<> null" that depends on ansi_null settings.
check for ansi_null: http://msdn.microsoft.com/en-us/library/ms188048(v=sql.105).aspx
-22203284 0Python looks for the installed packages in the PYTHON_PATH environment variable. But I am not sure if that is your problem here. The error message suggests that there is a problem with the shared object versions... I would recommend you that you install everything you need with the pip install command on the console...
-15428036 0 how to remove 3 lines in row if the first line contain a specific character?I have a data file (which a matrix with 290 lines and 2 columns) like this:
# RIR1 ABABABABABABABABAA ABABABABABABABABBA # WR ABABABABABABABABAB BABABBABABABABABAA # BR2 ABABABABABABABBABA ABBABABABABABABABA # SL AAABABABABABABBABA AAABBABABABABABABA
I would like to remove all the data that are for SL and WR (as example). So I will have only:
# RIR1 ABABABABABABABABAA ABABABABABABABABBA # BR2 ABABABABABABABBABA ABBABABABABABABABA
I know how to remove one line that start or contain something but no idea how to do with 3 lines in row.
this is what I use for one line:
old<-old[!substr(old[1,],1,5)=="# BR2",] old<-old[!substr(old[1,],1,6)=="# RIR1",]
thanks in advance.
-28702920 0Here's one bash
solution (assuming the numbers are in a file, one per line):
sort -n numbers.txt | grep -n . | grep -v -m1 '\([0-9]\+\):\1' | cut -f1 -d:
The first part sorts the numbers and then adds a sequence number to each one, and the second part finds the first sequence number which doesn't correspond to the number in the array.
Same thing, using sort and awk (bog-standard, no extensions in either):
sort -n numbers.txt | awk '$1!=NR{print NR;exit}'
-10520854 0 $('.className').click(funcName);
less load as it uses a single jquery object
$('.className').each(function(){ $(this).click(funcName); });
more load as it uses the initial instance, and also generates a new instance for each 'eached' element via $(this)
. If $('.className')
contains 50 elements, you now have 51 jQuery objects, versus a single object.
As far as pluggin development, you can use javascript objects and use new
for each instance of the plugin. Or you can define a parent object class, and use .each
on that to set up instances. I hope this helps, it hard to make a recommendation without knowing what your are cooking.
I have the template saved as a string somewhere and I want to create the mustache with that. How can I do this? Or is it doable?
-8170148 0Generic info about buttons here
To use image for a button you need an android.widget.ImageButton. Example of drawable selector (put it in res/drawable/):
<selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true" android:drawable="@drawable/button_pressed" /> <!-- pressed --> <item android:state_focused="true" android:drawable="@drawable/button_focused" /> <!-- focused --> <item android:drawable="@drawable/button_normal" /> <!-- default --> </selector>
So you can use different images for various states. To generate buttons on the fly you can define base layout with any layout manager (FrameLayout, RelativeLayout, LinearLayout), find it by id (findViewById()) within your Activity and make it visible:
public void createContainerForImageView() { LinearLayout container = new LinearLayout(this); container.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); container.setOrientation(LinearLayout.HORIZONTAL); ImageView img=(ImageView)findViewById(R.id.ImageView01); Bitmap bmp=BitmapFactory.decodeResource(getResources(), R.drawable.sc01); int width=200; int height=200; Bitmap resizedbitmap=Bitmap.createScaledBitmap(bmp, width, height, true); img.setImageBitmap(resizedbitmap); container.addView(img); // or you can set the visibility of the img }
Hope this helps.
-19733155 0You would need to use the constructor for Dictionary which accepts a custom IEqualityComparer(Of T)
for your key type.
Arrays, without a custom IEqualityComparer(Of T)
, are not valid object types as keys to a dictionary (or other hash-based collection).
Is it possible to set MySQL auto_increment_increment so that it survives the server restart?
Currently I'm setting it like this:
SET @@auto_increment_increment=2;
But it loses the value when I:
sudo service mysql restart
And returns to default value of 1.
I'm on a AWS and I would like to be able to handle possible doomsday errors as easy as possible: by setting up a new instance from an AMI. I would like it to be ready to serve right away when it's up and avoid things like setting the auto_increment_increment -value by hand.
-11313935 1 Trying to catch integrity error with SQLAlchemyI'm having problems with trying to catch an error. I'm using Pyramid/SQLAlchemy and made a sign up form with email as the primary key. The problem is when a duplicate email is entered it raises a IntegrityError, so I'm trying to catch that error and provide a message but no matter what I do I can't catch it, the error keeps appearing.
try: new_user = Users(email, firstname, lastname, password) DBSession.add(new_user) return HTTPFound(location = request.route_url('new')) except IntegrityError: message1 = "Yikes! Your email already exists in our system. Did you forget your password?"
I get the same message when I tried except exc.SQLAlchemyError
(although I want to catch specific errors and not a blanket catch all). I also tried exc.IntegrityError
but no luck (although it exists in the API).
Is there something wrong with my Python syntax, or is there something I need to do special in SQLAlchemy to catch it?
I don't know how to solve this problem but I have a few ideas of what could be causing the problem. Maybe the try statement isn't failing but succeeding because SQLAlchemy is raising the exception itself and Pyramid is generating the view so the except IntegrityError:
never gets activated. Or, more likely, I'm catching this error completely wrong.
An alternative approach is to just add a few forwarding functions:
T numberedFunction( unsigned int i ) { ... } T single() { return numberedFunction(1); } T halfDozen() { return numberedFunction(6); }
-20520733 0 CSS code a:visited does not work I have a pretty noob problem, so I hope someone could help me out.
I have a Blogger blog, and I can't get the links to function like I want to.
I want the links in the post content and in the sidebar - the ones that are a purple shade (#8B7083) and underlined - to look the same for both a:link and a:visited. For some reason visited links turn black, even though I don't have that anywhere in my CSS.
Help me, please?
-39556966 0This line:
A[j - 1] = 1;
Should be:
A[j] = 1;
So, now should works well:
#include<stdio.h> int A[1000000]; void sieve(int till) { for(int i = 2; i < till; i++) { if(A[i] == 0) { for(int j = i*i; j < till; j+=i) { A[j] = 1; } } } } int main() { int N,i; scanf("%i", &N); for (i = 0;i < N;i++) A[i] = 0; sieve(N); for (i = 2;i < N;i++) if (A[i]) printf("%i is not prime\n",i); else printf("%i is prime\n",i); }
-34104103 0 In BigInt
, note /%
operation which delivers a pair with the division and the reminder (see API). Note for instance
scala> BigInt(3) /% BigInt(2) (scala.math.BigInt, scala.math.BigInt) = (1,1) scala> BigInt(3) /% 2 (scala.math.BigInt, scala.math.BigInt) = (1,1)
where the second example involves an implicit conversion from Int
to BigInt
.
I use this code:
public void getDefaultLauncher() { final Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_HOME); PackageManager pm = getPackageManager(); final List<ResolveInfo> list = pm.queryIntentActivities(intent, 0); pm.clearPackagePreferredActivities(getApplicationContext().getPackageName()); for(ResolveInfo ri : list) { if(!ri.activityInfo.packageName.equals(getApplicationContext().getPackageName())) { startSpecificActivity(ri); return; } } } private void startSpecificActivity(ResolveInfo launchable) { ActivityInfo activity=launchable.activityInfo; ComponentName name=new ComponentName(activity.applicationInfo.packageName, activity.name); Intent i=new Intent(Intent.ACTION_MAIN); i.addCategory(Intent.CATEGORY_LAUNCHER); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); i.setComponent(name); startActivity(i); }
Maybe it works for you as well.
-23922079 1 How to write unittests for a custom pylint checker?I have written a custom pylint checker to check for non-i18n'ed strings in python code. I'd like to write some unittests for that code now.
But how? I'd like to have tests with python code as a string, which will get passed through my plugin/checker and check the output?
I'd rather not write the strings out to temporary files and then invoke the pylint binary on it. Is there a cleaner more robust approach, which only tests my code?
-35737341 0You are referencing to the wrong API. The link you have provided is for the Google Play Developer API which is for subscription, in-app purchase and publishing. The API for sharing progress and other in-game API calls is the Google Play Games Services which has a default quota of 50000000 requests/day and in which the user can have 500 requests per second(The quotas can be seen in the Developer's Console). You could also see Managing Quota and Rate Limiting for other info about the quota and limits.
-12784538 0You should try moving your integration test to the top level project. This way it will run after the WAR artifact has been built.
Have you had a look at the Maven Failsafe Plugin? It's designed for the sort of thing you're doing, which is actually an integration test and not a unit test. The page offers some good advice on why you might want to use the integration-test
phase for your integration testing.
Namely, it describes why you might want to do start-jetty
during pre-integration-test
and so on, so that you can tear it all down appropriately.
This is a duplcate of an existing question
See http://stackoverflow.com/a/7661057/2319909
Converted code for reference:
You need to set the button to allow multiple lines. This can be achieved with following P/Invoke code.
Private Const BS_MULTILINE As Integer = &H2000 Private Const GWL_STYLE As Integer = -16 <System.Runtime.InteropServices.DllImport("coredll")> _ Private Shared Function GetWindowLong(hWnd As IntPtr, nIndex As Integer) As Integer End Function <System.Runtime.InteropServices.DllImport("coredll")> _ Private Shared Function SetWindowLong(hWnd As IntPtr, nIndex As Integer, dwNewLong As Integer) As Integer End Function Public Shared Sub MakeButtonMultiline(b As Button) Dim hwnd As IntPtr = b.Handle Dim currentStyle As Integer = GetWindowLong(hwnd, GWL_STYLE) Dim newStyle As Integer = SetWindowLong(hwnd, GWL_STYLE, currentStyle Or BS_MULTILINE) End Sub
Use it like this:
MakeButtonMultiline(button1)
-11932580 0 I solved this problem by using an activation profile :-
<profiles> <profile> <id>ptest</id> <activation> <property> <name>ptest</name> </property> </activation> <build> <resources> <resource> <directory>src/jmeter</directory> </resource> </resources> <plugins> <plugin> <groupId>com.lazerycode.jmeter</groupId> <artifactId>jmeter-maven-plugin</artifactId> <version>1.4.1</version> <executions> <execution> <id>jmeter-tests</id> <phase>verify</phase> <goals> <goal>jmeter</goal> </goals> </execution> </executions> <configuration> <useOldTestEndDetection>true</useOldTestEndDetection> </configuration> </plugin> </plugins> </build> </profile> </profiles>
Using this approach you can install once, not using the profile, and then run subsequently with the profile turned on.
-19092733 0You can try and run an exception handler on the occurrence of exception. You can use a flag, I have used the exception for checking the exception occurence itself in the example:
private static AggregateException exception = null; static void Main(string[] args) { Console.WriteLine("Start"); Task.Factory.StartNew(PrintTime, CancellationToken.None).ContinueWith(HandleException, TaskContinuationOptions.OnlyOnFaulted); for (int i = 0; i < 20; i++) { Console.WriteLine("Master Thread i={0}", i + 1); Thread.Sleep(1000); if (exception != null) { break; } } Console.WriteLine("Finish"); Console.ReadLine(); } private static void HandleException(Task task) { exception = task.Exception; Console.WriteLine(exception); } private static void PrintTime() { for (int i = 0; i < 10; i++) { Console.WriteLine("Inner Thread i={0}", i + 1); Thread.Sleep(1000); } throw new Exception("exception"); }
-21068282 0 Checkbox look like radio buttons on iPad/iPad Mini? Not sure why this is happening, but couldn't find anything on this. Every input type="checkbox" look like radio buttons on iPads. Has anyone come across this issue and if so, how were you able to fix the problem?
Thank you guys!
<div> <input type="checkbox" name="checkNow">Check Now </div>
-2023342 0 You can achieve this with a DockPanel
:
<DockPanel Width="300"> <TextBlock>Left</TextBlock> <Button HorizontalAlignment="Right">Right</Button> </DockPanel>
The difference is that a StackPanel
will arrange child elements into single line (either vertical or horizontally) whereas a DockPanel
defines an area where you can arrange child elements either horizontally or vertically, relative to each other (the Dock
property changes the position of an element relative to other elements within the same container. Alignment properties, such as HorizontalAlignment
, change the position of an element relative to its parent element).
Every valid JSON is also valid JavaScript but not every valid JavaScript is also valid JSON as JSON is a proper subset of JavaScript:
JSON ⊂ JavaScript
JSON requires the names of name/value pairs to be quoted while JavaScript doesn’t (as long as they are not reserved keywords).
So your first example {"active": "yes"}
is both valid JSON and valid JavaScript while the second example {active: "yes"}
is only valid JavaScript.
You need to send exception about your error, to method fail()
.
Assert.fail("Some message", new Exception(errorDivs.get(0).getText()));
-14341379 0 Trigger a process (SQL update) when leaving an APEX page This is a very odd question but i wondered whether it was possible to trigger a process that runs an SQL UPDATE when the user leaves this specific page, either by clicking on the breadcrumb, tabs or back button?
I did setup the process to run on the 'Back' button; however i ran into the problem of: What if s/he clicks on the breadcrumb or a tab instead.
I have searched the net and posting this question was a last resort. I wondered if anyone can point me in the correct direction?
UPDATED POST
Page 1:
Includes a text field and a button. The user enters the category into the text field and clicks on the button to proceed to the next page. The button passes the value in the text field to a text field on Page 2.
Page 2:
Two regions on the page. One region holds information about the category - Category name from the previous page, category description, and the category revision number (which is what i'm trying to get working). The second region is a report that pulls the item name and number that are listed under the category in the category text field. A 'View' link is used on the report to load the edit page for the specific item selected. The 'View' link passes the 'category name' (from the category text field) and the 'item number' from the report to page 3.
Page 3
Two regions are used, first region: Lists the Item number which came from page 2 and name of the item (which i use a simple query to retrieve). In the second region: A report is used with two columns: a list of item properties in column 1, and a text field next to each item property in column 2 to hold the value that can be updated. The 'Apply Changes' button has some PlSql behind which looks for changes and updates where required. It updates the relevant fields that have changed, and it then takes the user back to Page 2 (Page showing user the items listed for the category intitally entered).
I cant increase the category revision on the 'apply changes' button on page 3 because the user may complete edits for items under the same category. So i dont know where i can increase the category revision by 1 per vist to a category. P.s I already increment the revision number for each item by 1 if the info has been changed using the 'apply changes' button on page 3.
-21044819 0You have to create a new serie and then add it to your chart.
Series series1 = new Series("series1"); chart1.Series.Add(series1);
You can also create them in your .aspx.
<form id="form1" runat="server"> <asp:Chart ID="Chart1" runat="server" ImageType="Png"> <ChartAreas> <asp:ChartArea Name="ChartArea1"></asp:ChartArea> </ChartAreas> <Legends> <asp:Legend Name="Legends1"></asp:Legend> </Legends> <Series> <asp:Series Name="Series0"></asp:Series> <asp:Series Name="Series1"></asp:Series> <asp:Series Name="Series2"></asp:Series> </Series> </asp:Chart> </form>
-7556033 0 Load or functional testing of GWT app using JMeter I am new to JMeter. I wanted to do some functional testing of my GWT application using JMeter. Does it support GWT testing? For example I would like to write a script that might check if the login module of my GWT application is doing good or not. Please let me know if we have some sort of documentation specific to GWT testing with JMeter.
Thanks a million.
-- Mohyt
-4139738 0 Need help with a mIRC macroI'm trying to make a script that will automatically says "see you later" as soon as one specific handle in a channel says the words "going home". I tried to do it on my own but got lost. Could anyone help me out?
-13168565 0Why not to convert your pseudo-code to real code?
public static class MyExtensions { public static IEnumerable<T> RunMeOnEachItemLater(this IEnumerable<T> sequence, Action<T> action) { foreach(T item in sequence) { action(item); yield return item; } } }
Now you can execute custom function for each item later using LINQ deferred execution:
IEnumerable<BaseModel> l = Cache[type].Data.Cast<BaseModel>() .RunMeOnEachItemLater(m => m.Init());
-7257281 0 Using doxygen to create documentation for existing C# code with XML comments I've read everywhere that doxygen is the way to go for generating documentation for C# code. I've got a single interface that I want to document first (baby steps), and it already has the XML comments (///) present.
Because of the vast number of posts and information available (including doxygen.org) that say these comments are already supported, I'm surprised that when I run doxywizard, I get errors like "warning: Compound Company::Product::MyInterface is not documented".
This leads me to believe that I have somehow misunderstood XML documentation (hopefully not, according to MSDN I am talking about the right thing), or I have misconfigured doxywizard.
I first ran doxywizard via the Wizard tab, and specified that I want to support C#/Java. When I run it, my HTML page is blank, presumably because of the previously-mentioned warnings. I then tried specifying a single file via the Expert tab and ran again -- same behavior.
Can anyone tell me what switch or setting I'm missing to get doxygen to generate the HTML?
Here's an example of what a documented property/method looks like in my interface:
/// <summary> /// Retrieve the version of the device /// </summary> String Version { get; } /// <summary> /// Does something cool or really cool /// </summary> /// <param name="thing">0 = something cool, 1 = something really cool</param> void DoSomething( Int32 thing);
I do have a comment above the interface, like this:
/// <summary> /// MyInterface /// </summary> public interface MyInterface {...}
-40597239 0 You will have to decide on a library to do API calls. A simple way is to use fetch
, which is built-in in modern browsers. There's a polyfill to cover older ones. jQuery's AJAX or SuperAgent are two alternatives. Here's a simple example using fetch
. You'll only have to change the URL of the request.
class Example extends React.Component { constructor() { super(); this.state = { data: {} }; } componentDidMount() { var self = this; fetch('http://reqres.in/api/users') .then(function(response) { return response.json() }).then(function(data) { self.setState({ data }, () => console.log(self.state)); }); } render() { return ( <div/> ); } } ReactDOM.render(<Example/>, document.getElementById('View'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="View"></div>
%p is the format token to show AM/PM
time_tag(time, :format=>'%B %d, %Y %l:%M %p')
-31740599 0 You have error in your query, you are writing select*
but there should be a space like so select *
$sql = mysql_query("select * from login where user= '$user' AND pass='$pass' LIMIT 3 ") or die(mysql_error());
EDIT
Also YOU MUST HAVE TO PUT session_start();
as the first line of your code... else it would not work.
So make this as your first lines of code
session_start(); error_reporting(E_ALL); // to see if there is error in code
And also PHP varialble names are case-sensitive,
Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-sensitive.
So please change
if($user==$username && $pass==$password)
to
if($user==$UserName && $pass==$Password)
-3896348 0 Seq.initInfinite (fun _ -> Console.ReadLine())
-10042197 0 It seems your mapper outputs a key-value pair of type ImmutableBytesWritable -> Result
but your Reducer reads in a key-value pair of type ImmutableBytesWritable -> Put
. This can't work as the output of the mapper must be of the same type the input of the reducer is. You should either
Put
object and adjust your method and class signaturesIn the main loop of my program, I have around a dozen variables that are calculated each time the loop is actioned. At this stage I would prefer a 'NameError' than to have the variables from an earlier pass affect the outcome of a future pass of the loop.
Right now I just have a series of the following statements run at the final step of each loop:
try: del my_var1 except: pass
I suspect there's a better way to do this?
-11281019 0Third option:
>>> from urlparse import urlparse, parse_qs >>> url = 'http://something.com?blah=1&x=2' >>> urlparse(url).query 'blah=1&x=2' >>> parse_qs(urlparse(url).query) {'blah': ['1'], 'x': ['2']}
-36026699 0 How to know whether Arduino Bluetooth is paired or not? I am using an Arduino Mega and a Bluetooth module hc-05 zs040. I want to connect an external LED to the Arduino, which will indicate whether Bluetooth is paired or not. I read about the STATE pin and tried to use it but my state always outputs digital 0, no matter whether it is connected or not. Is there any other way to do this (other than soldering)?
-25275368 0Explicitly declare all the variables:
function animate(num, element, transitionUnit, delayUnit) { var delay = 0; var transition = 0; var x = document.getElementById(element).getElementsByTagName("LI"); for (var i = 0; i <= x.length - 1; i++) { x[i].style.WebkitTransform = "translate3d(" + num + "px,0,0)"; x[i].style.transition = transition + "s " + delay + "s ease-in-out"; delay += delayUnit; transition += transitionUnit; if (x[i].querySelectorAll('ul li').length > 0) { x[i].style.background = "rgba(0,0,0,0.35)"; } } }
Using implicit globals in for loops causes problems.
As aSeptik mentioned, you might be inverting values:
animate(0,"mainNav",0.04,0.02);
-22980046 0 how to solve onTouchListener android i have problem, I am successfully to display image in alert dialog custom, but when I want to add event onTouchListener
to the image, i cannot get problem : the method setonTouchListener in Type View is not applicable
. Here my source code :
public class ViewDetailItem extends Activity implements OnTouchListener{ bla bla... onloaditem() }
here onloaditem() sourcecode :
imgmain.setImageResource(imgID); imgmain.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub /*Intent MyIntentDetailItem=new Intent(getBaseContext(), ViewDetailItemFullscreen.class); Other_class.setItemCode(timgName); startActivity(MyIntentDetailItem);*/ LayoutInflater li = LayoutInflater.from(ViewDetailItem.this); final View inputdialogcustom = li.inflate(R.layout.activity_view_detail_item_fullscreen2, null); final AlertDialog.Builder alert = new AlertDialog.Builder(ViewDetailItem.this); final ImageView imgmainbig=((ImageView) inputdialogcustom.findViewById(R.id.imgmainbig)); imgID=getBaseContext().getResources().getIdentifier(imgName2+"_1", "drawable", getBaseContext().getPackageName()); imgmainbig.setImageResource(imgID); imgmainbig.setOnTouchListener(this); } }
The problem refers to imgmainbig.setOnTouchListener(this);
Microsoft tried to do something like that with WinFS but gave up on it. It would be great if they could get it to work.
-1765718 0 Android - NPE in BrowserFrameI get this exception triggered by users occasionally that I cannot reproduce. Since it's issued from looper I suppose it is result of Handler-type callback. I found similar bug on Google code but putting the solution into code didn't solve it. The problem is at this line of code in BrowserFrame:
WebAddress uri = new WebAddress( mCallbackProxy.getBackForwardList().getCurrentItem() .getUrl());
Which throws this Exception because I suppose mCallbackProxy is null
java.lang.NullPointerException at android.webkit.BrowserFrame.handleMessage(BrowserFrame.java:348) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:123) at android.webkit.WebViewCore$WebCoreThread.run(WebViewCore.java:471) at java.lang.Thread.run(Thread.java:1060)
And the questions are - will this forclose the app? And how do I work around this bug?
-30478039 1 entering data and displaying entered data using pythonI am newbie to python , I am trying to write a program in which i can print the entered data .
here is the program which I tried.
#!"C:\python34\python.exe" import sys print("Content-Type: text/html;charset=utf-8") print() firststring = "bill" secondstring = "cows" thridstring = "abcdef" name = input('Enter your name : ') print ("Hi %s, Let us be friends!" % name)
The output of this program is only : "Enter your name : " I cannot enter anything from my keyboard. I am running this program using apache in localhost like http://localhost:804/cgi-bin/ex7.py Can anyone plz help me to print the user entered data. Thank you.
-17328937 0 Does installing a file automatically register it?I am creating an MSI installer using WiX. I have several .ocx and .dll files that must be registered on the end user's computer. Does including these files in the installation automatically register them as if the regsvr32 command had been run?
-11461733 0 How to embed a property as a string argument in soapUII have recently started using soapui to test web services and fairly new. I was wondering how to embed a property value as a string in the request. For example the request is like below
<org:Customer org1:Description="customer" org1:DisplayName="google" org1:Name="google"/>
Essentially I am looking to do this something like this,
<org:Customer org1:Description=${#Project#orgdesc} org1:DisplayName=${#Project#orgdisplayname} org1:Name=${#Project#orgdisplayname}/>
I have properties defined for all of the fields above at the project level for parameterizing my test. I am trying to embed these properties within the request. I tried following things but none of them work. Can someone please let me know what I am missing?
Edit#1
I think I am not doing the right thing below. Because in the original request above, Description, DisplayName and Name are the attributes of Customer and I sending the request by making them as child nodes below. It seems fundamentally incorrect. Then how do I embed value of the properties I defined within attributes of a tag?
Attempt 1
<org:Customer> <arg0> <org1:Description>${#Project#orgdesc}</org1:Description> <org1:DisplayName>${#Project#orgdisplayname}</org1:DisplayName> <org1:Name>${#Project#orgname}</org1:Name> </arg0> </org:Customer>
Attempt 2
<org:Customer> <org1:Description> <arg0>${#Project#orgdesc}</arg0> </org1:Description> <org1:DisplayName> <arg0>${#Project#orgdisplayname}</arg0> </org1:DisplayName> <org1:Name> <arg0>${#Project#orgname}</arg0> </org1:Name> </org:Customer>
-38900347 0 There is an event in magento,
sales_quote_collect_totals_after
This is fired whenever your total is calculated, what you can do is set a flag in session on click on the button to apply discount, and in this above event's observer method, check if it is set then apply discount.
In your config.xml
<global> <events> <sales_quote_collect_totals_after> <observers> <class>Custom_Module_Model_Observer</class> <method>collectTotals</method> </observers> </sales_quote_collect_totals_after> </events> </global>
Make a Observer.php in
Custom /Module /Model /Observer.php
Make a function in Observer.php
public function collectTotals(Varien_Event_Observer $observer) { $quote=$observer->getEvent()->getQuote(); $quoteid=$quote->getId(); //check condition here if need to apply Discount if($disocuntApply) $discountAmount =5; if($quoteid) { if($discountAmount>0) { $total=$quote->getBaseSubtotal(); $quote->setSubtotal(0); $quote->setBaseSubtotal(0); $quote->setSubtotalWithDiscount(0); $quote->setBaseSubtotalWithDiscount(0); $quote->setGrandTotal(0); $quote->setBaseGrandTotal(0); $canAddItems = $quote->isVirtual()? ('billing') : ('shipping'); foreach ($quote->getAllAddresses() as $address) { $address->setSubtotal(0); $address->setBaseSubtotal(0); $address->setGrandTotal(0); $address->setBaseGrandTotal(0); $address->collectTotals(); $quote->setSubtotal((float) $quote->getSubtotal() + $address->getSubtotal()); $quote->setBaseSubtotal((float) $quote->getBaseSubtotal() + $address->getBaseSubtotal()); $quote->setSubtotalWithDiscount( (float) $quote->getSubtotalWithDiscount() + $address->getSubtotalWithDiscount() ); $quote->setBaseSubtotalWithDiscount( (float) $quote->getBaseSubtotalWithDiscount() + $address->getBaseSubtotalWithDiscount() ); $quote->setGrandTotal((float) $quote->getGrandTotal() + $address->getGrandTotal()); $quote->setBaseGrandTotal((float) $quote->getBaseGrandTotal() + $address->getBaseGrandTotal()); $quote ->save(); $quote->setGrandTotal($quote->getBaseSubtotal()-$discountAmount) ->setBaseGrandTotal($quote->getBaseSubtotal()-$discountAmount) ->setSubtotalWithDiscount($quote->getBaseSubtotal()-$discountAmount) ->setBaseSubtotalWithDiscount($quote->getBaseSubtotal()-$discountAmount) ->save(); if($address->getAddressType()==$canAddItems) { $address->setSubtotalWithDiscount((float) $address->getSubtotalWithDiscount()-$discountAmount); $address->setGrandTotal((float) $address->getGrandTotal()-$discountAmount); $address->setBaseSubtotalWithDiscount((float) $address->getBaseSubtotalWithDiscount()-$discountAmount); $address->setBaseGrandTotal((float) $address->getBaseGrandTotal()-$discountAmount); if($address->getDiscountDescription()){ $address->setDiscountAmount(-($address->getDiscountAmount()-$discountAmount)); $address->setDiscountDescription($address->getDiscountDescription().', Amount Waived'); $address->setBaseDiscountAmount(-($address->getBaseDiscountAmount()-$discountAmount)); }else { $address->setDiscountAmount(-($discountAmount)); $address->setDiscountDescription('Amount Waived'); $address->setBaseDiscountAmount(-($discountAmount)); } $address->save(); }//end: if } //end: foreach //echo $quote->getGrandTotal(); foreach($quote->getAllItems() as $item){ //We apply discount amount based on the ratio between the GrandTotal and the RowTotal $rat=$item->getPriceInclTax()/$total; $ratdisc=$discountAmount*$rat; $item->setDiscountAmount(($item->getDiscountAmount()+$ratdisc) * $item->getQty()); $item->setBaseDiscountAmount(($item->getBaseDiscountAmount()+$ratdisc) * $item->getQty())->save(); } } } }
collectTotals
function will be called, whenever the quote totals is updated, so there is no need to call it explicitly.
Check for how it works here.
Setting magento session variables, check here.
hope it helps!
-39225329 0First one is an example of a nested state which fulfills your requirement for inheriting the scope object. e.g state/sub-state-a, state/sub-state-b The comment above the first snippet you took from the doc reads:
Shows prepended url, inserted template, paired controller, and inherited $scope object.
The second example is a nested view where you can define multiple views per state and use each depending on your use-case. From the docs:
-26493784 0Then each view in views can set up its own templates (template, templateUrl, templateProvider), controllers (controller, controllerProvider).
To get the results you want without changing your existing code too much, you can get the sequence line when you're processing the header line:
while ( my $line = <FILE2> ) { if ($line =~ /^>(\S+)\s+\S+\s+(\d+)\s+(\d+)\s+(\S+)/) { my $cds1 = $1; my $cds2 = $2; my $cds3 = $3; my $cds4 = $4; # fetch the next line from the file -- i.e. the sequence $nextline = <FILE2>; for my $cc22 (@file1list) { if ( $cc22 > $cds2 && $cc22 < $cds3 ) { print "$cc22 $cds2 $cds3 $cds4 $nextline"; } } } }
-5730726 0 The mouse does work for single finger gestures and taps, not sure why it wouldn't work for you except to assume that your code must not be working as you assume :-)
Just for reference, the other way of testing multi-touch is to have a multi-touch enabled monitor
-3319559 0" Is it possible with some code in the controller to define the nested master page and master page?"
Nope. The default view engine only lets you define one level of MasterPages.
See: http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.view.aspx
-2420358 0 Why does using a structure in C program cause Link errorI am writing a C program for a 8051 architecture chip and the SDCC compiler.
I have a structure called FilterStructure;
my code looks like this...
#define NAME_SIZE 8 typedef struct { char Name[NAME_SIZE]; } FilterStructure; void ReadFilterName(U8 WheelID, U8 Filter, FilterStructure* NameStructure); int main (void) { FilterStructure testStruct; ReadFilterName('A', 3, &testFilter); ... ... return 0; } void ReadFilterName(U8 WheelID, U8 Filter, FilterStructure* NameStructure) { int StartOfName = 0; int i = 0; ///... do some stuff... for(i = 0; i < 8; i++) { NameStructure->Name[i] = FLASH_ByteRead(StartOfName + i); } return; }
For some reason I get a link error "?ASlink-Error-Could not get 29 consecutive bytes in internal RAM for area DSEG"
If I comment out the line that says FilterStructure testStruct;
the error goes away.
What does this error mean? Do I need to discard the structure when I am done with it?
-1351741 0The answer is no, by default object identity is not preserved via serialization if you are considering 2 separate serializations of a given object/graph. For example, if a I serialize an object over the wire (perhaps I send it from a client to a server via RMI), and then do it again (in separate RMI calls), then the 2 deserialized objects on the server will not be ==.
However, in a "single serialization" e.g. a single client-server message which is a graph containing the same object multiple times then upon deserialization, identity is preserved.
For the first case, you can, however, provide an implementation of the readResolve
method in order to ensure that the correct instance is returned (e.g. in the typesafe enum pattern). readResolve
is a private method which will be called by the JVM on a de-serialized Java object, giving the object the chance to return a different instance. For example, this is how the TimeUnit
enum
may have been implemented before enum
's were added to the language:
public class TimeUnit extends Serializable { private int id; public TimeUnit(int i) { id = i; } public static TimeUnit SECONDS = new TimeUnit(0); //Implement method and return the relevant static Instance private Object readResolve() throws ObjectStreamException { if (id == 0) return SECONDS; else return this; } }
.
-29765240 0 If without else not runningI have a little code for testing a sprite, that I want to move with the mouse. When I click the screen, the sprite has to move to the clicked point. But something weird is going on.
I'm running it in a thread, called Controls, that extends to Thread and implements MouseListener, and using the following code, the sprite moves.
public void run() { while(true){ if((int)point.getX() > player.getX()){ while((int)point.getX() > player.getX()){ player.moveX(1); } } else{ System.out.println("Nah!"); } } }
Everything works as expected, but if i do this:
public void run() { while(true){ if((int)point.getX() > player.getX()){ while((int)point.getX() > player.getX()){ player.moveX(1); } } } }
It doesn't work. If i do this:
public void run() { while(true){ if((int)point.getX() > player.getX()){ while((int)point.getX() > player.getX()){ player.moveX(1); } } else{ } } }
It doesn't work either. I have no idea of what is going on, any ideas?
-28395585 0 Laravel 4.2 returning soft deleted on BelongsToMany resultsHello I just noticed one weird behaviour of softDelete. Basically, when I query for a related set of models, Eloquent returns a collection that also contains soft deleted rows.
I have been following the 4.2 guides on traits usage for softdelete and my code works just fine as long as I get/delete/restore/force delete my models. The issue is triggered with relations.
Consider this scenario: I have a user model that has a belongToMany friendship relation where the friendship status can be accepted/pending/requested/blocked as follows:
public function friends() { return $this->belongsToMany('User', 'friends', 'user_id', 'friend_id')->where('status', 'accepted'); }
This friends table rows are basically "vectors" where user1->status->user2 and viceversa (user2->status->user1 is on another row). When user1 decides not to be friend with user2 anymore, the 2 friends rows are softdeleted.
Here is the issue: when I query the DB from the controller like this:
$friends = $user->friends;
even the softdeleted rows show up in the returned collection even though I would have expected these to be hidden from results unless I used ->withTrashed().
I suspect the belongsToMany() method doesn't take into account the deleted_at field on the pivot table.
Did anyone faced a similar issue? Am I doing something wrong with this relation?
Thanks a lot for your help!!!
-18988439 0Method 1: Using list.index
:
def match(strs, actual): seen = {} act = actual.split('/') for x in strs.split('/'): if x in seen: #if the item was already seen, so start search #after the previous matched index ind = act.index(x, seen[x]+1) yield ind seen[x] = ind else: ind = act.index(x) yield ind seen[x] = ind ... >>> p1 = '/foo/baz/myfile.txt' >>> p2 = '/bar/foo/myfile.txt' >>> actual = '/foo/bar/baz/myfile.txt' >>> list(match(p1, actual)) #ordered list, so matched [0, 1, 3, 4] >>> list(match(p2, actual)) #unordered list, not matched [0, 2, 1, 4] >>> p1 = '/foo/bar/bar/myfile.txt' >>> p2 = '/bar/bar/baz/myfile.txt' >>> actual = '/foo/bar/baz/bar/myfile.txt' >>> list(match(p1, actual)) #ordered list, so matched [0, 1, 2, 4, 5] >>> list(match(p2, actual)) #unordered list, not matched [0, 2, 4, 3, 5]
Method 2: Using defaultdict
and deque
:
from collections import defaultdict, deque def match(strs, actual): indexes_act = defaultdict(deque) for i, k in enumerate(actual.split('/')): indexes_act[k].append(i) prev = float('-inf') for item in strs.split('/'): ind = indexes_act[item][0] indexes_act[item].popleft() if ind > prev: yield ind else: raise ValueError("Invalid string") prev = ind
Demo:
>>> p1 = '/foo/baz/myfile.txt' >>> p2 = '/bar/foo/myfile.txt' >>> actual = '/foo/bar/baz/myfile.txt' >>> list(match(p1, actual)) [0, 1, 3, 4] >>> list(match(p2, actual)) ... raise ValueError("Invalid string") ValueError: Invalid string >>> p1 = '/foo/bar/bar/myfile.txt' >>> p2 = '/bar/bar/baz/myfile.txt' >>> actual = '/foo/bar/baz/bar/myfile.txt' >>> list(match(p1, actual)) [0, 1, 2, 4, 5] >>> list(match(p2, actual)) ... raise ValueError("Invalid string") ValueError: Invalid string
-34621470 0 I assume, the question reflects an attemtpt to use unique_lock, which OP is saying works. The same example with lock_guard would not work, since std::vector::emplace_back
requires the type to be both MoveInsertable
and EmplaceConstructible
, and std::lock_guard
does not suit.
Use:
NodeList nodeList = doc.getElementsByTagName("xLabel"); for (int temp = 0; temp < nodeList.getLength(); temp++) { Node node = nodeList.item(temp); NodeList namexLabelNodes = node.getChildNodes(); for (int i = 0; i < namexLabelNodes.getLength(); i++) { System.out.println(" Name : " + namexLabelNodes.item(i).getTextContent()); } }
For yLabel will be same code.
-22907415 0 Eclipse PHP code formatter removes pipe symbols from @return commentsI'm using Eclipse Kepler (4.3.1) for a PHP project.
I've stumbled across a problem with the eclipse code formatter for PHP regarding PHPDoc's @return with pipe (vertical bar) symbol: When having a comment like this:
<?php /** * * @param string|array The parameter. Either a string or an array. * @return int|string The return value. Either an int or a string. */ function test($param) { }
Using the format function with [CTRL]+[SHIFT]+[F] results in:
<?php /** * * @param * string|array The parameter. Either a string or an array. * @return int string return value. Either an int or a string. */ function test($param) { }
As one can see, the pipe symbol between 'int' and 'string' in the '@return' statement has been replaced by a space. But not only that. Also the first word of the description ('The') has been chopped off. On the other hand, it works just fine for the '@param' statement.
phpdoc.org states, that the pipe symbol is used when handling ambigous return values: phpdoc-@return
Somebody also asked a question about this int the Eclipse Community Forums: Forum Post just a few days ago.
Using '@formatter:off' and '@formatter:on' is no option, since this setting is only local and others might not have it set.
Does anyone know how to fix-configure the eclipse php code formatter? Does anybody have a workaround?
-38567369 0Rudy Velthuis's answer explains it perfectly. If I understand correctly what you are trying to do can be done like this.
int pckt_number = 0; // 0 pckt_number |= 0 << 24; // most significant byte, pckt_number |= 1 << 16; // second most significant byte, pckt_number |= 0 << 8; // third most significant byte, pckt_number |= 0; // least significant byte,
-41059077 0 The correct path to use is the platform/google_appengine/
directory, within the google-cloud-sdk
installation directory,
All your optionals need to be unwrapped. So lvt
should become lvt!
Word of Caution Unwrapping an optional which doesn't have a value will thrown an exception. So it might be a good idea to make sure your lvt isn't nil.
if (lvt != nil)
-38529477 0 Repeating Javascript Animation I have found a JSFiddle that has some great code to animate a ball - it rotates it through 360 deg. What I would like to do is have the ball constantly rotate through 360 deg - it needs to turn continuously. I have tried to achieve this but have had no success. I would be grateful for any help in adjusting this javascript.
$(document).ready(function(){ var s=$('.ball').position(); var g=s.left; var r=$('.ball').css('margin-left'); $('.ball').css({'margin-left':'0px'}); $('.ball').css({'margin-left':''+r+''}); if(r=="0px") { $('.ball').css({'position':'absolute'}); $('.ball').animate({'left':''+g+'px'}); } $('.ball').css({'transform': 'rotate(360deg)','-webkit-transform': 'rotate(360deg)','-moz-transform': 'rotate(360deg)'}); });
This is the JSFiddle I found http://jsfiddle.net/996PJ/5/
-7053631 0You can try to use a different library to load this assembly, like Mono.Cecil
.
I keep getting the error list index out of range. I'm not sure what I'm doing wrong.
My code:
from scanner import * def small(array): smallest=array[0] for i in range(len(array)): if (array[i]<smallest): smallest=array[i] return smallest def main(): s=Scanner("data.txt") array=[] i=s.readint() while i!="": array.append(i) i=s.readint() s.close() print("The smallest is", small(array)) main()
The traceback I get:
Traceback (most recent call last): File "file.py", line 21, in <module> main() File "file.py", line 20, in main print("The smallest is", small(array)) File "file.py", line 5, in small smallest=array[0] IndexError: list index out of range
-12503239 0 Use the overload that takes a MidpointRounding
Math.Round(276.5, MidpointRounding.AwayFromZero);
demo: http://ideone.com/sQ26z
-6561284 0new/new[]/malloc
and not freeing itp = new int; p = new int[1];
new int[100];
or cout<<(*new string("hello"))<<endl;
using row number windowed function along with a CTE will do this pretty well. For example:
;With preResult AS ( SELECT TOP(100) [ID] = c.[ID], [Name] = c.[Name], [Keyword] = [colKeyword].[StringVal], [DateAdded] = [colDateAdded].[DateVal], ROW_NUMBER()OVER(PARTITION BY c.ID ORDER BY [colDateAdded].[DateVal]) rn FROM @cards AS c LEFT JOIN @cardindexes AS [colKeyword] ON [colKeyword].[CardID] = c.ID AND [colKeyword].[IndexType] = 1 LEFT JOIN @cardindexes AS [colDateAdded] ON [colDateAdded].[CardID] = c.ID AND [colDateAdded].[IndexType] = 2 WHERE [colKeyword].[StringVal] LIKE 'p%' AND c.[CardTypeID] = 1 ORDER BY [DateAdded] ) SELECT * from preResult WHERE rn = 1
-8643895 0 QTableView - change selection when scrolling I have a QTableView. I want the selection to be moved when i scroll - so the cursor would be always visible.
There is QTableView.selectRow(rowNo)
, but do you have a suggestion where to call this?
Ideally i would like upon scrolling the selected row to be in the center.
-35714038 0You have to enable the allowable rotations at the project level and then restrict rotation on all the viewControllers you DON'T want to rotate. i.e. if you have 5 viewControllers, you'll need to restrict rotation on 4 of them and only allow rotation on the Player Controller. You can see more on this here Handling autorotation for one view controller in iOS7
-3431255 0Thanks to advice, I made it! Here is the code.
var foo = function(){}; foo.prototype = { say : function(s){ Queue.enqueue(function(){ alert(s); }); Queue.flush(); return this; }, delay : function(ms){ Queue.enqueue('delay:' + ms); return this; } } Queue = { entries : [], inprocess : null, enqueue : function(entry){ Queue.entries.push(entry); }, flush : function(){ if(Queue.inprocess) return; while (Queue.entries.length){ var entry = Queue.entries.shift(); if(entry.toString().indexOf('delay:') !== -1){ var ms = Number(entry.split(':')[1]); Queue.inprocess = setTimeout(function(){ Queue.inprocess = null; Queue.flush(); }, ms); return; } entry(); } } }
I prepared a Queue object to manage functions' entries. With this, I can play with a method-chain:
var bar = new foo(); bar.delay(2000).say('Hello, ').delay(3000).say('world!');
Many thanks!
-23850869 0Return a pair of values containing the weight and value:
pair<int, int> knapsack(int N, int budget) { if((!N) || (!budget)) return pair<int, int>(0, 0); pair<int, int> local(N, budget); if(hash_memo[local].second) return hash_memo[local]; pair<int, int> b = pair<int, int>(0, 0); pair<int, int> a = knapsack(N-1, budget); if(budget >= arr[N-1].first) { pair<int, int> c = knapsack(N-1, budget - arr[N-1].first); b = pair<int, int>(c.first + arr[N-1].first, c.second + arr[N-1].second); } if(a.second > b.second) { return hash_memo[local] = a; } return hash_memo[local] = b; }
-22752345 0 I'm assuming you left some out, is this the complete code?
public class House { private final House house; public static void main(String[] args) { house = new House("Robinsons"); house.setColor("Red"); } public House(String houseName) { // do something } public void setColor(String color) { // do something } }
If so, there are a number of problems with this.
main
method, either make house
a static variable, which I wouldn't recommend. Or declare an instance inside the main
method before using it.I am trying to get the Google GCM demo app up and running. My android emulator makes a successful connection to the GCM server and goes on to make successful connection to my own server which is located at http://localhost:8080/gcm-demo-server
(ie. the emulator sends the request to http://10.0.2.2:8080/gcm-demo-server
).
However when I click 'Send message' on my server's webpage the message doesn't get delivered to the emulator. Nothing shows up in Logcat and my breakpoint in onMessage() in the GCMIntentService class doesn't get hit.
I can't understand how it can successfully register with the server, passing it's registrationId, yet when that registrationId is used to send a message back to the emulator it doesn't get received. I have not altered the demo app code.
Anyone ideas what could be going where or where I could start looking for problems as I don't even know where to start with this.
-5721079 0 Issue with transferring of developer certificate and Provisioning Profile under XcodeI am trying transfer my developer certificate under the keychain to someone. I exported the item. And also send him the provisioning profile which includes his device ID. He installed my certificate to his keychain and also the provisioning profile to his xcode. However, The provisioning profile under his xcode complains of there's no Valid signing Identity. Well I already sent him the certificate.
What's wrong?
-15025659 0if( browser.Button("id").Enabled) Console.Write("Enabled"); else Console.Write("Disabled");
you can try this.
-10101095 0 Please explain the behaviour of Rails's cache in this caseImagine I have 5 tags: tag1,tag2...tag5
. If I do the following:
Rails.cache.fetch("all.tags") { Tag.all }
and afterwards I write Rails.cache.fetch("all.tags")
, I see the 5 tags. If I add another tag, and I try to fetch from the cache again, the new tag is also loaded. Why is that?
EDIT: Here's my actual code:
Rails.cache.fetch("autocomplete.#{term}") { puts "Cache miss #{term}"; Tag.starting_with(term) }
Where starting_with
is doing a where to find tags starting with certain letters. Here's the behaviour I get in the console:
1.9.3p125 :046 > Rails.cache.read("autocomplete.ta") Tag Load (1.0ms) SELECT "tags".* FROM "tags" WHERE (name like 'ta%') => [#<Tag id: 10, name: "tag1">, #<Tag id: 11, name: "tag2">, #<Tag id: 12, name: "tag3">, #<Tag id: 13, name: "tag4">] 1.9.3p125 :048 > Tag.create(name:"tag5") (0.2ms) begin transaction SQL (1.0ms) INSERT INTO "tags" ("name") VALUES (?) [["name", "tag5"]] (150.9ms) commit transaction => #<Tag id: 14, name: "tag5"> 1.9.3p125 :049 > Rails.cache.read("autocomplete.ta") Tag Load (0.8ms) SELECT "tags".* FROM "tags" WHERE (name like 'ta%') => [#<Tag id: 10, name: "tag1">, #<Tag id: 11, name: "tag2">, #<Tag id: 12, name: "tag3">, #<Tag id: 13, name: "tag4">, #<Tag id: 14, name: "tag5">]
-17066858 0 It is a typo indeed
<? require($_SERVER["DOCUMENT_ROOT"] . '/WestAncroftSettings.php' ); ?>
should be
<?php require($_SERVER["DOCUMENT_ROOT"] . '/WestAncroftSettings.php' ); ?>
and later in your code you have the same line again without <?php
and your missing quotes around DOCUMENT_ROOT
I am working for a web application using praat features. I have written a script for that and it is working fine in ubuntu. But now i want to run these .praat scripts in a remote ubuntu server and I have already installed praat but when I run praat it gives me the following error:
(praat:1364): GLib-GObject-WARNING **: invalid (NULL) pointer instance
(praat:1364): GLib-GObject-CRITICAL **: g_signal_connect_data: assertion 'G_TYPE_CHECK_INSTANCE (instance)' failed
(praat:1364): Gtk-WARNING **: Screen for GtkWindow not set; you must always set a screen for a GtkWindow before using the window
(praat:1364): Gdk-CRITICAL **: IA__gdk_screen_get_default_colormap: assertion 'GDK_IS_SCREEN (screen)' failed
(praat:1364): Gdk-CRITICAL **: IA__gdk_colormap_get_visual: assertion 'GDK_IS_COLORMAP (colormap)' failed
(praat:1364): Gdk-CRITICAL **: IA__gdk_screen_get_default_colormap: assertion 'GDK_IS_SCREEN (screen)' failed
(praat:1364): Gdk-CRITICAL **: IA__gdk_screen_get_root_window: assertion 'GDK_IS_SCREEN (screen)' failed
(praat:1364): Gdk-CRITICAL **: IA__gdk_screen_get_root_window: assertion 'GDK_IS_SCREEN (screen)' failed
(praat:1364): Gdk-CRITICAL **: IA__gdk_window_new: assertion 'GDK_IS_WINDOW (parent)' failed Segmentation fault (core dumped)
Please tell me way a that I can run a praat script in remote ubuntu server.
-11334903 0I guess you are not using server side code. If that is the case, I suggest you to read this short tutorial on Javascript and cookies from w3schools:
http://www.w3schools.com/js/js_cookies.asp
-26632555 0I think that instead of build a table of images I would put the first image and I would store the url of the others images ina javascript variable. Then, when you want to load the others images (timer, click event, ...) you just have to change the src parameter of the original image.
-39902288 0 Opening a form, closing it, then opening it again in the same locationI have a pop up selector for my main form that comes up when I click a button. After I make my selection the box is closed and I continue my work in the main form. However if I go to click that button again, the pop up will appear slightly under where it had opened up previously. Is there a way to fix this so that every time that form is opened it opens in the same spot?
-6968494 0Perhaps the problem is already at the point where you malloc
your data
. It gets past around wrong (0x4
isn't plausible) so probably you already have had problems there. A common error is to forget to include the header file and have malloc
interpreted as returning int
per default rules.
Casting almost always hides a programming or, worse, design error:
malloc
. malloc
returns void*
this is compatible with any other data type pointervoid*
as you do when calling pthread_create
. All data type pointers are converted to void*
without problemsLevel: Beginner
In the following code my 'samePoint' function returns False where i am expecting True. Any hints?
import math class cPoint: def __init__(self,x,y): self.x = x self.y = y self.radius = math.sqrt(self.x*self.x + self.y*self.y) self.angle = math.atan2(self.y,self.x) def cartesian(self): return (self.x, self.y) def polar(self): return (self.radius, self.angle) class pPoint: def __init__(self,r,a): self.radius = r self.angle = a self.x = r * math.cos(a) self.y = r * math.sin(a) def cartesian(self): return (self.x, self.y) def polar(self): return (self.radius, self.angle) def samePoint(p, q): return (p.cartesian == q.cartesian) >>> p = cPoint(1.0000000000000002, 2.0) >>> q = pPoint(2.23606797749979, 1.1071487177940904) >>> p.cartesian() (1.0000000000000002, 2.0) >>> q.cartesian() (1.0000000000000002, 2.0) >>> samePoint(p, q) False >>>
source: MIT OpenCourseWare http://ocw.mit.edu Introduction to Computer Science and Programming Fall 2008
-4612798 0 In SQL Server 2008, how do I check if a varchar parameter can be converted to datatype money?I've got a stored procedure I use to insert data from a csv. The data itself is a mix of types, some test, some dates, and some money fields. I need to guarantee that this data gets saved, even if it's formatted wrong, so, I'm saving them all to varchars. Later, once the data's been validated and checked off on, it will be moved to another table with proper datatypes.
When I do the insert into the first table, I'd like to do a check that sets a flag (bit column) on the row if it needs attention. For instance, if what should be a money number has letters in it, I need to flag that row and add the column name in an extra errormsg field I've got. I can then use that flag to find and highlight for the users in the interface the fields they need to edit.
The date parameters seem to be easy, I can just use IF ISDATE(@mydate) = '0'
to test if that parameter could be converted from varchar to datetime. But, I can't seem to find an ISMONEY(), or anything that's remotely equivalent.
Does anyone know what to call to test if the contents of a varchar can legitimately be converted to money?
EDIT: I haven't tested it yet, but what do you think of a function like this?:
CREATE FUNCTION CheckIsMoney ( @chkCol varchar(512) ) RETURNS bit AS BEGIN -- Declare the return variable here DECLARE @retVal bit SET @chkCol = REPLACE(@chkCol, '$', ''); SET @chkCol = REPLACE(@chkCol, ',', ''); IF (ISNUMERIC(@chkCOl + 'e0') = '1') SET @retVal = '1' ELSE SET @retVal = '0' RETURN @retVal END GO
Update
Just finished testing the above code, and it works!
-27756694 0To change from a many-to-many relationship to a one-to-one, start by removing the best_friends
table.
friends = db.Table('friends', db.Column('user_id', db.Integer, db.ForeignKey('user.id')), db.Column('friend_id', db.Integer, db.ForeignKey('user.id')) )
You then want to add a foreign key to User
that references another User
.
class User(db.Model): id = db.Column(db.Integer, primary_key = True) name = db.Column(db.String(50), index=True, unique= True) email = db.Column(db.String(50),index=True, unique= True) bestfriend_id = db.Column(db.Integer, db.ForeignKey('user.id')) bestfriend = db.relationship('User', remote_side=['id'], lazy='dynamic') def are_bestfriends(self, user): return self.best_friend == user def be_bestfriend(self, user): if not self.are_bestfriends(user): self.bestfriend = user user.bestfriend = self return self
-12452961 0 How to get city code weather in AccuWeather? Have someone ever use AccuWeather to search your country weather? I want to get my city weather code in AccuWeather who can help me? The code generate has form like this: EUR|DE|GM014|TORGAU. I can't find my city code (Phnom Penh, Cambodia)
-25054125 0 ASP MVC / EF6 - Automatic loggingEvery table of my database has got 2 columns at the end, which allows logging (User who made the action, and Date of the action). EDIT : I use Code-First migrations.
So I would like those two logging columns to be filled automatically :
Each time I insert a new entry in my table (using DbContext.[Model].Add(entry))
OR each time I do a DbContext.SaveChanges() action
I have considered overriding the DbContext.SaveChanges() method, but it didn't work out...
I have also tried overriding the DbSet Add() method, to do the log filling action there. For that I have created a CustomDbSet class which inherits from DbSet :
public class CustomDbSet<TEntity> : DbSet<TEntity> where TEntity : class { public TEntity Add(TEntity entity) { //Do logging action here return base.Add(entity); } }
But this didn't make it neither.
EDIT : What happens with this CustomDbSet is that any DbContext.[Model] returns null, now (instead of being filled with the content of the database table)
I already have the extension method which will do the logging action, but I don't know where to put it so logging would become an "automatic" action..
public static void EntityLogCreate<T>(this T model, string userName) where T : LogColumns { model.Create_User = userName; model.Create_Date = DateTime.Now; }
Any idea to achieve that ?
-1514725 0Usually when I have come across this it has been a fatal error in PHP somewhere. Have a look at your PHP-cgi log to see if it is in there. There should be something in the nginx log like this: 104: Connection reset by peer
. Depending on your setup this (sorry, link dead) might help but if you're using php-fpm it won't.
I made some jQuery code for preventing users from typing chars but only numbers:
$("div").on("keydown", ":text", checkKey); function checkKey(e) { var n = e.keyCode; if (n == 13) { $(this).closest("form").submit(); console.log('enter'); } else if (e.shiftKey || e.ctrlKey || e.altKey) { e.preventDefault(); } else { if (!((n == 8) || (n == 46) || (n == 9) || (n >= 35 && n <= 40) || (n >= 48 && n <= 57) || (n >= 96 && n <= 105)) ) { e.preventDefault(); console.log('ok'); } } }
end in html:
<div> <input type="text" id="test" /> </div>
but whenever I type something, it seems it's being fired three times for example for one pressing enter I get three 'enter' in console and for numbers I get three 'ok', why is that? I also replaced it with delegate and live, live worked fine but delegate also was fired three times. thanks.
-22503882 0 What does the read call return on earth if there are already both FIN and RST in the TCP buffer?Assuming that the client and server send packets according to the order of sequence as shown in the figure, the client does not know FIN has arrived.
It sends “hello again” to the server, the server responds to the client with an RST and the RST has arrived. Then if the client is blocking on a read, why it return 0 due to the FIN instead of -1 because the RST? In the 《Effective TCP/IP programming》, it tells us that the core will return ECONNRESET error.
My operating system is Ubuntu 12.10. Is it related with the operating system? Please tell me some TCP’s details on this implementation. Thanks in advance.
I have a batch file which is asking for some user input text in the middle of that process. I need to run this batch file through c# code. I cannot change the bat file. So the option having command line arguments also is not working for me. Is there any way that i can provide the input when it prompts?
-12585443 0Use mysql_fetch_row()
to get the $amount_data.Mysql_query() returns only the resouce id
$amount_data = mysql_query ("SELECT * FROM subscriber WHERE payment_amount = '$payment_amount' AND id = '$id' "); $row = mysql_fetch_row($amount_data); echo $row[0];
Check the link http://php.net/manual/en/function.mysql-fetch-row.php
-2791931 1 Speed vs security vs compatibility over methods to do string concatenation in PythonSimilar questions have been brought (good speed comparison there) on this same subject. Hopefully this question is different and updated to Python 2.6 and 3.0.
So far I believe the faster and most compatible method (among different Python versions) is the plain simple +
sign:
text = "whatever" + " you " + SAY
But I keep hearing and reading it's not secure and / or advisable.
I'm not even sure how many methods are there to manipulate strings! I could count only about 4: There's interpolation and all its sub-options such as %
and format
and then there's the simple ones, join
and +
.
Finally, the new approach to string formatting, which is with format
, is certainly not good for backwards compatibility at same time making %
not good for forward compatibility. But should it be used for every string manipulation, including every concatenation, whenever we restrict ourselves to 3.x only?
Well, maybe this is more of a wiki than a question, but I do wish to have an answer on which is the proper usage of each string manipulation method. And which one could be generally used with each focus in mind (best all around for compatibility, for speed and for security).
Thanks.
edit: I'm not sure I should accept an answer if I don't feel it really answers the question... But my point is that all them 3 together do a proper job.
Daniel's most voted answer is actually the one I'd prefer for accepting, if not for the "note". I highly disagree with "concatenation is strictly using the + operator to concatenate strings" because, for one, join
does string concatenation as well, and we can build any arbitrary library for that.
All current 3 answers are valuable and I'd rather having some answer mixing them all. While nobody volunteer to do that, I guess by choosing the one less voted (but fairly broader than THC4k's, which is more like a large and very welcomed comment) I can draw attention to the others as well.
-31377154 0Expand the size of your q1
buffer. scanf("%s", q1)
doesn't have enough room to store the input. Remember that C uses a null character '\0'
to terminate strings. If you don't account for that, the buffer could overrun into other memory causing undefined behavior. In this instance, it's probably overwriting memory allocated to name
, so name
ends up pointing to "\0ick". This causes printf(%s)
, which looks for '\0'
to know when to stop printing, to think that the string is shorter than it really is.
The code works perfectly if you expand the buffer:
#include <stdlib.h> #include <stdio.h> #include <string.h> int main(void) { char name[50]; char q1[50]; printf( " What is your name?\n"); scanf("%49s", name); printf( " Hi %s, Do you want to have some fun? [Y/N]\n",name); scanf("%49s",q1); if(strcmp(q1,"Y") == 0||strcmp(q1,"y")==0) { printf("Awesome, let's play!\n"); } else { printf("Fine"); } printf( "So %s, it's time to get started\n", name); getchar(); return 0; }
Output:
What is your name? Nick Hi Nick, Do you want to have some fun? [Y/N] y Awesome, let's play! So Nick, it's time to get started
Note that I've added the qualifier %49s
to avoid buffer overruns like this.
You could also circumvent the need for another string entirely by changing char q1[50]
and scanf("%49s")
to simply char q1
and scanf("%c%*c", &q1)
(note the "address of" operator because q1
is no longer a pointer).
You'll probably even get a performance gain from this (albeit small), because strings are notorious memory hoggers. Comparing a single character is usually preferred over comparing strings.
#include <stdlib.h> #include <stdio.h> #include <string.h> int main(void) { char name[50]; char q1; printf( " What is your name?\n"); scanf("%49s%*c", name); printf( " Hi %s, Do you want to have some fun? [Y/N]\n",name); scanf("%c%*c",&q1); if(q1 == 'Y' || q1 == 'y') { printf("Awesome, let's play!\n"); } else { printf("Fine"); } printf( "So %s, it's time to get started\n", name); getchar(); return 0; } if(q1 == 'Y' || q1 == 'y') { printf("Awesome, let's play!\n"); } else { printf("Fine"); } printf( "So %s, it's time to get started\n", name); getchar(); return 0; }
If you go this route, you have to ignore the enter key using the format specifier %*c
because pressing enter sends a key to the stream as well.
I'm trying to sort trough a list of 32-bit numbers using MIPS assembler and xspim. I've been stepping trough my code to see what fails and noticed that when comparing 0x00000000 with 0xFFFFFFFF it doesn't switch those numbers as it should. At the point where the program fails I got 0x00000000 in $t3 and 0xFFFFFFFF in $t4 and it looks like this.
bge $t3,$t4,lol
#So if t3
is greater than or equal I should jump forward else continue. Now the problem is that the program jumps even though t3
is smaller.
I'm not sure where you quoted that from, it doesn't appear in the documentation at all. To actually quote from the documentation:
The
HashSet<T>
class is based on the model of mathematical sets and provides high-performance set operations similar to accessing the keys of theDictionary<TKey, TValue>
orHashtable
collections. In simple terms, theHashSet<T>
class can be thought of as aDictionary<TKey, TValue>
collection without values.
So it is a collection, containing actual values. The sentence you quoted there is false.
That being said, you could create an ISet<T>
implementation that works that way, e.g. representing numbers in a set as ranges. But trying to do that with a vanilla HashSet<T>
will quickly break down.
Use an initializer parameter:
static char calc_crc(char init, unsigned char *data, unsigned len) { for ( int i = 0 ; i < len; i++ ) init = init ^ data[i]; return init; }
Then you can do result=calc_crc(calc_crc(0,buffer1,buffer1len), buffer2, buffer2len);
-17294712 0I can't quite make out what you're trying to say. Are the folders still empty, or is there content in them now?
Git doesn't track folders, it only tracks files. So you can't add an empty folder into the Git repo, if that's what you're trying to do. If you really want the directory there, the standard practice is to add an empty .gitkeep
file into it, so that Git has some content to track there. Then you would git add foldername
and commit it.
Have a look at the documentation on the website but pretty sure it should be like below:
has_attached_file :avatar, :styles => { :thumb => ["32x32#", :png] }
https://github.com/thoughtbot/paperclip
Under post processing
Guess your issue is here:
@format = options[:format] @basename = File.basename(@file.path, @current_format) temp_file = Tempfile.new([@basename, @format].compact.join("."))
-33630716 0 You installed a jquery
module as global module.
If the module identifier passed to require()
is not a native module (e.g. http
), and does not begin with '/', '../', or './', then Node.js
starts at the parent directory of the current module, and adds /node_modules
, and attempts to load the module from that location.
If it is not found there, then it moves to the parent directory, and so on, until the root of the file system is reached.
To make global modules available to the Node.js (and CoffeeScript) REPL, it might be useful to also add the /usr/lib/node_modules
folder to the $NODE_PATH
environment variable. Since the module lookups using node_modules folders are all relative, and based on the real path of the files making the calls to require()
, the packages themselves can be anywhere.
Tough to answer without knowing more. Drupal is not very strong if all you're doing is building [x], where [x] is an online store, blog, forum, rss aggregation site, etc. We recently retooled our company store in Drupal using the Ubercart plugin suite, though, and were able to exercise a lot of control over the final results -- and more importantly, intgrate it better with the rest of our site's content.
That's where the real win is -- if you have lots of existing content and/or community, and you want that integrated smoothly with your store. We can do things like auto-suggest products from the store that match the tags on the articles a user is reading, give people access to private forums on our main site based on purchases they make in the store, etc.
If you aren't already an old hand with Drupal, and you don't need that kind of connection, it's probably better to go with a dedicated solution.
(Random notes: Article about putting up the store, podcast about same)
-6681159 0Instead of messing about with errorformat
, just set cscopequickfix
and use the normal :cscope
commands. eg. (from vim help)
:set cscopequickfix=s-,c-,d-,i-,t-,e-
Edit
You could also use a filter like the following to reorder the fields
sed -e 's/^\([^ ]\+\) \([^ ]\+\) \([^ ]\+\) \(.*\)$/\1 \3 \4 inside \2/'
set it to filter your message, then use the efm
errorformat=%f\ %l\ %m
-4693000 0 Your problem is the space after CMD=
. This evaluates to CMD=<empty string> "git --version"
. First, the environment variable CMD
is set to an empty string, then the command git --version
is called. Notice that due to the "..."
the shell really tries to execute a command git --version
and not git
with argument --version
. Simple remove the space between =
and "
to fix this.
Since CMIS was approved as a standard last month, the new best way to achieve this is probably via CMIS, as explained here.
-10330814 0Use REST; REST is nothing more than using plain HTTP 'better'. Since you are already using HTTP, somehow you are already doing REST like calls and moving these calls to full fledged REST will be easy.
Implementing REST calls is easy. You have two approaches:
Don't use SOAP. The only reason you would want to use SOAP is that you want to contractualise using a WSDL what you are exposing (you can do the same with REST btw, see the Amazon documentation for instance). Trust me, SOAP is way too heavy and confusing for what you are trying to do.
-34693184 0Do I need to include ;WITH CTE_Backup AS at the beginning of the query when I use it in Java code?
Yes you should, otherwise use simple subquery:
SELECT D.name ,ISNULL(CONVERT(VARCHAR,backup_start_date),'No backups') AS last_backup_time ,D.recovery_model_desc ,state_desc, CASE WHEN type ='D' THEN 'Full database' WHEN type ='I' THEN 'Differential database' WHEN type ='L' THEN 'Log' WHEN type ='F' THEN 'File or filegroup' WHEN type ='G' THEN 'Differential file' WHEN type ='P' THEN 'Partial' WHEN type ='Q' THEN 'Differential partial' ELSE 'Unknown' END AS backup_type ,physical_device_name FROM sys.databases D LEFT JOIN ( SELECT database_name,backup_start_date,type,physical_device_name ,Row_Number() OVER(PARTITION BY database_name,BS.type ORDER BY backup_start_date DESC) AS RowNum FROM msdb..backupset BS JOIN msdb.dbo.backupmediafamily BMF ON BS.media_set_id=BMF.media_set_id ) AS CTE ON D.name = CTE.database_name AND RowNum = 1 ORDER BY D.name,type;
Common Table Expression is nice readable way to introduce derived tables.
-14462559 0One solution is to translate the mesh geometry, and compensate by changing the mesh position, like so:
var offset = objMesh.centroid.clone(); objMesh.geometry.applyMatrix(new THREE.Matrix4().makeTranslation( -offset.x, -offset.y, -offset.z ) ); objMesh.position.copy( objMesh.centroid );
updated fiddle: http://jsfiddle.net/Ldt7z/165/
P.S. You do not need to save your fiddle before running it. There is no reason to have so many versions.
three.js r.55
-36542725 0Niknam ansuwer is perfect and I want to add if you use tor just add in your environment
export _JAVA_OPTIONS="-DsocksProxyHost=127.0.0.1 -DsocksProxyPort=9050"
-2651470 0 The most common path is to include a licensing notice at the top of files inside block comments - that's the way most likely to ensure that anyone utilizing the code is aware of the license, since the only possible way for it to be decoupled from the code is someone intentionally removing it.
-31319822 0 Modal is coming back undefined in directiveGoogle is giving me the error: "TypeError: Cannot read property 'open' of undefined" in response to my ui-bootstrap module. I've been using other ui-bootsrap directives fine.
Am I not declaring the modal dependency correctly?
angular.module('ireg').directive('study', function (studyFactory) { return { restrict:'E', scope: { objectid:'@objectid' }, templateUrl: '/ireg/components/study/study.html', link: function (scope, element, attrs, $modal) { scope.openMilestonesDialog = function () { var modalInstance = $modal.open({ animation: $scope.animationsEnabled, templateUrl: '/ireg/components/add-milestones/addMilestonesDialog.html', controller: '/ireg/components/add-milestones/addMilestonesDialogController.js', size: lg }); }; }//end of link } }); angular.module('ireg').controller('addMilestonesDialogController', function ($scope, $modalInstance, studyId) { $scope.ok = function () { $modalInstance.close(); }; });
-34939698 0 out.println () is a little ugly in terms of readability - but the cost of these calls will be small compared to I/O times.
Using + for String concatenation inside your loop might harm your memory footprint (and it's not the fastest way either). Consider this line you have:
out.println("<td>"+ rs.getString("FirstName") + " " + rs.getString("LastName") + "</td>");
You could gain readability and speed and have less char [] left to be garbage collected by coding with format()
:
out.format ("<td>%s %s</td>", rs.getString ("FirstName"), rs.getString ("LastName"));
More Notes
You create and connect a new database connection every time your servlet is called. This will severly impact your performance and scalability. You should consider using a connection pool from which you fetch pre-connected Connections. The performance you gain will make up for very many String concats or println calls.
-3186544 0 iOS4 and audio playback during backgroundingWhen my app is backgrounded, the audioplayer continues to play, but i cant hear any sound. When i open my app again, it plays from the point where it would have been had the app not been backgrounded at all. This shows that the app is playing in the background though it is not audible. Why could this be happening?
I have set the audio key in the info.plist for the UIBackgroundModes array. Also my audioplayer is set to the "AVAudioSessionCategoryPlayback" category with an override to allow for audio mixing. So what am i doing wrong that im unable to hear the audio even though it is playing in the background?
Could this be an issue with the simulator alone as i have not been able to test this on a device with iOS4 so iv only been testing it on the simulator.
-2633115 0 Java GUI File MenuI have a GUI with a Menu named file
how do I Add a file open and close function to the program. If the program is in the encrypting mode, it should load/save the cleartext text area. If the program is in decrypting mode, it should load/save the ciphertext area.
-40014705 0 How to convert a “String” value to “Type” in Angular 2 TSThis is my current object, Home refers to my import
import { Home } from '../home/home'; arr = [ { name: "Home", root: "Home", icon: "calc" } ];
This is what i want to achieve:
import { Home } from '../home/home'; arr = [ { name: "Home", root: Home, icon: "calc" } ];
Im getting a error because "Home" is a string. eval() works but i'm looking for a alternative
Working code:
for (var i = 0; i < arr.length; i++) { arr[i].root = eval(arr[i].root); }
-13516947 0 how to make a connection to datastore inside jstl tags I'm making a project on Google App Engine and in one of my jsp files, I want to search an entry in my datastore. I normally do this search by clicking on a button on this jsp page, then I make the connection to datastore in a servlet and then I send the query results to jsp back . Well, I want to query datastore without clicking this button. When I load the page, I want to see the query results on my page. When I was using EL tag lib, I could do that by just typing <% %>, now I'm using jstl tag lib. So is there any way to do ? After using jstl tags, I'm not able to use EL tags.
-26092740 0System.out.println((int)(5.4%((int)5.4)*10));
Basically 5.4 mod 5
gets you .4 * 10
gets you 4
.
I'm writing a unit test and the piece of code its testing requires that a file be in Request.Files.
In my controller I'm calling something called AddDocument(file)
and the file is taken from Request.Files.
How do you achieve unit testing this? Isn't the Request only available in the controller?
-29722509 0 Foreach loop - three columns(dynamic) table layouti have the below code, which will create a table with three columns.
<?php $t = array(' 1 ' , ' 2 ' ,' 3 ', ' 4 ' , ' 5 '); $count = 0; $col =3; echo '<table><tr>'; foreach($t AS $r){ $count++; echo '<td> '.$r.' </td>'; if($count == $col){ echo '</tr><tr>'; $count = 0; } } echo '</tr></table>'; ?>
but what i really want is for the first column to have at least 4 rows before creating a new column and so on. max number of columns is 3 and each column should have at least 4 rows.
-10580465 0 How can I populate Viewmodel list collectionHow can I populate list collection in ViewModel
Controller:
SchoolEntities db = new SchoolEntities(); public ActionResult Index() { var student= from s in db.Students select s.Name.ToList(); return View(); }
ModelView:
public List<Student>students { get; set;}
-23015705 0 Try this....
ScriptManager.RegisterStartupScript(this, this.GetType(), "onclick", "javascript:window.open( 'SomePage.aspx','_blank','height=600px,width=600px,scrollbars=1');", true);
-9039733 0 I believe it's working the way it's supposed to. If you want arrivingLabelRed to end with it's alpha at 0 you should set it that way in the completion block.
-20014967 0 How can remove white screen when page changes one to another page?I have done my application in iphone using phonegap and jquery mobile. It is major project and it is totally completed. But there is one problem , in application pages load using rel="external" , when page changes one to another page in between 2 to 3 seconds screen display totaly white, that time don't want to display white screen. Anybody idea what can we do for that ? and don't reply with remove rel="external".
-9626322 0 Apache + NginX reverse proxy: serving static and proxy files within nested URLsI have Apache running on my server on port 8080 with NginX running as a reserve proxy on port 80. I am attempting to get NginX to serve static HTML files for specific URLs. I am struggling to write the NginX configuration that does this. I have conflicting directives as my URLs are nested within each other.
Here's what I want to have:
One URL is at /example/
and I want NginX to serve a static HTML file located on my server at /path/to/www/example-content.html
instead of letting Apache serve the page to NginX.
Another URL is at /example/images/
and I want Apache to serve that page to NginX, just as it does for the rest of the site.
I have set up my nginx.conf file like this:
server { listen 80; server_name localhost; # etc... location / { proxy_pass http://127.0.0.1:8080/; } # etc...
My attempt to serve the static file at /example/
from NginX went like this:
location /example/ { alias /path/to/www/; index example-content.html; }
This works, but it means everything after the /example/
URL (such as /example/images/
) is aliased to that local path also.
I would like to use regex instead but I've not found a way to serve up the file specifically, only the folder. What I want to be able to say is something like this:
location ~ ^/example/$ { alias /path/to/www/example-content.html; }
This specifically matches the /example/
folder, but using a filename like that is invalid syntax. Using the explicit location = /example/
in any case doesn't work either.
If I write this:
location ~ ^/example/$ { alias /path/to/www/; index example-content.html; } location ~ /example/(.+) { alias /path/to/www/$1; }
The second directive attempts to undo the damage of the first directive, but it ends up overriding the first directive and it fails to serve up the static file.
So I'm at a bit of a loss. Any advice at all extremely welcome! Many thanks.
-33573673 0 Hiding flyout of a buttonI got my DataTemplate for items and within this DataTemplate I have such code:
<Button x:Name="DoneButton" Style="{StaticResource ButtonStyle1}" BorderThickness="1" Margin="0,0,20,0" HorizontalAlignment="Left" VerticalAlignment="Center" Grid.Column="2" Grid.Row="1" Width="50" Height="50" > <Image Source="Images/WPIcons/checked.png" Width="30" Height="30" Margin="-10,0,-10,0" /> <Button.Flyout> <Flyout x:Name="myFly"> <Grid Margin="10"> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <TextBlock Grid.Row="0" x:Uid="myNote" Text="Note: " Style="{StaticResource myText}" /> <TextBox Grid.Row="1" TextWrapping="Wrap" AcceptsReturn="True" Height="40" x:Name="note" Text="{Binding RecentNote, Mode=TwoWay}" Style="{StaticResource TextBoxStyle1}"/> <Button x:Name="CompletedButton" Command="{Binding CompletedCommand}" CommandParameter="{Binding}" Style="{StaticResource ButtonStyle1}" BorderThickness="1" HorizontalAlignment="Left" VerticalAlignment="Center" Grid.Row="2" Click="CompletedButton_Click" Content="Done" MinWidth="80" Height="40" /> </Grid> </Flyout> </Button.Flyout> </Button>
After the flyout for the item has been called and user put his data in it I want to hide this flyout as soon as user hits the "Done" button (x:Name="CompletedButton").
I tried to do that in code behind like:
private void CompletedButton_Click(object sender, RoutedEventArgs e) { Button button = (Button)sender; Grid grid = (Grid)VisualTreeHelper.GetParent(button); Flyout fly = (Flyout)VisualTreeHelper.GetParent(grid); fly.Hide(); }
But I get cast exception with that I can't cast ContentPresenter to Flyout so I guess it's not the way I look for. How I can hide this flyout?
-22359144 0use [[NSDate date] timeIntervalSince1970]
The keyword DISTINCT is used to eliminate duplicate rows from a query result:
SELECT DISTINCT ... FROM A JOIN B ON ...
However, you can sometimes (possibly even 'often', but not always) avoid the need for it if the tables are organized correctly and you are joining correctly.
To get more information, you are going to have to ask your question more clearly, with concrete examples.
-36864836 0 How to register a post type and taxonomy in WordPress and display in a page/single postI have a question about WordPress register post type:
How can I register a post type like portfolio
?
For example: In the WordPress dashboard, I can register a post type and taxonomy. After this I want to create a page to display all the portfolio and taxonomies like (portfolio.php) and display a single portfolio in a (single-portfolio.php).
Can someone explain this for me please?
-4254487 0Try setting up a view in the DB that applies the security filter to the records as needed, and then when retrieving records through L2S. This will ensure that the records that you need will not be returned.
Alternatively, add a .Where() to the query before it is submitted that will apply the security filter. This will allow you to apply the filter programmatically (in case it needs to change based on the scenario).
-26187227 0 Is this myFile = SD.open("test.txt", FILE_WRITE); class object usage good/possible in cppI have created a class object named myFile for a class File which is present in one of my cpp files (FILE.cpp) which I am calling in another file(SDtrail.cpp) where I am working on.
In SDtrail.cpp file I have defined a statement as shown below myFile = SD.open("test.txt", FILE_WRITE);
So, my doubt is can I declare like above statement or not as I think that this is the root cause of the following errors
error: no match for 'operator=' in 'myFile = SDClass::open(const char*, uint8_t)(((const char*)"test.txt"), 19u)'
error: could not convert 'myFile' to 'bool'
I know that SD.open("test.txt", FILE_WRITE); will provide 1(success) or 0(fail) as output and myFile is an object of my File class ( I have declared it as File myFile). I don't know whether a class object consists of a type declaration. (FYI: myFile = SD.open("test.txt", FILE_WRITE); worked perfectly when I ran that in my Arduino software and when I have printed the myFile variable I got 1 as an output.)
Thanks in advance.
-34832022 0Use another variable:
int dist=fillUps[index].calcDistance(); //or double, depands on the method's returning value fillUps[index].calcMPG(dist);
-25143478 0 Depending on which type of database you are using (SQL, Oracle ect..);To take the Previous days votes you can usually just subtract 1 from the date and it will subtract exactly 1 day:
Where Cast(Posts.modification_date - 1 as Date) = Votes.vote_date
or if modification_date is already in date format just:
Where Posts.modification_date - 1 = Votes.vote_date
-28354179 1 Why would django fail with server 500 only when Debug=False AND db is set to production database on Heroku? When we run $ python manage.py runserver --settings=project.settings.local
there are 4 different possible combinations:
The fourth one is simultaneously: the most important, the hardest to debug, and the only one that fails.
Our django settings are setup with this structure:
settings ├── base.py ├── __init__.py ├── local.py └── production.py
For this test we only used local.py
and modified the contents for each run.
For Debug=True and DB=local this is the local.py
file:
from project.settings.base import * DEBUG = True TEMPLATE_DEBUG = True DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': ***, 'USER': ***, 'PASSWORD': ***, 'HOST': 'localhost', 'PORT': '5432', } }
For Debug=False and DB=production this is the local.py
file used:
from project.settings.base import * ALLOWED_HOSTS = ['*'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': ***, 'USER': ***, 'PASSWORD': ***, 'HOST': '***.amazonaws.com', 'PORT': '5432', } }
We also ran it with Debug=True and DB=production as well as Debug=False and DB=local, both of which worked.
The DB settings were copied directly from the Heroku configuration and the connection to the database works great as long as Debug is set to True, so we're pretty sure it's not a DB schema or connection problem. We just can't figure out how it's possible that the production DB works when Debug is True, and it runs with DB set to False with the local DB, but for some reason when the two are combined it fails. We've also deployed the code to Heroku and confirmed that it runs with Debug set to True but fails with the same Server 500 error when Debug is set to False.
For reference, this is the contents of our base.py
:
import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = *** # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'appname', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'project.urls' WSGI_APPLICATION = 'project.wsgi.application' # Database # https://docs.djangoproject.com/en/1.6/ref/settings/#databases SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') # Internationalization # https://docs.djangoproject.com/en/1.6/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.6/howto/static-files/ STATIC_ROOT = 'staticfiles' STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), )
Our googling has come up with a lot of people misconfiguring the ALLOWED_HOSTS variable and ending up with similar symptoms but that doesn't seem to be our problem. Does anybody have any insight as to what could be causing this problem?
As requested, here is production.py, although it should be noted that this settings file was never used in this experiment.
from project.settings.base import * import dj_database_url DEBUG = False TEMPLATE_DEBUG = False ALLOWED_HOSTS = ['*', '.***.com', '.herokuapp.com', 'localhost', '127.0.0.1'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': ***, 'USER': ***, 'PASSWORD': ***, 'HOST': '***.amazonaws.com', 'PORT': '5432', } } STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
-1164933 0 WPF RibbonControlLibrary Can anyone tell me how to download Wpf RibbonControlLibrray and how to use it?
-26320408 0You can use that, im not using the prettiest way, but you can write a new accessor that injects that methods.
Classes:
class Container def property=(arg) arg.called_from = self.class @arg = arg end def property @arg end end class SomeClass def container_class @klass end def called_from=(klass) @klass = klass end end
Spec:
require_relative 'container' describe Container do let(:container) { Container.new } it 'passes message' do container.property = SomeClass.new expect(container.property.container_class).to eq Container end end
-11325145 0 Team City nightly build fails to start I have a Team City instance running on my PC.
I've set up a nightly build to run at midnight each night, even if there are no checkins to build.
I leave the PC locked at night so assume the build should trigger.
However I keep getting "Unable to collect changes", "Failed to start build", "Failed to collect changes, error: org.tmatesoft.svn.core.SVNException: svn: E210003: Unknown host MySVNServer".
If I set the build to run during the day, it triggers fine, even when the PC is locked.
I have a checkin triggered build, and a couple of others for 1 off ad-hoc builds to the same environment, they all run fine.
Will Team City build fail if I am not "logged in", is the fact the PC is locked causing the issue?
-36252837 0 Get parts of string after a certain word? ShellI have the following variable that contains a string displaying folders in a dir tree:
root/f1/f2/f3/f4/f5 root/f1/f2/f3/f4 root/f1/f2/f3
How would I go about removing everything that is before f2 so what I'm left with will be:
f2/f3/f4/f5 f2/f3/f4 f2/f3
?
-34221557 0 NodeJS/Express Service down error handlingI have my client
which is developed in angular
and i am trying to hit my api service[rest-ful]
.
If my service/server is down, how can i notify my client saying its down?
POST http://localhost:3000/login net::ERR_CONNECTION_REFUSED
In my console all i am getting is this error message,
api.login(username, password).success(function(response) { }).error(function(response, error){ //i am not getting any error message here. });
The login method is just a $http
call
login: function (username, password) { return $http.post('http://localhost:8080/login', { username: username, password: password }); }
-22610166 0 You can bind Media Element directly from the view model
in xaml:
<ContentControl Content="{Binding MediaElementObject}"/>
in ViewModel:
private MediaElement _mediaElementObject; public MediaElement MediaElementObject { get { return _mediaElementObject; } set { _mediaElementObject = value;RaisePropertyChanged(); } }
And on OnNavigatedTo
Override method you can create it's new object & can register it's events.
MediaElementObject=new MediaElement();
So that you can do all thing from the viewmodel itself.
-35665366 0Try to clean your project and rebuild it
-28979557 0see this Fiddle
you just need to set hours to midnight 12. You can do it like this d.setHours(0,0,0,0);
var today = true; var d = new Date(), till = new Date(), t, h, m; d.setHours(0, 0, 0, 0); if (today) { till.setDate(d.getDate() + 1); till.setHours(0, 0, 0, 0); while (d <= till) { h = d.getHours(); m = d.getMinutes(); t = h % 12; t = t == 0 ? 12 : t; $('#time').append('<li>' + (t < 10 ? '0' : '') + t + ':' + (m < 10 ? '0' : '') + m + ' ' + (h < 12 || h == 24 ? 'AM' : 'PM') + '</li>'); d.setMinutes(m + 15); } } else { // print full list of time }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <div id="time"></div>
I have a file like below
<AUDIT_RECORD TIMESTAMP="2013-07-30T17:52:29" NAME="Query" CONNECTION_ID="10" STATUS="0" SQLTEXT="show databases"/> <AUDIT_RECORD TIMESTAMP="2013-07-29T17:27:53" NAME="Quit" CONNECTION_ID="12" STATUS="0"/> <AUDIT_RECORD TIMESTAMP="2013-07-30T17:52:29" NAME="Query" CONNECTION_ID="10" STATUS="0" SQLTEXT="show grants for root@localhost"/> <AUDIT_RECORD TIMESTAMP="2013-07-30T17:52:29" NAME="Query" CONNECTION_ID="10" STATUS="0" SQLTEXT="create table stamp like paper"/>
Here each record begin with <AUDIT_RECORD
and end with "/>
and the record might spread across multiple lines.
My requirement is to display result like below
<AUDIT_RECORD TIMESTAMP="2013-07-30T17:52:29" NAME="Query" CONNECTION_ID="10" STATUS="0" SQLTEXT="show databases"/> <AUDIT_RECORD TIMESTAMP="2013-07-30T17:52:29" NAME="Query" CONNECTION_ID="10" STATUS="0" SQLTEXT="show grants for root@localhost"/> <AUDIT_RECORD TIMESTAMP="2013-07-30T17:52:29" NAME="Query" CONNECTION_ID="10" STATUS="0" SQLTEXT="create table stamp like paper"/>
for that purpose I have used
sed -n "/Query/,/\/>/p" file.txt
but it is displaying the entire file including the record with the string "Quit".
Can anyone help me regarding this? Also please let me know if it is possible to match exactly string named "Query" ( like grep -w "Query"
).
For example if brand id is 100
:
select b.id, sum(h.points),h.brandId from brands b left join histories h on b.id = h.brandid and h.userId = 2866 where b.id=100 group by b.id limit 1;
-27559237 0 Possible arrangements of binary vectors keeping sum fixed in R Suppose we have fixed row sums for a matrix (say, MAT) of dimension 3 x N which (i.e the row sums) are = (RS,LS,NCS)'. The N column vectors are unknown. There are 3 possible choices for each of the N column vectors - (1,0,0)', (0,1,0)', (0,0,1)'.
So the first question is -
How can we get all possible choices of this matrix MAT by keeping the row sums fixed as (RS,LS,NCS)' using R software ?
For example - Take N=7, RS=sum of first row=2, LS=sum of second row=2 and NCS=sum of third row=3. So (1,0,0)' will appear twice, (0,1,0)' will also appear twice and (0,0,1)' will appear thrice in the set of N columns of that matrix MAT. One possible choice of MAT is -
1 0 0 0 0 1 0
0 1 0 0 0 0 1
0 0 1 1 1 0 0
I think there will be 7!/(2!x2!x3!)=210 possible choices of MAT by keeping the row sum fixed as (2,2,3)'.
But how to get those possible choices of MAT using R software ? It should be an array of dimension 3xNxn, where n is the number of possible choices of MAT.
The second question is-
How the solution mechanism changes in the above problem if the possible choices of each of the N column vectors of that matrix MAT becomes - (1,1,0)', (1,0,0)', (0,1,0)', (0,0,1)' ?
-38863310 0 How to jump to an another line of code while executing an Android appI want to know how to jump to an another line of code while executing an Android app.
Here is my problem in detail.
First of all, here is my code:-.
listView.setOnItemClickListener (new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { int Current_Song; Songs song = Song.get(i); //If mediaPlayer is not used before, this will make oldsong as present song. if (Old_Song == -326523) { Old_Song = song.getSong(); } Current_Song = song.getSong(); ImageView IVP_P = (ImageView) findViewById(R.id.P_PImage); //If mediaPlayer is paused. if (IsPaused) { P_and_P.setImageResource(R.drawable.ic_pause_white_48dp); //If the song paused is same as the new song. if (Current_Song == Old_Song) { mediaplayer.start(); } //If the song Paused is not the new song. else { if (mediaplayer != null) { mediaplayer.release(); mediaplayer = null; } int result = mAudioManager.requestAudioFocus(mOnAudioFocusChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT); if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { mediaplayer = mediaplayer.create(SongsListActivity.this, song.getSong()); Old_Song = song.getSong(); NameD.setText(song.getNameOfSong()); RateD.setText(song.getDeveloperRate()); ImageD.setImageResource(song.getImage()); mediaplayer.start(); mediaplayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mediaPlayer) { P_and_P.setImageResource(R.drawable.ic_play_arrow_white_48dp); IsPaused = true; } }); } } IsPaused = false; } else if (mediaplayer != null) { //If mediaPlayer is already Playing a song. if (mediaplayer.isPlaying()) { P_and_P.setImageResource(R.drawable.ic_play_arrow_white_48dp); mediaplayer.pause(); IVP_P.setImageResource(R.drawable.ic_play_arrow_black_24dp); IsPaused = true; } } //If mediaPlayer is used for first time and if mediaPlayer is neither paused else { if (mediaplayer != null) { mediaplayer.release(); mediaplayer = null; } int result = mAudioManager.requestAudioFocus(mOnAudioFocusChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT); if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { mediaplayer = mediaplayer.create(SongsListActivity.this, song.getSong()); Old_Song = song.getSong(); NameD.setText(song.getNameOfSong()); RateD.setText(song.getDeveloperRate()); ImageD.setImageResource(song.getImage()); mediaplayer.start(); P_and_P.setImageResource(R.drawable.ic_pause_white_48dp); mediaplayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mediaPlayer) { P_and_P.setImageResource(R.drawable.ic_play_arrow_white_48dp); IsPaused = true; P_and_P.setImageResource(R.drawable.ic_pause_white_48dp); } }); } } } } );
Now, whenever the execution enters into any if the onCompletion() method, i want want the execution to start execution from beginning of the onItemClick() method.
What should I do?
For being more detailed:-
Here my app displays a list of songs using ListView and Adapter. The details of songs are stored in a arrayList(As You All Can See).When an item is clicked, it gets the position of that item, then refers to the corresponding element of the arrayList, gets the location of the corresponding song and then plays that song. What I want is that when an song is over, and the method onCompletion() is called, I want to increase to value of i(look in the 4th line of my code) by one and then go to the first line of the onItemClick method.
-5349875 0 matlab "arrayfun" functionConsider the following function, which takes a gray image (2D matrix) as input:
function r = fun1(img) r = sum(sum(img));
I'm thinking of using arrayfun
to process a series of images(3d matrix), thus eliminating the need for a for
loop:
arrayfun(@fun1, imgStack);
But arrayfun
tries to treat every element of imgStack
as an input to fun1
, the result of the previous operation also being a 3D matrix. How can I let arrayfun
know that I want to repeat fun1
only on the 3rd dimension of imgStack
?
Another question, does arrayfun
invoke fun1
in parallel?
Simply adding your CustomPanel
to any other JComponent
and updating the UI should do the trick. Swing takes care of all the painting for you.
Here is a reslly useful guide to swing painting;
http://java.sun.com/products/jfc/tsc/articles/painting/#paint_process
When you use FileReader
and FileWriter
, they will use the default encoding for your platform. That's almost always a bad idea.
In your case, it seems that that encoding doesn't support U+0092, which is fairly reasonable given that it's a private use character - many encodings won't support that. I suspect you don't actually want (char) 144
at all. If you really, really want to use that character, you should use an encoding which can encode all of Unicode - I'd recommend UTF-8.
It's important to differentiate between text and binary, however - if you're really just interested in bytes, then you shouldn't use a reader or writer at all - use an InputStream
and an OutputStream
. Hex editors are typically byte-oriented rather than text-oriented, although they may provide a text view as well (ideally with configurable encoding). If you want to know the exact bytes in the file, you should definitely be using FileInputStream
.
You had a wonky join. Try:
select A1.* from Asset A1 left join AuditedItems A2 on A1.asset_number = A2.asset_number where A1.location_id = 15 and A2.asset_number is null
-3291303 0 C#: DataTable conversion row-by-row In an abstract class (C# 3), there is a virtual method named GetData
which returns a DataTable. The algorithm of the method is as following:
In the 3rd point, I clone the original DataTable in order to change the Type of column (I can't do that on populated table and can't setup this at the 2nd point) and enumerate every row in which I copy and transform data from the original one. Transformations depends on the class, every one has private methods which transforms data on its own.
The question is: How to make a method in a base class which will be based on the following three params: column name which will be converted, Type of new column and action during the transformation. Two first are quite simple but I'm not sure about the third one. I thought about designing a new class which will store these three parameters, and the action will be stored as following delegate:
public delegate object Convert(object objectToConvert);
The conversion would look something like that:
int rowCounter = 0; foreach(DataRow row in dt.Rows) { foreach(var item in Params) { row[item.ColumnIndex] = item.Convert(originalDataTable.Rows[rowCounter].ItemArray[item.ColumnIndex]); } ++rowCounter; }
For now, I have to override the method GetData()
in every class I want to have a transformations which causes a large duplication of code. The point I want to achieve is to make a base class which will be based on params I mentioned above. Is the above solution good for this problem or is it any other way to do that?
Coming from JUnit background I don't really understand the point of all the text in spockD tests, since they don't show on the output from the test.
So for example, if I have a constraint on a field Double foo with constraints foo max:5, nullable:false
And I write tests like this:
void "test constraints" { when: "foo set to > max" foo=6D then: "max validation fails" !foo.validate() when: "foo is null foo=null then: "null validation fails" !foo.validate() }
The test is well documented in its source, but if the validation fails, the error output doesn't take advantage of all this extra typing I've done to make my tests clear.
All I get is
Failure: | test constraints(com.grapevine.FooSpec) | Condition not satisfied: f.validate() | | | false
But I can't tell form this report whether it failed the null constraint or the max constraint validation and I then need to check the line number of the failure in the test source.
At least with JUnit I could do
foo=60D; assertFalse("contraints failed to block foo>max", f.validate()); foo=null; assertFalse("contraints failed to block foo=null", f.validate());
And then I'd get useful info back from in the failure report. Which seems to both more concise and gives a more informative test failure report.
Is there some way get more robust error reporting out of Spec that take advantage of all this typing of when and then clauses so they show up on failure reports so you know what actually fails? Are these "when" and "then" text descriptors only serving as internal source documentation or are they used somewhere?
-15707923 0 Get twitter entity value from json with PHPI am looping through each tweet in json feed from twitter. The first part of the code works perfectly...
$screen_name = "BandQ"; $count = 10; $urlone = json_decode(file_get_contents("http://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=false&screen_name=BandQ&count=".$count."&page=1"),true); $urltwo = json_decode(file_get_contents("http://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=false&screen_name=BandQ&count=".$count."&page=2"),true); $data = array_merge_recursive( $urlone, $urltwo); // Output tweets //$json = file_get_contents("http://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=false&screen_name=".$screen_name."&count=".$count."", true); //$decode = json_decode($json, true); $count = count($data); //counting the number of status $arr = array(); for($i=0;$i<$count;$i++){ $text = $data[$i]["text"]." "; $retweets = $data[$i]["text"]."<br>Retweet Count: ".$data[$i]["retweet_count"]. "<br>Favourited Count: ".$data[$i]["favorite_count"]."<br>".$data[$i]["entities"]["user_mentions"][0]["screen_name"]."<br>"; // $arr[] = $text; $arr[] = $retweets; } // Convert array to string $arr = implode(" ",$arr); print_r($arr);
but when I try to get entities->user_mentions->screen_name the PHP throws errors...
Notice: Array to string conversion in C:\xampp\htdocs\tweets.php on line 29 Notice: Use of undefined constant user_mentions - assumed 'user_mentions' in C:\xampp\htdocs\tweets.php on line 29 Notice: Use of undefined constant screen_name - assumed 'screen_name' in C:\xampp\htdocs\tweets.php on line 29
How do I get that screen_name value?
Many thanks
-7456037 0SELECT ACOS(COS(RADIANS(lat)) * COS(RADIANS(lon)) * COS(RADIANS(34.7405350)) * COS(RADIANS(-92.3245120)) + COS(RADIANS(lat)) * SIN(RADIANS(lon)) * COS(RADIANS(34.7405350)) * SIN(RADIANS(-92.3245120)) + SIN(RADIANS(lat)) * SIN(RADIANS(34.7405350))) * 3963.1 AS Distance FROM Stores WHERE 1 HAVING Distance <= 50
Here's how I use it in PHP:
// Find rows in Stores within 50 miles of $lat,$lon $lat = '34.7405350'; $lon = '-92.3245120'; $sql = "SELECT Stores.*, ACOS(COS(RADIANS(lat)) * COS(RADIANS(lon)) * COS(RADIANS($lat)) * COS(RADIANS($lon)) + COS(RADIANS(lat)) * SIN(RADIANS(lon)) * COS(RADIANS($lat)) * SIN(RADIANS($lon)) + SIN(RADIANS(lat)) * SIN(RADIANS($lat))) * 3963.1 AS Distance FROM Stores WHERE 1 HAVING Distance <= 50";
-26319502 0 Uncaught ReferenceError: _ is not defined with Browserify I have a Backbone
project that requires a fair amount of shimming for browserify.
I have set it up so that all of my underscore files are concat'd into one file templates.js
In turn I have to shim this into my project:
package.json
"dependencies": { ..... "underscore": "^1.7.0" ..... } ...... "browserify": { "transform": [ "browserify-shim" ] }, "browser": { "//": "SP Core Components", "jst": "./jst/templates", }, "browserify-shim": { "jst" : {"depends": "underscore"} } .....
init.js
var JST = require('jst'); var jsonobject = {}; JST.staffOverview(jsonobject)
This will generate the following when trying to call :
Uncaught ReferenceError: _ is not defined
So my question is, how can I set underscore
as a dependency of jst
Ok, I found the answer. csl's answer set me on the right path.
pexpect has a "env" option which I thought I could use. like this:
a = pexpect.spawn('program', env = {"TERM": "dumb"})
But this spawns a new shell which does not work for me, our development environment depends on a lot of environmental variables :/
But if I do this before spawning a shell:
import os os.environ["TERM"] = "dumb"
I change the current "TERM" and "dumb" does not support colours, which fixed my issue.
-34244587 0Absolutely:
var View = React.View; /* later... */ propTypes: { ...View.propTypes, myProp: PropTypes.string }
-7819531 0 Try this way:
mProgressDialog.setProgressStyle(android.R.attr.progressBarStyleSmall);
-8982017 0 Design pattern for catching memory leaks in objective-c? I have read Apple's memory management guide, and think I understand the practices that should be followed to ensure proper memory management in my application.
At present it looks like there are no memory leaks in my code. But as my code grows more complex, I wonder whether there is any particular pattern I should follow to keep track of allocations and deallocations of objects.
Does it make sense to create some kind of global object that is present throughout the execution of the application which contains a count of the number of active objects of a type? Each object could increment the count of their type in their init method, and decrement it in dealloc. The global object could verify at appropriate times if the count of a particular type is zero of not.
EDIT: I am aware of how to use the leaks too, as well as how to analyze the project using Xcode. The reason for this post is to keep track of cases which may not be detected through leaks or analyze easily.
EDIT: Also, it seems to make sense to have something like this so that leaks can be detected in builds early by running unit tests that check the global object. I guess that as an inexperienced objective-c programmer I would benefit from the views of others on this.
-8242619 0standard in any enterprise web application is varchar with 255 length
varchar(255)
-8290882 0 1) A htaccess
is recursive by default
2) You can put some random garbages caracters in htaccess
, then call you web page. You should see an error 500
that attest that the htaccess
is used. That done, you can add your real configuration to finish.
I connected to a unix server through ssh and tried to execute a "ls" command and obtain it's output. The code is like this
SessionChannelClient session = client.openSessionChannel(); session.startShell(); String cmd = "ls -l"; session.executeCommand(cmd); ChannelInputStream in = session.getInputStream(); ChannelOutputStream out = session.getOutputStream(); IOStreamConnector input = new IOStreamConnector(System.in, session.getOutputStream()); IOStreamConnector output = new IOStreamConnector(session.getInputStream(), System.out);
After running I was not getting any output in log file. What I found is that the channel request is failing as shown
1019 [main] INFO com.sshtools.j2ssh.connection.ConnectionProtocol - Channel request succeeded 1020 [main] INFO com.sshtools.j2ssh.session.SessionChannelClient - Requesting command execution 1021 [main] INFO com.sshtools.j2ssh.session.SessionChannelClient - Command is ls -l 1021 [main] INFO com.sshtools.j2ssh.connection.ConnectionProtocol - Sending exec request for the session channel 1021 [main] INFO com.sshtools.j2ssh.transport.TransportProtocolCommon - Sending SSH_MSG_CHANNEL_REQUEST 1021 [main] INFO com.sshtools.j2ssh.connection.ConnectionProtocol - Waiting for channel request reply 1032 [Transport protocol 1] INFO com.sshtools.j2ssh.transport.TransportProtocolCommon - Received SSH_MSG_CHANNEL_EXTENDED_DATA 1033 [ssh-connection 1] DEBUG com.sshtools.j2ssh.transport.Service - Routing SSH_MSG_CHANNEL_EXTENDED_DATA 1033 [ssh-connection 1] DEBUG com.sshtools.j2ssh.transport.Service - Finished processing SSH_MSG_CHANNEL_EXTENDED_DATA 1075 [Transport protocol 1] INFO com.sshtools.j2ssh.transport.TransportProtocolCommon - Received SSH_MSG_CHANNEL_FAILURE 1075 [main] INFO com.sshtools.j2ssh.connection.ConnectionProtocol - Channel request failed
Why is this happening ?
-5254808 0In short, there is no such thing as Foo<String>
at runtime due to the type Type Erasure. The type information is lost.
Instead, you can expose Bar
as raw Foo
with service property typeArg=java.lang.String
and use filter when injecting it to the consumer.
Other way is to introduce interfaces FooString extends Foo<String> { }
, FooDouble extends Foo<Double> { }
and use them instead of Foo
.
Have you ever look servicestack ? It's awesome ,totally DTO based and very easy to create API for .net
Please look out my blog post about that
Check this thread for authentication options in ServiceStack.
https://groups.google.com/d/topic/servicestack/U3XH9h7T4K0/discussion
Look at example here
-18612637 0I had this code in a fragment and it was crashing if I try to come back to this fragment
if (mRootView == null) { mRootView = inflater.inflate(R.layout.fragment_main, container, false); }
after gathering the answers on this thread, I realised that mRootView's parent still have mRootView as child. So, this was my fix.
if (mRootView == null) { mRootView = inflater.inflate(R.layout.fragment_main, container, false); } else { ((ViewGroup) mRootView.getParent()).removeView(mRootView); }
hope this helps
-39145786 0 Create a row with subtotals above data to be added with a Loop through an array in VBAI need to programmatically format an excel table creating two different subtotals base on changes of values in two specified column (the first and second of the spreadsheet).
I managed to code the routine for the first subtotals but I’m now stuck trying to figure out the second part of the code.
In the second routine I need to create the subtotal row above the data that will be added. I couldn’t manage to insert the calculation in the right row and there is something wrong when I do the loop through the columns included in the array.
Anyone that can see what I’m doing wrong?
Thank you
Public Sub SubtotalTable() Dim RowNumber As Long Dim RangePointer As Range Dim RangeTopRow As Range 'Pointing the column to check Set RangePointer = ActiveSheet.Range("B1") 'Assigning the first row to a range Set RangeTopRow = Rows(2) 'Assigning to long a variable the number of row from which begin checking RowNumber = 3 Do If RangePointer.Offset(RowNumber).Value <> RangePointer.Offset(RowNumber - 1).Value Then Set RangeTopRow = Rows(RowNumber) 'Call the function to insert the row Call InsertRowTotalsAbove(RangePointer.Offset(RowNumber), RangeTopRow, RowNumber) Else RowNumber = RowNumber + 1 End If RowNumber = RowNumber + 1 Loop End Sub Public Function InsertRowTotalsAbove(RangePointer As Range, lastRow As Range, RowNumber As Long) Dim ArrayColumns() As Variant Dim ArrayElement As Variant Dim newRange As Range 'Assigning number of columns to an array ArrayColumns = Array("D", "E", "F", "G") Do If RangePointer.Offset(RowNumber).Value = RangePointer.Offset(RowNumber - 1).Value Then RowNumber = RowNumber - 1 Else ActiveSheet.Cells(RowNumber + 1, 2).Select Set newRange = Range(ActiveCell, ActiveCell.Offset(0, 0)) Rows(newRange.Offset(RowNumber + 1).Row).Insert shift:=xlDown newRange.Offset(RowNumber + 1, 0).Value = "Totale" & " " & newRange.Offset(RowNumber + 2, 0) For Each ArrayElement In ArrayColumns newRange.Cells(RowNumber, ArrayElement).Value = Application.WorksheetFunction.Sum(Range(lastRow.Cells(-1, ArrayElement).Address & ":" & RangePointer.Cells(0, ArrayElement).Address)) Next ArrayElement End If Loop End Function
-19890828 0 How can I do editable listview item? I have todolist application which includes task,priority,date,status and ı can add new item to list.When click the item another activity run.Here is the problem,ı cant get item's values for new activity and when i click edit button, program add new item without deleting old one.
here setOnItemClickListener
todoListView.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent editIntent = new Intent(MainActivity.this, EditItem.class); startActivityForResult(editIntent, EDIT_NOTE); } });
and OnActivityResult
protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == Activity.RESULT_OK) { switch (requestCode) { case ADD_NOTE: String extraName = AddItem.code; ArrayList<String> list = data .getStringArrayListExtra(extraName); todoItems.addAll(list); todoArrayAdapter.notifyDataSetChanged(); break; case EDIT_NOTE: String extraName2 = EditItem.code; ArrayList<String> list2 = data .getStringArrayListExtra(extraName2); todoItems.addAll(list2); todoArrayAdapter.notifyDataSetChanged(); break; default: break; } } super.onActivityResult(requestCode, resultCode, data); }
and EditItem.java
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.edit_item); editText1 = (EditText) findViewById(R.id.editText1); spinner = (Spinner) findViewById(R.id.prioritySpinner); datePicker = (DatePicker) findViewById(R.id.datePicker); toggleButton = (ToggleButton) findViewById(R.id.statusbutton); editButton = (Button) findViewById(R.id.editButton); cancelButton = (Button) findViewById(R.id.cancelButton); editButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { itemList = new ArrayList<String>(); item = editText1.getText().toString(); priorityLevel = spinner.getSelectedItem().toString(); status = toggleButton.getText().toString(); int day = datePicker.getDayOfMonth(); int month = datePicker.getMonth() + 1; int year = datePicker.getYear(); date = day + "/" + month + "/" + year; itemList.add(new Entry(item, priorityLevel, date, status) .toString()); Intent okIntent = new Intent(); okIntent.putExtra(code, itemList); setResult(Activity.RESULT_OK, okIntent); finish(); } });
-11680931 0 Nginx/Django Admin POST https only I've got an Nginx/Gunicorn/Django server deployed on a Centos 6 machine with only the SSL port (443) visible to the outside world. So unless the server is called with the https://
, you won't get any response. If you call it with an http://domain:443
, you'll merely get a 400 Bad Request message. Port 443 is the only way to hit the server.
I'm using Nginx to serve my static files (CSS, etc.) and all other requests are handled by Gunicorn, which is running Django at http://localhost:8000
. So, navigating to https://domain.com
works just fine, as do links within the admin site, but when I submit a form in the Django admin, the https is lost on the redirect and I'm sent to http://domain.com/
request_uri which fails to reach the server. The POST action does work properly even so and the database is updated.
My configuration file is listed below. The location location /
section is where I feel like the solution should be found. But it doesn't seem like the proxy_set_header X-*
directives have any effect. Am I missing a module or something? I'm running nginx/1.0.15.
Everything I can find on the internet points to the X-Forwarded-Protocol https
like it should do something, but I get no change. I'm also unable to get the debugging working on the remote server, though my next step may have to be compiling locally with debugging enabled to get some more clues. The last resort is to expose port 80 and redirect everything...but that requires some paperwork.
[http://pastebin.com/Rcg3p6vQ](My nginx configure arguments)
server { listen 443 ssl; ssl on; ssl_certificate /path/to/cert.crt; ssl_certificate_key /path/to/key.key; ssl_protocols SSLv3 TLSv1 TLSv1.1 TLSv1.2; ssl_ciphers HIGH:!aNULL:!MD5; server_name example.com; root /home/gunicorn/project/app; access_log /home/gunicorn/logs/access.log; error_log /home/gunicorn/logs/error.log debug; location /static/ { autoindex on; root /home/gunicorn; } location / { proxy_pass http://localhost:8000/; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Scheme $scheme; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Protocol https; } }
-30502870 0 Shiny slider on logarithmic scale I'm using Shiny to build a simple web application with a slider that controls what p-values should be displayed in the output.
How can I make the slider act on a logarithmic, rather than linear, scale?
At the moment I have:
sliderInput("pvalue", "PValue:", min = 0, max = 1e-2, value = c(0, 1e-2) ),
Thanks!
-9444159 0You should just let GetPassword()
return null
if the password isn't found. The next problem though is that CompareStringToHash()
will fail if you pass in a null password, so instead of
bool isSame = hasher.CompareStringToHash(txtPassword.Text, hashedPassword); if (isSame==false) { MessageBox.Show("Invalid UserName or Password"); }
You do
if (hashedPassword == null || hasher.CompareStringToHash(txtPassword.Text, hashedPassword) { MessageBox.Show("Invalid UserName or Password"); }
If hashedPassword
is null
the if
statement will be exited before it tries to execute the CompareStringToHash()
so you won't get an exception. CompareStringToHash()
will only execute if hashedPassword
is not null
. Then provided you've stored a valid string (which you will have because you are creating it will Encrypto) it should all work - and without a lot of messy if
statements :o)
I decided to post an answer to try and explain this situation for anyone else that arrives here from Google.
As David points out, to fix this error...
uninitialized constant Excel::Iconv
...you'll have to require "iconv":
require "iconv" require "roo"
This is because the Roo gem calls Iconv.new
in its internal Excel class but Roo forgot to require "iconv" itself, so you're forced to do it. It's a bug. It's no different than calling Set.new
without require "set"
Iconv is part of Ruby 1.8 and 1.9's standard library. You don't install it. It's already there.
However, it's worth pointing out that Iconv is deprecated in Ruby 1.9 and removed in Ruby 2.0.
-2510502 0One problem is that you have two AJAX calls - get
and load
. You don't need both.
Either use load
:
$("#content").load('pagination3.php?&category='+ this_id );
or get
:
$.get("pagination3.php", { category: this_id }, function(data){ $("#content").html(data); }, "html" );
(A side note here is that two calls are not necessarily wrong - they might both work. Also, watch out for SQL injection - you are very close..)
-11749002 0CUDA and TBB are optional, it shouldn't matter that they're not there.
.m
files are actually plain Matlab source, not anything compiled. In addition to a few .m
files, you should end up with a nearest_neighbors.mexa64
(or some other mex
extension depending on your platform) in the directory build/matlab/
.
This isn't going to be the same directory with the .m
and .cpp
files -- that's the source directory. You should probably run make install
to gather things either in /usr/local
, or somewhere else if you do cmake .. -DCMAKE_INSTALL_PREFIX=/wherever
. Then you'll have the .m
and .mexa64
(but not the .cpp
) files in /usr/local/share/flann/matlab/
.
Yes, they are both called "Year", but one is a static function and the other a property. You would need to use the "new" keyword added for the compiler to be happy.
public new readonly int Year;
-6629439 0 Variable length array allocation (or any array declaration actually) is done on the stack (assuming GCC compiler). Malloc assigns memory from the heap.
Two advantages to heap vs. stack: 1. Stack is much smaller. There is a decent chance that your variable-size array could cause your stack to overflow. 2. Items allocated on the stack don't survive after the function they were declared in returns.
-17187362 0 How to parse below JSONHow to parse below JSON code in javascript where iterators are not identical?
var js= { '7413_7765': { availableColorIds: [ '100', '200' ], listPrice: '$69.00', marketingMessage: '', prdId: '7413_7765', prdName: 'DV by Dolce Vita Archer Sandal', rating: 0, salePrice: '$59.99', styleId: '7765' }, '0417_2898': { availableColorIds: [ '249', '203' ], listPrice: '$24.95', marketingMessage: '', prdId: '0417_2898', prdName: 'AEO Embossed Flip-Flop', rating: 4.5, salePrice: '$19.99', styleId: '2898' }, prod6169041: { availableColorIds: [ '001', '013', '800' ], listPrice: '$89.95', marketingMessage: '', prdId: 'prod6169041', prdName: 'Birkenstock Gizeh Sandal', rating: 5, salePrice: '$79.99', styleId: '7730' } }
How can i parse this JSON in jvascript? I want the values of 'prdName', 'listprice', 'salePrice' in javascript?
-1712345 0You might need to consider using a different text box control.
Daniel Grunwald has written the Wpf text editor for SharpDevelop completely from scratch. It is called AvalonEdit and a good article is on codeproject:
http://www.codeproject.com/KB/edit/AvalonEdit.aspx
It seems that he has done optimizations for large files.
-21158408 0When references to data are passed around in LabVIEW internally, the data type is always passed around, too. Data is passed around as void pointers and the type is passed along with them. So any time LabVIEW sees your array, it'll also see that the type is a 2d array of int32s. (I work on the LabVIEW team at National Instruments)
-25581842 0 Array of File object is empty/null in struts 2 action while uploading multiple filesI am trying to upload multiple files in struts 2 application but every time I am getting File[] fileUpload
is empty . I have made several configuration changes in struts.xml
but still getting fileUplaod
object as either null or empty . Can someone tells me what am i supposed to do to get it working
The corresponding action code is as : In this action I am retrieving the file object array and printing the details
EDIT :
DummyFileUploadAction.java
:
package com.cbuddy.common.action; import java.io.File; import com.opensymphony.xwork2.ActionSupport; public class DummyFileUploadAction extends ActionSupport{ private File[] fileUpload; private String fileUploadFileName; private String[] fileUploadContentType; public File[] getFileUpload() { return fileUpload; } public void setFileUpload(File[] fileUpload) { this.fileUpload = fileUpload; } public String getFileUploadFileName() { return fileUploadFileName; } public void setFileUploadFileName(String fileUploadFileName) { this.fileUploadFileName = fileUploadFileName; } public String[] getFileUploadContentType() { return fileUploadContentType; } public void setFileUploadContentType(String[] fileUploadContentType) { this.fileUploadContentType = fileUploadContentType; } @Override public void validate() { if (null == fileUpload) { System.out.println("DummyFileUploadAction.validate()"); } } public String uplaod(){ return "success"; } public String execute() throws Exception{ for (File file: fileUpload) { System.out.println("File :" + file); } for (String fileContentType: fileUploadContentType) { System.out.println("File type : " + fileContentType); } return SUCCESS; } }
The struts.xml
is : I was able to get file object for single file upload with same set of configuration in struts.xml
struts.xml
:
<struts> <constant name="struts.enable.DynamicMethodInvocation" value="false" /> <constant name="struts.devMode" value="true" /> <constant name="struts.custom.i18n.resources" value="ApplicationResources" /> <constant name="struts.multipart.maxSize" value="1000000" /> <package name="default" extends="struts-default,json-default" namespace="/"> <action name="upload" class="com.cbuddy.common.action.DummyFileUploadAction" method="uplaod"> <result name="success">/uplaod.jsp</result> </action> <action name="dummyUpload" class="com.cbuddy.common.action.DummyFileUploadAction" > <interceptor-ref name="fileUpload"> <param name="allowedTypes">image/jpeg,image/gif,image/png</param> </interceptor-ref> <interceptor-ref name="defaultStack"></interceptor-ref> <result name="success">/success.jsp</result> <result name="input">/uplaod.jsp</result> </action> </package> </struts>
And then success.jsp
which will be rendered once files details are successfully printed .
This is an extension of a question I asked before: C#: How do I get the ID number of the last row inserted using Informix
I am writing some code in C# to insert records into the informix db using the .NET Informix driver. I was able to get the id of the last insert, but in some of my tables the 'serial' attribute is not used. I was looking for a command similar to the following, but to get rowid instead of id.
SELECT DBINFO ('sqlca.sqlerrd1') FROM systables WHERE tabid = 1;
And yes, I do realize working with the rowid is dangerous because it is not constant. However, I plan to make my application force the client apps to reset the data if the table is altered in a way that the rowids got rearranged or the such.
-5523027 0You could make all of the keys lowercase before searching:
array_change_key_case($all_meta, CASE_LOWER));
-26462091 0 CWnd.wndTopMost usage What CWnd.wndTopMost is used for?
in definition I found that it is:
static AFX_DATA const CWnd wndTopMost;
How macro AFX_DATA affects this line?
This code:
this->wndTopMost.SetWindowPos(NULL, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
Returns error
'CWnd::SetWindowPos' : cannot convert 'this' pointer from 'const CWnd' to 'CWnd &'
Why does it needs reference? This method returns to nothing.
-8502296 0Instead of using a 2nd connection object, you could change your connection string and use MARS (Multiple active result set) for this purpose. Add the following statement to your connection string:
MultipleActiveResultSets=True
EDIT: And like the other's said, use SqlParameters for your parameters and not string concatenation. It's not only a security issue, but also a huge performance hit!
-7380869 0 SQL Comma Delimit ProblemI have a small problem. I am getting this error, and I would appreciate if anyone could help me out! All I am trying to do is a comma delimited list.
SET NOCOUNT ON; DECLARE @TypeID Varchar(250) SELECT @TypeID = COALESCE(@TypeID +',' ,'') + TypeID FROM Related RETURN @TypeID
Conversion failed when converting the varchar value '8,' to data type int.
Does anyone know how to fix, please? I've tried CONVERT(VARCHAR, @TypeID)
but this doesn't seem to make any difference!
I am New to selenium RC..already working on selenium IDE. For selenium RC i have chosen java language.also installed selenium rc server. Now i dont have any idea have to go further. Please advice me on same
-21510280 0 How can I change hidden input val when add or remove item with using select2 pluginI use select2 plugin and get values when user typing least 3 character. Get data from php as json like this;
"1":"val1" , "5":"val2" , "19":"val3"....
I want to store id values of selected items at hidden input and when user remove any selected item, the id of removed item also remove from hidden input. For example;
When val1 and val2 items are selected like below, value of hidden input (id which 'hdn-id') change like below, also.
<input type="hidden" id="hdn-id" val="1,5" />
And when val1 is removed, id of this item (1) removed from hidden input like this ;
<input type="hidden" id="hdn-id" val="5" />
But I can't do this. My codes;
SELECT2:
function selectAjax(element,url,hiddenElement) { var selectedItemsArray = [] $('#'+element).select2({ multiple: multi, id: function(element) { return element }, ajax: { url: url, dataType: 'json', data: function(term,page) { return { term: term, page_limit: 10 }; }, results: function(data,page) { var titleArr = []; $.each(data, function(k,v){ titleArr.push(k+':'+v); }); return { results: titleArr }; } }, formatResult: formatResult, formatSelection: formatSelection, }); function formatResult(data) { return '<div>'+data.substr(data.indexOf(':')+1)+'</div>' }; function formatSelection(data) { var id = data.split(':',1), text = data.substr(data.indexOf(':')+1), hiddenElementValue = eval([jQuery('#'+hiddenElement).val()]); selectedItemsArray.push(id); jQuery('#'+hiddenElement).val(selectedItemsArray); return '<div data-id="'+id+'" class="y-select2-selected-items">'+text+'</div>'; }; } selectAjax('select2-element','ajx.php','hdn-id');
HTML:
<input type="text" id="select2-element" /> <input type="hidden" id="hdn-id" />
I can store ids at hidden input with above code but when remove an item I can't remove id from hidden input. Because plugin assign 'return false' to element's onclick event. I handed the job with above codes, I think.How can I be a better solution?
-39015172 0Thanks @vercelli
I got my answer with this query with your help.
Declare @ProdID int set @ProdID=1 DECLARE @columnName VARCHAR(1000) DECLARE @columnVal VARCHAR(1000) DECLARE @Query VARCHAR(1000) --Create dynamic column name SELECT @columnName =COALESCE(@columnName + ', ','')+'['+cast(rn as varchar(10))+'] AS [R'+cast(rn as varchar(10))+']', @columnVal =COALESCE(@columnVal + ',','')+'['+cast(rn as varchar(10))+']' FROM ( select distinct ROW_NUMBER () over (partition By VendorId order by QuotedAmount desc) as rn from tbl_Vendor_Quotation where [ProductRequestID]=@ProdID ) a print @columnName print @columnVal set @Query='select VendorId,'+@columnName+' from ( select VendorId, QuotedAmount, ROW_NUMBER () over (partition By VendorId order by QuotedAmount desc) as rn from tbl_Vendor_Quotation where [ProductRequestID]='+cast(@ProdID as varchar(10))+') t1 PIVOT ( max(QuotedAmount) for rn in ('+@columnVal+')) As PivotTable' exec (@Query)
-23240829 0 Regular Threads can prevent the VM from terminating normally (i.e. by reaching the end of the main method - you are not using System#exit() in your example, which will terminate the VM as per documentation).
For a thread to not prevent a regular VM termination, it must be declared a daemon thread via Thread#setDaemon(boolean) before starting the thread.
In your example - the main thread dies when it reaches the end of it code (after t1.start();), and the VM - including t1- dies when t1 reaches the end of its code (after the while(true) aka never or when abnormally terminating.)
Compare this question, this answer to another similar question and the documentation.
-786498 0I found this info while digging around, and it seems it can be the most cost effective way. I will try it out when I get the guts to dig into assembly. :)
UPDATE
I tested this with my profiler. although a bit faster, it seems I still have tonnes of other overhead :( (I did not bother with timing as I it did not seem to be enough benefit)
-14067271 0Well it depends on your app and the connect, first your app must support background running. Then if the internet connection is GRPS, CDMA or EDGE your connection is dropped and NSURLConnection
will receive an error if the connection is not reestablished with the time out period. On 3G and WiFi you can have data and voice at the same time. On LTE all data connection are dropped and the witches back to UMTS(3G) see comment by Codo
You can write your business logic in onchange function as shown below
<form name="login" action="procesarAdd.do"> <br> <b>CATEGORIA</b> <br> <input type="radio" name="g1" value="per" checked="checked" onchange="product(this.value)"/>PERFUME <input type="radio" name="g1" value="joy" onchange="product(this.value)"/>JOYAS <input type="radio" name="g1" value="car" onchange="product(this.value)"/>BOLSO CARTERAS <table border="1"> <tbody> <tr> <td>ID Producto</td> <td><input type="text" name="id" id ="field1" value="" /></td> </tr> <tr> <td>Nombre</td> <td><input type="text" name="nombre" id ="field2" value="" /></td> </tr> <tr> <td>Stock</td> <td><input type="text" name="stock" id ="field3" value="" /></td> </tr> <tr> <td>Precio</td> <td><input type="text" name="precio" id ="field4" value="" /></td> </tr> </tbody> </table>
Javascript function:
function product(x){ alert("Product Name : " +x); if(x=="per"){ document.getElementById("myImg").src = "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcScKsjtuajfWrNvk2pXTxf4Et2dPoCEsF58XVetpBrVCpDnLmAkVg" } if(x=="joy"){ document.getElementById("myImg").src = "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcQM3y6qUIwqIr164GbERvTyOXNMBYcWOueodxxwxzug16oFalPldiHJQV1r" } if(x=="car"){ document.getElementById("myImg").src = "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcS3P65pTpiNFx2psFeqOoF6iuXzQErc_gBUmAf6bn1846ghx1TrOw" } }
codepen URL for your reference: http://codepen.io/nagasai/pen/KMwGMg?editors=1010
Please let me know if you need any further details
-35258921 0 multiple apps from one certificateI have two active projects, my main app and a test app. It seems to be the case that using the "generate" button to run the certificate wizard, I have to generate certificates from scratch each time I switch from one app to the other. The "use existing" option never works. Generating a new cert for one app invalidates the cert for the other app. This doesn't seem right, so what am I doing wrong?
-27581465 0You need to change $chk_group[]
to $chk_group
in your first line.
In PHP syntax, $chk_group[] =
means push the right had value to an array called $chk_group
. Your entire array is being stored to $chk_group[0]
What you need instead is:
$chk_group[] =array( '1' => 'red', '2' => 'thi', '3' => 'aaa', '4' => 'bbb', '5' => 'ccc' );
-24842599 0 select string with specific character in regular expression Given the following text of example:
Hello
$NAME$
how are you? You are visiting this$LOGIN_PAGE$
page, please fill the form and log in.
I want to select only the following "variable" $LOGIN_PAGE$
without select even the $NAME
character.
I made this regex trying to achieve the result but it select both of the string
(\$([A-Z\_])+\$)
Which part I'm missing in this regex?
-21417931 0 jQuery script not working properly on Google ChromeI have the following code that seems to not work in Google Chrome.
$("#productImg img").click(function() { var img = $(this).attr("src"); var text = $(this).attr("id"); $("#loader").show(); $("#largeImg img").load(function() { $("#loader").hide(); }).attr("src", img.replace('th_', 'si_')); });
It works fine in Firefox, but doesn't in Chrome. If i click the first image it makes some kind of loop and never hides the #loader
. You can test it here.
Any help is appreciated!
-20146345 0 How to rename an IndexedDB database?I created an IndexedDB databse named "A" by indexedDB.open method.
Now I want to modify the database name to "B", how can I do it?
I dont't want to create a new database with new name and copy all data from old database to new database.
-2970040 0The following code would do what you literally ask (assuming thesocket
is a connected stream socket):
with open('thefile.mp3', 'rb') as f: thesocket.sendall(f.read())
but of course it's unlikely to be much use without some higher-level protocol to help the counterpart know how much data it's going to receive, what type of data, and so forth.
-16226057 0 Recreate original PHP array from print_r outputLet's say I have this output from some source where I don't have access to the original PHP created array:
Array ( [products] => Array ( [name] => Arduino Nano Version 3.0 mit ATMEGA328P [id] => 10005 ) [listings] => Array ( [category] => [title] => This is the first line This is the second line [subtitle] => This is the first subtitle This is the second subtitle [price] => 24.95 [quantity] => [stock] => [shipping_method] => Slow and cheap [condition] => New [defects] => ) [table_count] => 2 [tables] => Array ( [0] => products [1] => listings ) )
Now I would like to input that data and have an algorithm recreate the original array that it was printing so I can then use it for my own application.
Currently I am thinking about a sub_str()
and regex statements that pull data and place it appropriately. Before I head further, is there a simpler way, via already written code or php plugins that do this for me already out there?
You can create multiple encryption keys (millions) and use separate keys for separate columns. Adding multiple keys is critical for any scenario that requires periodic key rotation. To encrypt data you use ENCRYPTBYKEY
and pass in the key name of the desired encryption key, see How to: Encrypt a Column of Data. You decrypt data using DECRYPTBYKEY
. Note that you do not specify what decryption key to use, the engine knows. But you have to properly open the decryption key first, see OPEN SYMMETRIC KEY
.
Its fun and challenging to go from static image processing to doing analysis in real-time. For example, analyze video from a webcam and have the user play a primitive video game by waving their hands.
Or, if you want to continue with your face recognition idea, try writing software to highlight famous faces in a running video in realtime.
Use google image search to gather training data and then see how well your software can do at identifying the president of the US in different settings , for example. Can you train all of the former presidential candidates and differentiate them all?
Also, look into using OpenCV for fast real time computer vision processing in C.
-13335931 0From the glob
module's documentation:
The
glob
module finds all the pathnames matching a specified pattern according to the rules used by the Unix shell. No tilde expansion is done, but*
,?
, and character ranges expressed with[]
will be correctly matched. This is done by using theos.listdir()
andfnmatch.fnmatch()
functions in concert, and not by actually invoking a subshell.
And if we look the documentation for os.listdir
:
os.listdir(path)
Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order. It does not include the special entries '.' and '..' even if they are present in the directory.
So glob.glob
does not return the files in alphabetical order. It is not stated anywhere in the documentation. Relying on this behaviour is a bug. If you want an ordered sequence you must sort the result. You can then easily imagine that there is no way to make iglob
return a sorted result since it does not even have all results available.
If memory is really a problem then you have two choices:
iglob
.Thank you guys for giving me such good advice! Maybe it is just a bad idea to use music, because it is inconvenient.
http://www.larajade.co.uk/high/
That's what I am thinking about - but there are only difficult ways to get it, flash / ajax. Iframes are bad...
Thank you :)
-35689257 0You can use the async package which is great for controlling flow, something like:
console.log('Recieved the get Request'); var i = 1; var count = 0; while (count < 10) { var url = 'http://www.imdb.com/title/tt' + i + '/'; console.log(url); count = count + 1; i = i + 1; async.waterfall([ function sendRequest (callback) { if (!error) { var $ = cheero.load(html); var json = { title: '', ratings: '', released: '' } } $('.title_wrapper').filter(function() { var data = $(this); json.title = data.children().first().text().trim(); json.released = data.children().last().children().last().text().trim(); }); $('.ratingValue').filter(function() { var data = $(this); json.ratings = parseFloat(data.text().trim()); }); callback(null, JSON.stringify(json, null, 4) + '\n'); }, function appendFile (json, callback) { fs.appendFile('message.txt', json, function(err) { if (err) { callback(err); } callback(); }); } ], function(err) { res.sendFile(__dirname + '/index.js'); });
-24656338 0 You get this as you cannot cast the IEnumerable to List (This is why LINQ has .ToList() extension). I think what you want is something like this:
public IEnumerable<T> Paginate<T>(IEnumerable<T> list) { return list.Skip(Page * PageSize).Take(PageSize); }
Which will work with any source that implements IEnumerable (List, T[], IQueryable)
You can then call it like this:
IEnumerable<int> list = someQueryResult; IEnumerable<int> page = class.Paginate<int>(list);
As pointed out in other answers. IQueryable has it's own set of extension methods. So all though this will work, the paging will not be done as the data-source, as it will use the IEnumerable extensions
-25861016 0 50% chance to make a boolean true or not by clicking a button?I've been stuck on this for a while, I'm trying to figure out how to make a boolean have a 50% chance to be set to true after clicking a button and a 50% chance to keep it false.
Any help would be appreciated.
-22387777 0If you want all results where the Quantity is 20, then all you need to do is specify that in the WHERE clause:
SELECT * FROM Product WHERE Quantity = 20;
There's no need to include the ORDER BY if you expect the value to be the same throughout. There's also no need to LIMIT unless you want the first number of results where Quantity is 20.
-34355272 0When you declare the function you just have to put a simple name without parentheses and parameters otherwise it will give that error.
See the documentation http://orientdb.com/docs/2.0/orientdb.wiki/Functions.html
-38564838 0OAuth is a concept, and not any library which you can inject, (of course libraries exists to implement that)
So if you want to have OAuth in your application (i.e your application has its own OAuth), you have to setup following things
Check out the OAuth 2.0 Specification to get clear understanding of how it works and how to build your own.
https://tools.ietf.org/html/rfc6749
-2748593 0 Authorization in a more purely OOP styleI've never seen this done but I had an idea of doing authorization in a more purely OO way. For each method that requires authorization we associate a delegate. During initialization of the class we wire up the delegates so that they point to the appropriate method (based on the user's rights). For example:
class User { private deleteMemberDelegate deleteMember; public StatusMessage DeleteMember(Member member) { if(deleteMember != null) //in practice every delegate will point to some method, even if it's an innocuous one that just reports 'Access Denied' { deleteMember(member); } } //other methods defined similarly... User(string name, string password) //cstor. { //wire up delegates based on user's rights. //Thus we handle authentication and authorization in the same method. } }
This way the client code never has to explictly check whether or not a user is in a role, it just calls the method. Of course each method should return a status message so that we know if and why it failed.
Thoughts?
-35192629 0 Preventing duplicate REST callsI'm creating an Android app that calls a PHP bases REST api methods for server side updates.
For example, to add reward points to customer, we can use:
http://example.com/rest/customer/add/1/20
Where 1 is customer id and 20 is reward points.
I was wondering how can I prevent duplicate calls to this URL. If for some reason, this URL is called twice, customer will get 20 more points. There is no such condition that customer cannot get more points on same day.
Also, how to prevent this URL to be executed anonymously?
Is OAuth 2.0 the best solution or there is something better?
Thanks
-39782499 0 MySQL: character set utf8 giving error with datetimeI am new to MySQL and wants to create this table after reading tutorial I wrote this command but on MySQL Workbench it shows error for 4 line created_at attribute:
CREATE TABLE tweetMelbourne ( `id` INT(11) NOT NULL AUTO_INCREMENT, `geo_type` VARCHAR(8) CHARACTER SET utf8, `created_at` DATETIME CHARACTER SET utf8 NOT NULL , `geo_coordinates_latitude` decimal(12,9) DEFAULT NULL, `geo_coordinates_longitude` decimal(12,9) DEFAULT NULL, `place_full_name` VARCHAR(35) CHARACTER SET utf8, `place_country` VARCHAR(15) CHARACTER SET utf8, `place_type` VARCHAR(18) CHARACTER SET utf8, `place_bounding_box_type` VARCHAR(10) CHARACTER SET utf8, `place_bounding_box_coordinates_NE_lat` decimal(12,9) DEFAULT NULL, `place_bounding_box_coordinates_NE_long` decimal(12,9) DEFAULT NULL, `place_bounding_box_coordinates_SW_lat` decimal(12,9) DEFAULT NULL, `place_bounding_box_coordinates_SW_long` decimal(12,9) DEFAULT NULL, `place_country_code` VARCHAR(5) CHARACTER SET utf8, `place_name` VARCHAR(17) CHARACTER SET utf8, `text` VARCHAR(140) CHARACTER SET utf8, `user_id` INT, `user_verified` VARCHAR(5) CHARACTER SET utf8, `user_followers_count` INT, `user_listed_count` INT, `user_friends_count` INT, `user_location` VARCHAR(30) CHARACTER SET utf8, `user_following` VARCHAR(5) CHARACTER SET utf8, `user_geo_enabled` VARCHAR(5) CHARACTER SET utf8, `user_lang` VARCHAR(5) CHARACTER SET utf8, PRIMARY KEY (id) );
Error is :
Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'CHARACTER SET utf8
-13459767 0 If the input is within the magnitude range supported by double, and you do not need more than 15 significant digits in the result, convert (a+b) and n to double, use Math.pow, and convert the result back to BigDecimal.
-9829667 0It's because your using an OR clause, you need to use AND. Basically your saying if the textSample is not D then show your message box.
Change it to:
Dim textSample as String = "F" If Not textSample = "D" AND Not textSample = "E" AND Not textSample = "F" Then MessageBox.Show("False") End If
That should work.
-14613725 0 Centered floating logo stuck on right only in IE9I have a fluid width site with a logo centered in the header area. The logo stays in the center regardless of the window size. Works in all browsers except ie9. In ie9 it is stuck on the right. If I could get it stuck on the left that would be an ok compromise but the right will not do. My best guess is that ie9 does not support the css code:
.logo { width:100%; position:relative; } .logo img { margin-left:auto; margin-right:auto; display:block; }
Here is the website http://www.cyberdefenselabs.org/
Anyone know a workaround for ie9 that will not affect other browsers or involve drastic recode?
-33082472 0 My timer increases speed after a single play through of my game why?I continue to get the error TypeError: Error #1009: Cannot access a property or method of a null object reference. at ChazS1127_win_loose_screen_fla::MainTimeline/updateTime() at flash.utils::Timer/_timerDispatch() at flash.utils::Timer/tick() and here is my code for my main game
stop(); import flash.events.MouseEvent; import flash.ui.Mouse; import flash.events.TimerEvent; import flash.utils.Timer; var timer:Timer = new Timer(1000, 9999); timer.addEventListener(TimerEvent.TIMER, updateTime); var timeRemaining = 30; timerBox.text = timeRemaining; function updateTime(evt:TimerEvent) { timeRemaining--; timerBox.text = timeRemaining; if(timeRemaining <= 0) { gotoAndStop(1, "Loose Screen"); } } addEventListener(MouseEvent.CLICK, onMouseClick); var score = 0 ; function onMouseClick(evt:MouseEvent) { if(evt.target.name == "playBtn") { texts.visible = false; playBtn.visible = false; backpackss.visible = false; backgrounds.visible = false; timer.start(); } if(evt.target.name == "Backpack") { Backpack.visible = false; message.text = "A backpack is a necessity for carrying all your items."; score = score + 1; scoredisplay.text = "score:" + score; 0 } if(evt.target.name == "Bandage") { Bandage.visible = false; message.text = "Bandages for cuts and scraps and to keep from bleeding out."; score = score + 1; scoredisplay.text = "score:" + score; } if(evt.target.name == "Brace") { Brace.visible = false; message.text = "A brace is good for a sprain or even a break in a bone allow you to keep going."; score = score + 1; scoredisplay.text = "score:" + score; } if(evt.target.name == "canned") { canned.visible = false; message.text = "Canned foods are a good resource as food will be scarce in situations."; score = score + 1; scoredisplay.text = "score:" + score; } if(evt.target.name == "Compass") { Compass.visible = false; message.text = "Going the wrong direction in a survival situation can be your downfall."; score = score + 1; scoredisplay.text = "score:" + score; } if(evt.target.name == "Flashlight") { Flashlight.visible = false; message.text = "A flashlight can help you see at night and help you stay sane."; score = score + 1; scoredisplay.text = "score:" + score; } if(evt.target.name == "Iodine") { Iodine.visible = false; message.text = "An ioddine purfication kit can assist in keeping water clean for drinking."; score = score + 1; scoredisplay.text = "score:" + score; } if(evt.target.name == "Lighter") { Lighter.visible = false; message.text = "A windproof lighter for even the windest of days to light fires."; score = score + 1; scoredisplay.text = "score:" + score; } if(evt.target.name == "Radio") { Radio.visible = false; message.text = "A radio to help keep up to date on news around if it's still brodcasting."; score = score + 1; scoredisplay.text = "score:" + score; } if(evt.target.name == "Sewing") { Sewing.visible = false; message.text = "A sewing kit for salvaging clothes and for patching up wounds."; score = score + 1; scoredisplay.text = "score:" + score; } if(evt.target.name == "Tent") { Tent.visible = false; message.text = "A tent can be a home for the night and a home for life."; score = score + 1; scoredisplay.text = "score:" + score; } if(score >= 11) { gotoAndStop(1, "Victory Screen"); } } function removeAllEvents() { removeEventListener(MouseEvent.CLICK, onMouseClick); timer.removeEventListener(TimerEvent.TIMER, updateTime); timer.stop(); }
and my Victory Screen
stop(); import flash.events.MouseEvent; addEventListener(MouseEvent.CLICK, onMouseClick2); play(); function onMouseClick2(evt:MouseEvent) { if(evt.target.name == "restartButton") { gotoAndStop(1, "Main Game"); removeAllEvents2(); } } function removeAllEvents2() { removeEventListener(MouseEvent.CLICK, onMouseClick2); }
and my loose screen
stop(); import flash.events.MouseEvent; play(); addEventListener(MouseEvent.CLICK, onMouseClick2); function onMouseClick3(evt:MouseEvent) { if(evt.target.name == "restartButton") { gotoAndStop(1, "Main Game"); removeAllEvents3(); } } function removeAllEvents3() { removeEventListener(MouseEvent.CLICK, onMouseClick3); }
so why does my game when through one play the timer will speed up and go fast for no reason. After one play through it'll go 2 seconds for every 1 second and so on.
-19097912 0 hover works only when entering from outside of container IEi saw many problems with IE but none was the same as mine. i have a gallery on my site, there are navigation arrows on each pic. i use hover to figure on which half of the picture the user hovers and to show the right arrow accordingly, the problem is that the hover works only when i enter the mouse from outside the div that contains the arrows, when i move form one arrow to another it dosent work. here the code:
<div class="lb-container"> <img class="lb-image" src="http://suburbanfinance.com/wp-content/uploads/2013/04/streetinfo.jpg?973b8a" style="display: block; width: 724px; height: 543px;"> <div class="lb-nav" style="display: block;"> <a class="lb-prev" href="" style="display: block;"></a> <a class="lb-next" href="" style="display: block;"></a> </div> <div class="lb-loader" style="display: none;"><a class="lb-cancel"> </a></div></div>
and the css:
.lb-next:hover { background: url(../images/next.png) right 48% no-repeat; } .lb-prev:hover { background: url(../images/prev.png) left 48% no-repeat; }
ideas?
-14565675 0 Create Buffer OpenGLES 2I am having some problem with the creation of frame buffer with opengles. For my application, I create the main frame buffer like this:
glGenFramebuffers( 1, &viewFramebuffer ); glGenRenderbuffers( 1, &viewRenderbuffer ); glBindFramebuffer( GL_FRAMEBUFFER, viewFramebuffer ); glBindRenderbuffer( GL_RENDERBUFFER, viewRenderbuffer ); [ Context renderbufferStorage : GL_RENDERBUFFER fromDrawable : ( CAEAGLLayer* )self.layer ]; glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, viewRenderbuffer ); glGetRenderbufferParameteriv( GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &backingWidth ); glGetRenderbufferParameteriv( GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &backingHeight ); if ( itUsesDepthBuffer ) { glGenRenderbuffers( 1, &depthRenderbuffer ); glBindRenderbuffer( GL_RENDERBUFFER, depthRenderbuffer ); glRenderbufferStorage( GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, backingWidth, backingHeight ); glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthRenderbuffer ); } if ( glCheckFramebufferStatus( GL_FRAMEBUFFER ) != GL_FRAMEBUFFER_COMPLETE ) { NSLog( @"failed to make complete framebuffer object %x", glCheckFramebufferStatus( GL_FRAMEBUFFER ) ); [ self destroyFramebuffer ]; return NO; }
But the function glGetRenderbufferParameteriv returns 0 either for GL_RENDERBUFFER_WIDTH and GL_RENDERBUFFER_HEIGHT and eventually the glCheckFramebufferStatus returns an error as framebuffer attachment is incomplete.
Do you have any idea why is this happening?
Thank you in advance.
-36067450 0 Manipulate scope value with angularjs directivemy model contains some values that I want to modify before showing it to the user. Maybe this is written in the docs and I am to blind to see it.
Lets say I want to display my variable like this
<span decode-directive>{{variable}}</span>
I want to write the decode-directive and it should display variable + 1234 f.e.
I need this at a few points so I can't code it for only one special object.
I hope you can help me out with this.
use list to store your all objects and iterate the list and check if the condition of search is satisfied or not, in your case it is "billy". If you don't want to use list, use an array of object and then iterate with for loop instead. Hope this has helped. Do tell if you want code for this.
-35453865 0I think you can create nested list groups and by changing their width you can create a responsive design. Using something like:
<div class="col-lg-2 col-md-3 col-sm-12 col-xs-12"> ... </div>
With this way you can but 6 columns side by side in large screens and only one column for each row in smaller screens.
Bootstrap should be used with 'mobile-first design' approach. So you must design your screen according to smaller screens first and then you should consider larger screen sizes.
I advise you to spend some time in
And here is a couple of demos for nested list groups:
consistent-styling-for-nested-lists-with-bootstrap
I hope this gives you a starting point.
-28373213 0Try the following code
{{ HTML::link(url().'/blog'.$Blog->id, $Blog->BlogTitle)}}
-19224665 0 Why does Object::try work if it's sent to a nil object? If you try to call a method on a nil
object in Ruby, a NoMethodError
exception arises with the message:
"undefined method ‘...’ for nil:NilClass"
However, there is a try
method in Rails which just return nil
if it's sent to a nil
object:
require 'rubygems' require 'active_support/all' nil.try(:nonexisting_method) # no NoMethodError exception anymore
So how does try
work internally in order to prevent that exception?
ever tried SET NOCOUNT ON;
as an option?
I'm trying to get a list of SEDOL's & ADP values. Below is my json text:
{ "DataFeed" : { "@FeedName" : "AdminData", "Issuer" : [{ "id" : "1528", "name" : "ZYZ.A a Test Company", "clientCode" : "ZYZ.A", "securities" : { "Security" : { "id" : "1537", "sedol" : "SEDOL111", "coverage" : { "Coverage" : [{ "analyst" : { "@id" : "164", "@clientCode" : "SJ", "@firstName" : "Steve", "@lastName" : "Jobs", "@rank" : "1" } }, { "analyst" : { "@id" : "261", "@clientCode" : "BG", "@firstName" : "Bill", "@lastName" : "Gates", "@rank" : "2" } } ] }, "customFields" : { "customField" : [{ "@name" : "ADP Security Code", "@type" : "Textbox", "values" : { "value" : "ADPSC1111" } }, { "@name" : "Top 10 - Select one or many", "@type" : "Dropdown, multiple choice", "values" : { "value" : ["Large Cap", "Cdn Small Cap", "Income"] } } ] } } } }, { "id" : "1519", "name" : "ZVV Test", "clientCode" : "ZVV=US", "securities" : { "Security" : [{ "id" : "1522", "sedol" : "SEDOL112", "coverage" : { "Coverage" : { "analyst" : { "@id" : "79", "@clientCode" : "MJ", "@firstName" : "Michael", "@lastName" : "Jordan", "@rank" : "1" } } }, "customFields" : { "customField" : [{ "@name" : "ADP Security Code", "@type" : "Textbox", "values" : { "value" : "ADPS1133" } }, { "@name" : "Top 10 - Select one or many", "@type" : "Dropdown, multiple choice", "values" : { "value" : ["Large Cap", "Cdn Small Cap", "Income"] } } ] } }, { "id" : "1542", "sedol" : "SEDOL112", "customFields" : { "customField" : [{ "@name" : "ADP Security Code", "@type" : "Textbox", "values" : { "value" : "ADPS1133" } }, { "@name" : "Top 10 - Select one or many", "@type" : "Dropdown, multiple choice", "values" : { "value" : ["Large Cap", "Cdn Small Cap", "Income"] } } ] } } ] } } ] } }
Here's the code that I have so far:
var compInfo = feed["DataFeed"]["Issuer"] .Select(p => new { Id = p["id"], CompName = p["name"], SEDOL = p["securities"]["Security"].OfType<JArray>() ? p["securities"]["Security"][0]["sedol"] : p["securities"]["Security"]["sedol"] ADP = p["securities"]["Security"].OfType<JArray>() ? p["securities"]["Security"][0]["customFields"]["customField"][0]["values"]["value"] : p["securities"]["Security"]["customFields"]["customField"][0]["values"]["value"] });
The error I get is:
Accessed JArray values with invalid key value: "sedol". Int32 array index expected
I think I'm really close to figuring this out. What should I do to fix the code? If there is an alternative to get the SEDOL
and ADP value
, please do let me know?
[UPDATE1] I've started working with dynamic ExpandoObject. Here's the code that I've used so far:
dynamic obj = JsonConvert.DeserializeObject<ExpandoObject>(json, new ExpandoObjectConverter()); foreach (dynamic element in obj) { Console.WriteLine(element.DataFeed.Issuer[0].id); Console.WriteLine(element.DataFeed.Issuer[0].securities.Security.sedol); Console.ReadLine(); }
But I'm now getting the error 'ExpandoObject' does not contain a definition for 'DataFeed' and no extension method 'DataFeed' accepting a first argument of type 'ExpandoObject' could be found
. NOTE: I understand that this json text is malformed. One instance has an array & the other is an object. I want the code to be agile enough to handle both instances.
[UPDATE2] Thanks to @dbc for helping me with my code so far. I've updated the json text above to closely match my current environment. I'm now able to get the SEDOLs & ADP codes. However, when I'm trying to get the 1st analyst, my code only works on objects and produces nulls for the analysts that are part of an array. Here's my current code:
var compInfo = from issuer in feed.SelectTokens("DataFeed.Issuer").SelectMany(i => i.ObjectsOrSelf()) let security = issuer.SelectTokens("securities.Security").SelectMany(s => s.ObjectsOrSelf()).FirstOrDefault() where security != null select new { Id = (string)issuer["id"], // Change to (string)issuer["id"] if id is not necessarily numeric. CompName = (string)issuer["name"], SEDOL = (string)security["sedol"], ADP = security["customFields"] .DescendantsAndSelf() .OfType<JObject>() .Where(o => (string)o["@name"] == "ADP Security Code") .Select(o => (string)o.SelectToken("values.value")) .FirstOrDefault(), Analyst = security["coverage"] .DescendantsAndSelf() .OfType<JObject>() .Select(jo => (string)jo.SelectToken("Coverage.analyst.@lastName")) .FirstOrDefault(), };
What do I need to change to always select the 1st analyst?
-357951 0Because your dropdownlist is contained within another control it may be that you need a recursive findcontrol.
http://weblogs.asp.net/palermo4/archive/2007/04/13/recursive-findcontrol-t.aspx
-16527755 0 if ($("b").has(":contains('Choose a sub category:')").length) { /*Your Stuff Here*/ }
-8656409 0 mongodb map-reduce output doubles my source database have documents like..
{date:14, month:1, year:2011, name:"abc", item:"A"} {date:14, month:1, year:2011, name:"abc", item:"B"} {date:14, month:1, year:2011, name:"def", item:"A"} {date:14, month:1, year:2011, name:"def", item:"B"} {date:15, month:1, year:2011, name:"abc", item:"A"} {date:16, month:1, year:2011, name:"abc", item:"A"} {date:15, month:1, year:2011, name:"def", item:"A"} {date:16, month:1, year:2011, name:"def", item:"A"}
and my map reduce is like...
var m = function(){ emit({name:this.name, date:this.date, month:this.month, year:this.year}, {count:1}) } var r = function(key, values) { var total_count = 0; values.forEach(function(doc) { total_count += doc.count; }); return {count:total_count}; }; var res = db.source.mapReduce(m, r, { out : { "merge" : "bb_import_trend" } } );
so "myoutput" collection will have counts like this....
{ "_id" : { date : 14, month : 1, year : 2011, name : "abc" }, "_value" : { "count" : 2 } }, { "_id" : { date : 14, month : 1, year : 2011, name : "def" }, "_value" : { "count" : 2 } }, { "_id" : { date : 15, month : 1, year : 2011, name : "abc" }, "_value" : { "count" : 1 } }, { "_id" : { date : 15, month : 1, year : 2011, name : "def" }, "_value" : { "count" : 1 } }, { "_id" : { date : 16, month : 1, year : 2011, name : "abc" }, "_value" : { "count" : 1 } }, { "_id" : { date : 16, month : 1, year : 2011, name : "def" }, "_value" : { "count" : 1 } }
so total 6 documents
so when aother three documents of date 17 like...
{date:17, month:1, year:2011, name:"abc", item:"A"} {date:17, month:1, year:2011, name:"abc", item:"B"} {date:17, month:1, year:2011, name:"def", item:"A"}
has been added to my source collection...and again i am running map-reduce it should be jus addition of two documents like...
previous 6 plus
... { "_id" : { date : 17, month : 1, year : 2011, name : "abc" }, "_value" : { "count" : 2 } }, { "_id" : { date : 17, month : 1, year : 2011, name : "def" }, "_value" : { "count" : 1 } }
but instead of this it duplicates all the previous 6 documents and adds another 2 new ones..so total of 14 documents in my output collection(though i 've used merge in output).
Note > : when i am using another database having same source collection and doing the same procedure it gives me desired output(of only 8 collection).but my database using by my gui is still duplicating the old ones.
-20973886 0The example method you provide
public SomeObject someObjectBehavior(final SomeObject oldSomeObject,final SomeObject newSomeObject) { if(oldSomeObject == null) { oldSomeObject = newSomeObject; //Assignment operation } }
is a perfect example of why making your parameters final
is a Good Idea. Without making your variables final
, you might not realize that your method does nothing, since reassigning a parameter reference doesn't change anything outside of your method.
I am trying to start using the just released Android Studio, I have already established the location for the Android SDK, and the Studio opens correctly.
Now, I want to create a new application project, but I cannot figure out what to select as project location.
Steps followed:
I read a similar question, and I am making sure, as you can tell by the steps I followed, that I am entering the path at the very end, and it still won't work for me.
I really think there must be a silly thing I am missing here, not sure what it may be though.
Any ideas?
-38902099 0 Is it necessary to use Static nested class to create a node for linked listCan you please describe the use of below code and how it works.
class LinkedList { Node head; // head of list static class Node { int data; Node next; Node(int d) { data = d; next=null; } // Constructor } public static void main(String[] args) { LinkedList llist = new LinkedList(); llist.head = new Node(1); Node second = new Node(2); Node third = new Node(3); llist.head.next = second; // Link first node with the second node second.next = third; // Link second node with the third node } }
-7971173 0 Webgrid checkbox selection lost after paging I have a webgrid
@{ var gdAdminGroup = new WebGrid(source: Model, rowsPerPage: 20, ajaxUpdateContainerId: "tdUserAdminGroup"); } @gdAdminGroup.GetHtml( htmlAttributes: new { id = "tdUserAdminGroup" }, tableStyle: "gd", headerStyle: "gdhead", rowStyle: "gdrow", alternatingRowStyle: "gdalt", columns: gdAdminGroup.Columns( gdAdminGroup.Column(columnName: "Description", header: "Admin Group"), gdAdminGroup.Column(header: "", format: @<text><input name="chkUserAdminGroup" type="checkbox" value="@item.AdminGroupID" @(item.HasAdminGroup == 0? null : "checked") /></text>) ) )
If I check some checkboxs and goes to the second page, the selection on the first page will be lost. Can anyone help me with this? Thank you
-12179679 0 How to allow read-only binding to the internal properties of a custom control DependencyProperty?I am developing a CustomControl
that exposes the DependencyProperty
SearchRange
, which is based on the custom class Range
.
public class MyCustomControl : Control { public static readonly DependencyProperty SearchRangeProperty = DependencyProperty.Register( "SearchRange", typeof (Range<DateTime>), typeof (VariableBrowser)); // ... public Range<DateTime> SearchRange { get { return (Range<DateTime>)this.GetValue(SearchRangeProperty); } set { this.SetValue(SearchRangeProperty, value); } } // ... }
The class Range
contains two different properties, Minimum
and Maximum
, and it implements INotifyPropertyChanged
.
public class Range<T> : INotifyPropertyChanged where T : IComparable { private T _maximum; private T _minimum; public T Maximum { get { return this._maximum; } set { this._maximum = value; this.OnPropertyChanged("Maximum"); } } public T Minimum { get { return this._minimum; } set { this._minimum = value; this.OnPropertyChanged("Minimum"); } } // ... }
The specifications that I am following require that an application that uses my Custom control should be able to bind to the SearchRange
property only in order to read its inner values (Minimum
and Maximum
), as these must be handled internally and set just by my CustomControl
. The binding target should be updated after any variation to either the SearchRange
property or its internal props (Minimum
and Maximum
), without reassigning the entire SearchRange
. Alternatively, I should permit to bind directly to the internal properties (SearchRange.Minimum
and SearchRange.Maximum
).
I tried many different ways to achieve this result, but none was successful. How could I obtain the required result?
Thanks in advance.
-25670049 0 Changing checkbox attributes for multiple rows with single checkboxGood Morning,
Im working on a larger project but i tried to do a simple page in order to check my work. php/mysql newb here. Sorry! :)
What im trying to accomplish is ultimately having a single user page shown with rows of tasks from a table and a single check mark in order to say if the user has completed the task or not by checking or unchecking the box.
For testing purposes, I have set up a table with rows labled testid, testdata and testcheck. The testid a INT(2)AutoIncrement and Primary and Unique, testdata is a VARCHAR(30) and testcheck is a TINYINT(1). The auto increment isnt really important because I manually populated all the rows. I have 5 rows (for the array sake) consisting of 1-5 testid, "testdata1-5" for testdata and either a 0 or a 1 for testcheck. The table is functioning fine and the database can be queried.
Here is the code for the php start page:
<html> <?php include_once('init.php'); $query = mysql_query("SELECT testid, testdata, testcheck FROM testtable"); ?> <h1>Test form for checkmarks</h1> <form method="POST" action="testover.php"> <table border="1"> <tr> <td> Test ID </td> <td> Test Data </td> <td> Checked </td> <td> Test Check </td> </tr> <?php while ( $row = mysql_fetch_assoc($query)) { ?> <tr> <td> <?php echo $row['testid']; ?> </td> <td> <?php echo $row['testdata']; ?> </td> <td> <center><input type="checkbox" name="<?php $row['testid'] ?>" value="<?php $row['testcheck']; ?>" <?php if($row['testcheck']=='1'){echo 'checked';} ?>></center> </td> <td> <center><?php echo $row['testcheck']; ?></center> </td> </tr> <?php } ?> </table> <input type="submit" name="confirm" value="Confirm Details"> <a href="testcheck.php"><input type="button" value="Home"></a> </form> </html>
Ive been going back and forth trying to use an array for the inputs name (name="something[]") or the "isset" parameter but that is where my knowledge is failing. Ive read countless articles both here and on other websites and I cant seem to find the right code to use. Most sites have rows with multiple check boxes or a different layout of their table.
I posted here to hopefully be pointed in some direction as to how to update the DB with these values of the check marks.
-22401676 0In object-oriented programming, a constructor in a class is a special type of subroutine called to create an object. It prepares the new object for use, often accepting arguments that the constructor uses to set member variables required.
So the var catC = new Cat("Fluffy", "White");
creates an new instance of the constructor class Cat
I need to create a simple Java application that connects to a local database file, and will run on a mac.
I've figured that JDBC is a good option, but what file format/drivers should I use? Is .MDB files a possibility?
Thanks for any help!
-2568729 0 Android: Create TextView that flashes when clickedHow do I set up a TextView to flash when it is clicked? With flashing I mean that I want to change the background color of the TextView. I essentially want one of the objects that is displayed in a ListActivity, but inside a normal View.
I have tried to do this by adding an OnClickListener, but what I really need is something like adding an On(Un)SelectListener. Using the onClickListener, I can change the TextView background, but obviously the background stays that color. I thought of using a new Handler().postDelayed(new Runnable(){ ... }) kind of thing to reset the backround after some small time, but I did not know if this would be overkill for what I'm trying to do.
What would you recommend?
-15656736 0Your server delivers the resource http://dev.fristil.se/hbh/wp-content/themes/skal/images/video/bubblybeer.webm with the HTTP header Content-Type: text/plain
– and therefore Firefox refuses to treat it as anything else.
“Teach” your server to deliver such content as video/webm
.
(Same goes for your ogv – your server also says that resource would be text, should be video/ogg
instead.)
(Earlier versions) of IE cannot cast a function object to it's source as you request it. Thus, the strings cannot be exchanged that easily.
You can either replace the whole old "_self" function by a new _parent function, e.g.:
$('a[onclick*="_self"]').attr('onclick', function() { _parent-stuff });
or - I read your last comment and the second solution won't work for you as it would require changing the HTML of the body.
-28401891 0Check out Array#map.
ids = [ 123, 456 ] connections = ids.map do |id| @graph.get_connections("#{ id }","?fields=posts") end
-10273591 0
-32906659 0 Just add a dummy column with the source name:
$query = '(SELECT "item" as table, id,name FROM `item` WHERE `accepted` = '1' AND `name` LIKE '%".$search."%') UNION ALL (SELECT "category" AS table, id,name FROM `category` WHERE `name` LIKE '%".$search."%') UNION ALL (SELECT "store" AS table, id,name FROM `store` WHERE `accepted` = '1' AND `name` LIKE '%".$search."%') LIMIT 25 ';
-1600849 0 Look up in the registry to find the DLL associated with the ProgID you have. Once you have its full path, load it as a normal .NET assembly:
var type = Type.GetTypeFromProgID("My.ProgId", true); var regPath = string.Format(@"{0}\CLSID\{1:B}\InProcServer32", Registry.ClassesRoot, type.GUID); var assemblyPath = Registry.GetValue(regPath, "", null); if (!string.IsNullOrEmpty(assemblyPath)) { var assembly = Assembly.LoadFrom(assemblyPath); // Use it as a normal .NET assembly }
-4704472 0 How to set alarm in qt mobility application Is it possible to set an alarm for a specific time in Qt?
-5597109 0I have an app that does something similar - we use Open ID and OAuth exclusively for logins, and while we store the user's email address (Google Account or Facebook sends it back during authentication) they never login using it and so don't have/need a password.
This is a callback for what happens when a user signs up via Facebook:
User.create!( :facebook_id => access_token['uid'], :email => data["email"], :name => data["name"], :password => Devise.friendly_token[0,20])
The Devise.friendly_token[...]
just generates a random 20 character password for the user, and we are using our default User model with devise just fine. Just setting the password in a similar way on your users would be my approach, since you are never going to use their password. Also, if you ever change your mind and want them to be able to login, you can just change a user's password in the database and build a login form, and devise will take care of the rest.
An inline event handler like your onclick='...'
can only reference globally scoped variables and functions, but if your variable named global
is declared inside a function (inside a document.ready handler, for example) then it is not global and the inline attribute event handler can't see it.
Can someone let me know if there is a way to get the inbox sms in pdu format?
-15984334 0You can get yourself right to left,
left
to something like stackoverflow
right
to left
stackoverflow
to right
margin:
and padding:
, if like margin:0 1px 0 5px
change to margin:0 5px 0 1px
Java code may need to be changed, I do not know
I'm currently trying to learn angularJS and am having trouble accessing data between controllers.
My first controller pulls a list of currencies from my api and assigns it to $scope.currencies. When I click edit, what is supposed to happen is that it switches the view which uses another controller. now when debugging using batarang, $scope.currencies does show an array of currency objects:
{ currencies: [{ CurrencyCode: HKD Description: HONG KONG DOLLAR ExchangeRateModifier: * ExchangeRate: 1 DecimalPlace: 2 }, { CurrencyCode: USD Description: US DOLLAR ExchangeRateModifier: * ExchangeRate: 7.7 DecimalPlace: 2 }] }
But when using angular.copy
, the $scope.copiedcurrencies
result in null.
function CurrencyEditCtrl($scope, $injector, $routeParams) { $injector.invoke(CurrencyCtrl, this, { $scope: $scope }); $scope.copiedcurrencies = angular.copy($scope.currencies); console.log($scope.copiedcurrencies); }
-11233777 0 I've got a functional solution using option #1, but it's such a hack I can't bear to post it publicly. Basically, in serializeData I'm reaching into the model and modifying _relations before and after a call to toJSON. Not thread safe and ugly as heck. Hoping to come back soon and find a proper solution.
-40104926 0 Javascript - Does not save into database when i change value in javascript sideMy code looks like this:
document.getElementById("medewerkers").value = mdwString; document.getElementById("medewerkersomschr").value = mdwNaam; $("#medewerkers").val(mdwString); $("#medewerkersomschr").val(mdwNaam); document.getElementById("machines").value = mchString; document.getElementById("machinesomschr").value = mchNaam; $("#machines").val(mchString); $("#machinesomschr").val(mchNaam);
As u can see i tried two ways to get a value into fields.
This does work for me, but next up when i try to save the values into the database it goes wrong. It looks like the view got updated but not the value of the html itself. Does anyone have an idea what i am doing wrong or what i should change up?
-11914152 1 How to send the TAB button using Python In SendKey and PywinAuto ModulesThis is the my code which will open the window and send the keys to the window but some screen s are not working
from pywinauto.application import * import time app=Application.Start("Application.exe") app.window_(title="Application") time.sleep(1) app.top_window_().TypeKeys("{TAB 2}")
-11900714 0 On the blog page you can use:
{% for post in site.posts %} … {% endfor %}
To retrieve all posts and show them all. If you want to filter more (say, you have a third category you wouldn't want to show on this page:
{% for post in site.posts %} {% if post.categories contains 'post' or post.categories contains 'photos' %} ... {% endif %} {% endfor %}
-1657811 0 Subscriptions in the iPhone SDK really are to get around the fact that you cannot sell virtual credits, therefore what you can do is sell a subscription and make the digital content free from within your application assuming the user has a subscription to your service, you are correct in that you have to handle the majority of the logic yourself
-23474010 0 Java: How to copy automatically a file each time one is generated in a folder?I am asking for a Java code.
An ERP generates XML files in a folder, and each one has a different name.
For data extraction, I need to:
If new file is generated:
Copy file from the main folder to a secondary folder
Rename this file under "temp"
Extract data with an ETL (Talend) from "temp"
Delete the file "temp"
My question is: How to capture automaticaly a file with Java in order to copy or rename it each time one is generated?
Thanks
-36421576 0 In import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener; SimpleImageLoadingLIstneer is not foundI am learning android and new to android. I want to pick multiple images from gallery and then want to show them in gridview and for that i am using UniversalImageLoader library 1.9.5
To Use UniversalImageLoader Library i added the following dependency in build.gradle app module
compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
and then i copied and pasted the solution from some tutorial
In This my mainactivity is like following in which i used universal image loader library
package tainning.infotech.lovely.selectmultipleimagesfromgallery; import java.util.ArrayList; import android.content.Context; import android.database.Cursor; import android.graphics.Bitmap; import android.os.Bundle; import android.provider.MediaStore; import android.util.Log; import android.util.SparseBooleanArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.BaseAdapter; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.Toast; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.GridView; import android.widget.ImageView; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener; /** * @author Paresh Mayani (@pareshmayani) */ public class MainActivity extends BaseActivity { private ArrayList<String> imageUrls; private DisplayImageOptions options; private ImageAdapter imageAdapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.content_main); final String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID }; final String orderBy = MediaStore.Images.Media.DATE_TAKEN; Cursor imagecursor = managedQuery( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null, null, orderBy + " DESC"); this.imageUrls = new ArrayList<String>(); for (int i = 0; i < imagecursor.getCount(); i++) { imagecursor.moveToPosition(i); int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA); imageUrls.add(imagecursor.getString(dataColumnIndex)); System.out.println("=====> Array path => "+imageUrls.get(i)); } options = new DisplayImageOptions.Builder() .showStubImage(R.drawable.stub_image) .showImageForEmptyUri(R.drawable.image_for_empty_url) .cacheInMemory() .cacheOnDisc() .build(); imageAdapter = new ImageAdapter(this, imageUrls); GridView gridView = (GridView) findViewById(R.id.gridview); gridView.setAdapter(imageAdapter); /*gridView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { startImageGalleryActivity(position); } });*/ } @Override protected void onStop() { imageLoader.stop(); super.onStop(); } public void btnChoosePhotosClick(View v){ ArrayList<String> selectedItems = imageAdapter.getCheckedItems(); Toast.makeText(MainActivity.this, "Total photos selected: "+selectedItems.size(), Toast.LENGTH_SHORT).show(); Log.d(MainActivity.class.getSimpleName(), "Selected Items: " + selectedItems.toString()); } /*private void startImageGalleryActivity(int position) { Intent intent = new Intent(this, ImagePagerActivity.class); intent.putExtra(Extra.IMAGES, imageUrls); intent.putExtra(Extra.IMAGE_POSITION, position); startActivity(intent); }*/ public class ImageAdapter extends BaseAdapter { ArrayList<String> mList; LayoutInflater mInflater; Context mContext; SparseBooleanArray mSparseBooleanArray; public ImageAdapter(Context context, ArrayList<String> imageList) { // TODO Auto-generated constructor stub mContext = context; mInflater = LayoutInflater.from(mContext); mSparseBooleanArray = new SparseBooleanArray(); mList = new ArrayList<String>(); this.mList = imageList; } public ArrayList<String> getCheckedItems() { ArrayList<String> mTempArry = new ArrayList<String>(); for(int i=0;i<mList.size();i++) { if(mSparseBooleanArray.get(i)) { mTempArry.add(mList.get(i)); } } return mTempArry; } @Override public int getCount() { return imageUrls.size(); } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if(convertView == null) { convertView = mInflater.inflate(R.layout.row_multiphoto_item, null); } CheckBox mCheckBox = (CheckBox) convertView.findViewById(R.id.checkBox1); final ImageView imageView = (ImageView) convertView.findViewById(R.id.imageView1); imageLoader.displayImage("file://"+imageUrls.get(position), imageView, options, new SimpleImageLoadingListener() { @Override public void onLoadingComplete(Bitmap loadedImage) { Animation anim = AnimationUtils.loadAnimation(MainActivity.this,Animation.START_ON_FIRST_FRAME); imageView.setAnimation(anim); anim.start(); } }); mCheckBox.setTag(position); mCheckBox.setChecked(mSparseBooleanArray.get(position)); mCheckBox.setOnCheckedChangeListener(mCheckedChangeListener); return convertView; } OnCheckedChangeListener mCheckedChangeListener = new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // TODO Auto-generated method stub mSparseBooleanArray.put((Integer) buttonView.getTag(), isChecked); } }; } } but when i try to build the project it shows me the error following error Error:(26, 53) error: cannot find symbol class SimpleImageLoadingListener and also in following import statement import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener; SimpleImageLoadingListener is underlined as red line. and it says cannot find symbol SimpleImageLoadingListener . The BaseActivity.java is following import android.app.Activity; import com.nostra13.universalimageloader.core.ImageLoader; /** * @author Paresh Mayani (@pareshmayani) */ public abstract class BaseActivity extends Activity { protected ImageLoader imageLoader = ImageLoader.getInstance(); } The UilApplication.java is like following package tainning.infotech.lovely.selectmultipleimagesfromgallery; /** * Created by student on 4/5/2016. */ import android.app.Application; import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; /** * @author Paresh Mayani (@pareshmayani) */ public class UILApplication extends Application { @Override public void onCreate() { super.onCreate(); // This configuration tuning is custom. You can tune every option, you may tune some of them, // or you can create default configuration by // ImageLoaderConfiguration.createDefault(this); // method. ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext()) .threadPoolSize(3) .threadPriority(Thread.NORM_PRIORITY - 2) .memoryCacheSize(1500000) // 1.5 Mb .denyCacheImageMultipleSizesInMemory() .discCacheFileNameGenerator(new Md5FileNameGenerator()) //.enableLogging() // Not necessary in common .build(); // Initialize ImageLoader with configuration. ImageLoader.getInstance().init(config); } } The manifest file is this <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="tainning.infotech.lovely.selectmultipleimagesfromgallery" > <!-- Include following permission if you load images from Internet --> <uses-permission android:name="android.permission.INTERNET" /> <!-- Include following permission if you want to cache images on SD card --> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" android:theme="@style/AppTheme.NoActionBar" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Build.gradle(Module:app) is like this apply plugin: 'com.android.application' android { compileSdkVersion 23 buildToolsVersion "23.0.2" defaultConfig { applicationId "tainning.infotech.lovely.selectmultipleimagesfromgallery" minSdkVersion 15 targetSdkVersion 23 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.1.1' compile 'com.android.support:design:23.1.1' compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5' } Kindly help as soon as possible.
I searched for the solution of above problem but was not able to find any. I searched as much i can but didn't get the solution.
Thanks in advance
-35106626 1 Implement Neighbors to find the d-neighborhood of a string in Python Input: A string Pattern and an integer d. Output: The collection of strings Neighbors(Pattern, d).
Sample Input:
ACG 1
Sample Output:
TCG ACG GCG CCG ACA ACT AGG AAG ATG ACC
What is the algorithm to solve this problem?
-1316659 0 BLOB data to simple string in DataGridView?I am using C# & MYSQL to develop a desktop application.
In one of my form I have a DataGridView
(dgvBookings) and in my database table I have a table tblBookings which contains a field specialization
of type BLOB
.
I am selecting data with following query,
SELECT * FROM tblBookings WHERE IsActive=1;
and then binding the data with DataGridView as,
dgvBookings.DataSource = ds.Tables["allbookings"];
BUT after binding the data in gridview it shows Byte[] Array
value for all rows of column specialization
which is of BLOB type.
How yo solve this problem, I want the data in String format, whatever is written in that column should be show as it is there in the grid.
-8912963 0I'm not sure I understand your question, but you may want to look into the NSNotificationCenter. You can use it to send messages to your controllers, here's an example of triggering a notification:
[[NSNotificationCenter defaultCenter] postNotificationName:@"myNotificationName" object:self userInfo:[NSDictionary dictionaryWithObject:XXXX forKey:@"someObject"]];
As you can see, you can even send parameters to it. And in the target controller you just register an observer to respond to those messages:
[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(yourMethodHere:) name: @"myNotificationName" object: nil];
Regards!
-28441260 0 Use ng-model in hrefAngular is new to me. I try to make a link which contains a dynamic href
attribute.
So far, I read that using ng-href
instead of href
was a good practice. But, when I try this :
<a target="_blank" data-ng-href="{{myUrl}}">Follow this URL</a>
(I also tried without the curly brackets)
The href value does not take the value that I put in the controller :
function (data) { console.log("data : %o", data); console.log("url : "+data.url); $scope.myUrl = data.url; }
Am I doing something wrong?
Here is the value of data as shown is the console :
data : Object requestTokenId: 3405 url: "https://api.twitter.com/oauth/authorize?oauth_token=TBqMIpdz[...]" __proto__: Object
More background :
I want to create a "twitter authorization" modal :
<div data-ng-controller="myController"> <!-- Some HTML elements on which data-binding works. --> <div class="modal fade" id="authorizationTwitterModal"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button> <h4 class="modal-title">Authorization</h4> </div> <div class="modal-body"> <ol> <li>Connect to your account</li> <li id="liAuthorizationTwitterURL"><a target="_blank" ng-href="{{myUrl}}">Follow this URL</a></li> <li>Authorize Ambasdr</li> <li>Copy/Paste the authorization code here :</li> </ol> <p class="text-center"> <input id="verifier" name="value" type="text"> </p> </div> </div> </div> </div>
Then, when the user wants to authorize twitter, I call my server, which calls twitter then give me the URL that I want to place into the href:
$scope.addTwitterAccount = function(brandId) { console.log("addTwitterAccount"); var popup = wait("Authorization"); //$scope.myUrl = 'http://www.google.fr'; <- This change works! $.doPost("/api/request_token/", { socialMedia: 'TWITTER' }, function (data) { console.log("data : %o", data); console.log("url : "+data.url); $scope.myUrl = data.url; // <- This change does not work! } ); };
-36458024 0 Git pull -The following untracked working tree files would be overwritten by merge I am trying to do git pull
in master branch and I see this message with a long list of files
The following untracked working tree files would be overwritten by merge:
I really don't care if these files are over written or not, as I need to get the latest form remote. I have looked into it and I cannot do git fetch
, git add *
and git reset HARD
When I do git status
, it shows me the list of only untracked files. I don't want to commit these files
A pointer is a variable, that store a memory address
The stored address in the pointer is the address of the first-block of the memory-structure of the object it points at
The syntax of a pointer that points at an object of type TYPE
:
TYPE * pointer; // define a pointer of type TYPE
NULL
(address 0
) denotes a pointer that doesn't point anywhere currently:
pointer = 0;
To get the memory address of a variable or object:
pointer = &object; // pointer now stores the address of object
To get the pointed TYPE
variable, you de-reference the pointer:
assert(&(*pointer) == &object); // *pointer ~ object
In example:
int a = 10; // type int int * b = &a; // pointer to int int* * c = &b; // pointer to int* printf(" %d \n ", a ); printf(" %d \n ", *b ); printf(" %d \n ", **c ); char t [256] = "Not Possible ?"; char * x = t; char * y = (x + 4); // address arithmetic printf(" %s \n ", x ); // Not Possible ? printf(" %s \n ", y ); // Possible ?
void*
is a special pointer-type that can store any pointer of any degree, but cannot be used until you cast it to a compatible type ..
void * z = &c; // c holds int** printf(" %d \n ", **((int**)c) );
-33248746 0 Hoisting moves function declarations and variable declarations to the top, but doesn't move assignments.
Therefore, you first code becomes
var a; function f() { console.log(a.v); } f(); a = {v: 10};
So when f
is called, a
is still undefined
.
However, the second code becomes
var a, f; a = {v: 10}; f = function() { console.log(a.v); }; f();
So when f
is called, a
has been assigned.
Good morning,
Does anyone know if there is an easy way I can use a SQL query in Excel to select specific data from an Excel spreadsheet without having to use VBA, Access, an SQL database or complicated Excel formula?
Thank you very much.
-23442863 0 osx x64 reverse tcp shell code program terminate with successBeen trying to learn some assembler 64 bit on osx and thought a good exercise would be to port a reverse tcp shell code. The program then compiled and linked run fine and listen to the given port 4444, but then I try to connect with nc -nv 127.0.0.1 4444
the shell_code terminate with success and the response back to nc is: Connection to 127.0.0.1 4444 port [tcp/*] succeeded!
It is compiled and linked with:
nasm -g -f macho64 bindshell.s ld -arch x86_64 -macosx_version_min 10.7.0 -lSystem -o bindshell bindshell.o (nasm -v NASM version 2.11.02 compiled on Feb 19 2014) uname -a Darwin MacBook-Pro.local 12.4.0 Darwin Kernel Version 12.4.0: Wed May 1 17:57:12 PDT 2013; root:xnu-2050.24.15~1/RELEASE_X86_64 x86_64
Been trying to debug it and looked at registers and memory but can't see whats missing, new to 64 bit assembler. The code used is:
BITS 64 section .text global start start: jmp runsh start_shell: dd '/bin//sh', 0 runsh: lea r14, [rel start_shell] ; get address of shell mov rax, 0x2000061 ; call socket(SOCK_STREAM, AF_NET, 0); mov rdi, 2 ; SOCK_STREAM = 2 mov rsi, 1 ; AF_NET = 1 xor rdx, rdx ; protocol, set to 0 syscall mov r12, rax ; save socket from call sock_addr: xor r8, r8 ; clear the value of r8 push r8 ; push r8 to the stack as it's null (INADDR_ANY = 0) push WORD 0x5C11 ; push our port number to the stack (Port = 4444) push WORD 2 ; push protocol argument to the stack (AF_INET = 2) mov r13, rsp ; Save the sock_addr_in into r13 ;bind mov rax, 0x2000068 ; bind(sockfd, sockaddr, addrleng); mov rdi, r12 ; sockfd from socket syscall mov rsi, r13 ; sockaddr mov rdx, 16 ; addrleng the ip address length syscall ;listen mov rax, 0x200006A ; int listen(sockfd, backlog); mov rdi, r12 ; sockfd xor rsi, rsi ; backlog syscall ;accept mov rax, 0x200001E ; int accept(sockfd, sockaddr, socklen); mov rdi, r12 ; sockfd xor rsi, rsi ; sockaddr xor rdx, rdx ; socklen syscall dup: ; dup2 for stdin, stdout and stderr mov rax, 0x200005A ; move the syscall for dup2 into rax mov rdi, r12 ; move the FD for the socket into rdi syscall ; call dup2(rdi, rsi) cmp rsi, 0x2 ; check to see if we are still under 2 inc rsi ; inc rsi jbe dup ; jmp if less than 2 ;execve mov rax, 0x200003B ; execve(char *fname, char **argp, char **envp); mov rdi, r14 ; set the address to shell xor rsi, rsi xor rdx, rdx run_cmd: ; using as break point syscall
-3586871 0 Bold & Non-Bold Text In A Single UILabel? How would it be possible to include both bold and non-bold text in a uiLabel?
I'd rather not use a UIWebView.. I've also read this may be possible using NSAttributedString but I have no idea how to use that. Any ideas?
Apple achieves this in several of their apps; Examples Screenshot:
Thanks! - Dom
-8856750 0 How do I sidestep TT_NUMBER from StreamTokenizerI replaced a call to String.split() with a loop using StreamTokenizer, because my users needed quoting functionality. But now I'm having problems from numbers being converted to numbers instead of left as Strings. In my loop if I get a TT_NUMBER, I convert it back to a String with Double.toString(). But that is not working for some long serial numbers that have to get sent to me; they are being converted to exponential notation.
I can change the way I am converting numbers back into Strings, but I would really like to just not parse numbers in the first place. I see that StreamTokenizer has a parseNumbers() method, that turns on number parsing, but there doesn't seem to be a way to turn it off. What do I have to do to create and configure a parser that is identical to the default but does not parse numbers?
-27482844 0It's a placeholder for formatting. It represents a string.
" %s link.get" % ('href')
is equivalent to
" " + 'href' + " link.get"
The placeholders can make things more readable, without cluttering the text with quotes and +. Though in this case, there is no variable, so it is simply
" href link.get"
However, .format()
is preferred to %
formatting nowadays, like
" {} link.get".format('href')
-38100821 0 laravel 5 subdomain not working in live I have a site that can be access in stage.mysite.com
now I want to have a subdomain for another page and it can be access at profile.stage.mysite.com
.
in my server I have configured the hosting.
ServerAdmin webmaster@localhost ServerName stage.mysite.com ServerAlias *.stage.mysite.com DocumentRoot /var/www/staging.mysite.com/public
in my routes.php this is the code.
Route::group(['domain' => 'profile.stage.mysite.com'], function() { Route::get('/', 'FrontendController@profile'); });
but when I tried to access http://profile.stage.mysite.com
returns Server not found
error. any ideas how to access my static page into subdomain?
I have functions which are called many times and require temporary arrays. Rather than array allocation happening every time the function is called, I would like the temporary to be statically allocated once.
How do I create a statically allocated array in Julia, with function scope?
-3897575 0With the AudioQueue, I can register for a callback whenever the system needs sound, and respond by filling a buffer with raw audio data.
The closest analogy to this in Android is AudioTrack
. Rather than the callback (pull) mechanism you are using, AudioTrack
is more of a push model, where you keep writing to the track (presumably in a background thread) using blocking calls.
I am using Jörn Zaefferer's JQuery Validate, but I need to make some database calls to validate some fields (for example to check if a User Name is unique). Is this possible using this plugin, and if so, does someone have some syntax examples? Here is my current code :
$("form").validate({ rules: { txtUserName: { required: true, minlength: 4 }, txtPassword: { required: true }, txtConfirmPassword: { required: true, equalTo: "#txtPassword" }, txtEmailAddress: { required: true, email: true }, txtTelephoneNumber: { required: true, number: true } }, messages: { txtUserName: { required: "Please enter a User Name", minlength: "User Name must be at least 4 characters" }, txtPassword: { required: "Please enter a Password" }, txtConfirmPassword: { required: "Please confirm Password", equalTo: "Confirm Password must match Password" }, txtEmailAddress: { required: "Please enter an Email Address", email: "Please enter a valid Email Address" }, txtTelephoneNumber: { required: "Please enter a Telephone Number", number: "Telephone Number must be numeric" } } }); });
EDIT :
I have got this far, but when I do this, I lose the values on my form, presumably because the form has already posted at this point?
$("form").validate({ //errorLabelContainer: $("#divErrors"), rules: { txtUserName: { required: true, minlength: 4 }, txtPassword: { required: true }, txtConfirmPassword: { required: true, equalTo: "#txtPassword" }, txtEmailAddress: { required: true, email: true }, txtTelephoneNumber: { required: true, number: true//, //postalCode:true } }, messages: { txtUserName: { required: "Please enter a User Name", minlength: "User Name must be at least 4 characters" }, txtPassword: { required: "Please enter a Password" }, txtConfirmPassword: { required: "Please confirm Password", equalTo: "Confirm Password must match Password" }, txtEmailAddress: { required: "Please enter an Email Address", email: "Please enter a valid Email Address" }, txtTelephoneNumber: { required: "Please enter a Telephone Number", number: "Telephone Number must be numeric" } }, onValid: addUser() }); });
function addUser() {
alert($('input[name="txtUserName"]').val());
}
-17269726 0depending on the state of the resource, if it's constant, you can put them in a enum object. it if's persistent information, you can put in conf/evolution/default/1.sql, and Play will automatically load it when you initialize everything. you can put configuration constants in conf/application.conf, if it's strings, you can put in message file.
-21822188 0 Images are not showing in pdf created using velocity templateI create pdf using Velocity template, but i am not able to put images in pdf. I am adding url into context object and accessing that object into eot.vm file, url is going proper but still images are not displaying in pdf.
Thanks & Regards, Tushar
-21969883 0The pure part of algorithm M is quite short indeed:
algorithmM = mapM (\n -> [0..n-1])
For example, here's a run in ghci:
> algorithmM [2,3] [[0,0],[0,1],[0,2],[1,0],[1,1],[1,2]]
It's also quite easy to put an input/output loop around it. For example, we could add
main = readLn >>= mapM_ print . algorithmM
Compile and run a program containing these two (!) lines, and you will see something like this:
% ./test [2,3] [0,0] [0,1] [0,2] [1,0] [1,1] [1,2]
-4337576 0 The Problem
I'm assuming that you are using JPA to get your data as objects that can be handled by JAXB. If this is the case the JPA objects may be using lazy loading meaning that a query may not realize all the data at once. However as the JAXB implementation traverses the object graph, more and more of it is brought into memory until you run out.
Option #1 - Provide Data in Chunks
One approach is to return your data in chunks and offer a URI like the one below:
These parameters tie in very nicely to JPA query settings:
namedQuery.setFirstResult(10); namedQuery.setMaxResults(100);
Option #2 - Provide Links to Get More Data
Alternatively, instead of including all the data you can provide links to get more. For example instead of:
<purchase-order> <product id="1"> <name>...</name> <price>...</price> ... </product> <product id="2"> <name>...</name> <price>...</price> ... </product> ... </purchase-order>
You could return the following, the client can then request details on products using the provided URI. You can map this in JAXB using an XmlAdapter.
<purchase-order> <product>http://www.example.com/products/1</product> <product>http://www.example.com/products/2</product> ... </purchase-order>
For more information on XmlAdapter see:
-29248865 0 Normal.dotm alternative in Excel for referencing the same single VBA codeJust curiosity.
The only way I know so far is to create an add-in with code, put it in some trusted directory and hope it opens when you need it. The drawback is that it sometimes does not open together with application (e.g. I have a custom UDF in the add-in, I use it in the worksheet and an error is what I get, because the addin hasn't started). For this I have a button on my ribbon which calls a sub in the addin which does nothing, but then the addin is activated the UDF works.
Is there any other efficient way to reference code in another workbooks, like in Word we have normal.dotm template?
-4949471 0To hint a browser that it should download a file, make sure you send the Content-Disposition: attachment
header from your application.
I think syntactical uniformity is quite important in generic programming. For instance consider,
#include <utility> #include <tuple> #include <vector> template <class T> struct Uniform { T t; Uniform() : t{10, 12} {} }; int main(void) { Uniform<std::pair<int, int>> p; Uniform<std::tuple<int, int>> t; Uniform<int [2]> a; Uniform<std::vector<int>> v; // Uses initializer_list return 0; }
-8808030 0 RequestBody of a REST application Iam bit new to SpringMVC REST concept. Need a help from experts here to understand/ resolve following issue, I have developed a SpringMVC application, following is a part of a controller class code, and it works perfectly ok with the way it is, meaning it works ok with the JSON type object,
@RequestMapping(method = RequestMethod.POST, value = "/user/register") public ModelAndView addUser( @RequestBody String payload) { try{ ObjectMapper mapper = new ObjectMapper(); CreateNewUserRequest request = mapper.readValue(payload, CreateNewUserRequest.class); UserBusiness userBusiness = UserBusinessImpl.getInstance(); CreateNewUserResponse response = userBusiness.createNewUser(request); return new ModelAndView(ControllerConstant.JASON_VIEW_RESOLVER, "RESPONSE", response);
and this is my rest-servlet.xml looks like
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" /> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> <bean id="jsonViewResolver" class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" /> <bean id="viewResolver" class="org.springframework.web.servlet.view.BeanNameViewResolver" /> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="jsonConverter" /> </list> </property> </bean> <bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="supportedMediaTypes" value="application/json" /> </bean> <bean name="UserController" class="com.tap.mvp.controller.UserController"/>
My problem is how do i make it work for normal POST request, My controller should not accept JSON type object instead it should work for normal HTTP POST variables. How do i get values from the request?What are the modifications should i need to be done for that. I need to get rid of
ObjectMapper mapper = new ObjectMapper(); CreateNewUserRequest request = mapper.readValue(payload, CreateNewUserRequest.class);
and instead need to add way to create an instance of
CreateNewUserRequest
class, by invoking its constructor. For that i need to get values from request. How do i do that? Can i treat @RequestBody String payload as a map and get the values? or is there a specific way to get values from the request of HTTP POST method? following values will be in the request,
-11148833 0 How to perform element-wise left shift with __m128i?firstName, lastName, email,password
The SSE shift instructions I have found can only shift by the same amount on all the elements:
_mm_sll_epi32()
_mm_slli_epi32()
These shift all elements, but by the same shift amount.
Is there a way to apply different shifts to the different elements? Something like this:
__m128i a, __m128i b; r0:= a0 << b0; r1:= a1 << b1; r2:= a2 << b2; r3:= a3 << b3;
-30298027 0 If you are not well aware of executor service then the easiest way to achieve this is by using Thread wait and notify mechanism:
private final static Object lock = new Object(); private static DataType type = null; public static String getTypeOfData { new Thread(new Runnable() { @Override public void run() { fetchData(); } }).start(); synchronized (lock) { try { lock.wait(10000);//ensures that thread doesn't wait for more than 10 sec if (type == DataType.partial || type == DataType.temp) { return "partial"; }else{ return "full"; } } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } return "full"; } private static void fetchData() { synchronized (lock) { type = new SelectTypes().getType(); lock.notify(); } }
You might have to do some little changes to make it work and looks better like instead of creating new thread directly you can use a Job to do that and some other changes based on your requirement. But the main idea remains same that Thread would only wait for max 10 sec to get the response.
-5066444 0I have figured it out! Although I don't know why the Xlinq approach doesn't work... here is the code that worked for me instead of the query:
public XElement filter(int min = 0, int max = int.MaxValue) { XElement filtered = new XElement("Stock"); foreach (XElement product in xmlFile.Elements("Product")) { if ((int)product.Element("Price") >= min && (int)product.Element("Price") <= max) filtered.Add(product); } return filtered; }
that would be great if someone gives me an explain. thanks for reading
-29527866 0 Jquery-ui autocomplete won't work in a specific onlyBeen trying for 2 days and appreciate any help. I can get autocomplete to work outside of the div I am trying to make it work in. The specific div, input field, does not work.
I have tried as others mentioned setting the .ui-autocomplete { z-index: 50000 !important; } to the class, but still doesn't work.
Here is a link to the test page. The div is "destinations" front and center. http://www.inidaho.com/responsive/test4.asp
Here is my header code:
<link rel="stylesheet" media="screen" href="css/bootstrap-theme.min.css"> <link rel="stylesheet" media="screen" href="css/bootstrap.min.css"> <link rel="stylesheet" media="screen" href="css/glyphicons.css"> <link rel="stylesheet" media="screen" href="css/iitheme.css"> <link href='https://fonts.googleapis.com/css?family=Roboto:400,100,300,500,700,900,100italic,300italic,400italic,500italic,700italic,900italic' rel='stylesheet' type='text/css'> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script>window.jQuery || document.write('<script src="js/vendor/jquery-1.10.2.min.js"><\/script>')</script> <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/themes/smoothness/jquery-ui.css" /> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js"></script> <script> $(function() { var availableTags = [ "ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++", "Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran" ]; $("#destination").autocomplete({ source: availableTags }); }); </script>
and here is the input I am trying to autocomplete
<form id="home-searchform" class="home-searchform"> <div class="col-lg-8 col-med-5 col-sm-4 col-xs-12 text-center ui-widget"> <label for="destination">destination</label> <input id="destination" name="destination" placeholder="Choose Destination"> </div> <div class="col-lg-4 col-med-3 col-sm-3 col-xs-12"> <input type="button" name="submit" value="GO" class="ui-btn med ui-main txt- center"/> </div> </form>
I have tried to format the code above correctly, but am having trouble so apologize. Any suggestions are appreciated. Best.
-17057721 0Highlighting the code of interest and hitting tab should add another level of indentation. Shift-tab will remove a level of indentation.
-35840752 0 How to use unverified custom domains with Google App EngineI need customers to be able to point their own custom domains to my GAE app.
e.g. customersdomain.com -- CNAME --> myapp.com (which in turn points to myapp.appspot.com)
I know that I can link a domain to my Google account and then use that domain to serve app engine, but this process does not scale and requires that I have direct access to the customer's domain register/DNS. The only other alternative is to force customers to sign up for Google Apps (why!).
Almost all other PaaS make this process painless:
Does anyone know of a workaround for this? Or am I just going to have to manually link hundreds of domains to my account?
-36309391 0 SSRS: Calculate the Max ValueI use SQL Server Report Builder.
I have got 20 machines and I calculate the scrap data for these 20 machines. In my query it looks like:
SELECT SUM(case when ScrapName = 'Blown wheel' then scrapUnits else 0 end) AS BlownWheel, Sum(case when ScrapName = 'Blown bell' then scrapUnits else 0 end) AS BlownBell, Sum(case when ScrapName = 'Produced' then scrapUnits else 0 end) AS Produced
And to get the scrap I did a calculation in SSRS:
=SUM(Fields!BlownWheel.Value) + SUM(Fields!BlownBell.Value) / SUM(Fields!Produced.Value)*100
This calculation gave me the correct value.
My Problem now is that I must create a new report and in this report I would like to show one of these 20 machines which produced the maximum value of scrap.
I have done this manually in Excel before. And now I would like to create it as a Report.
-16838693 0There are really only a few methods in NSJSONSerialization
. Take a look at the documentation.
json_dic_values = [NSJSONSerialization JSONObjectWithData: [response dataUsingEncoding: NSUTF8StringEncoding] options: 0 error: &error];
-18059 0 Prevent WebBrowser control from swallowing exceptions I'm using the System.Windows.Forms.WebBrowser
, to make a view a-la Visual Studio Start Page. However, it seems the control is catching and handling all exceptions by silently sinking them! No need to tell this is a very unfortunate behaviour.
void webBrowserNavigating(object sender, WebBrowserNavigatingEventArgs e) { // WebBrowser.Navigating event handler throw new Exception("OMG!"); }
The code above will cancel navigation and swallow the exception.
void webBrowserNavigating(object sender, WebBrowserNavigatingEventArgs e) { // WebBrowser.Navigating event handler try { e.Cancel = true; if (actions.ContainsKey(e.Url.ToString())) { actions[e.Url.ToString()].Invoke(e.Url, webBrowser.Document); } } catch (Exception exception) { MessageBox.Show(exception.ToString()); } }
So, what I do (above) is catch all exceptions and pop a box, this is better than silently failing but still clearly far from ideal. I'd like it to redirect the exception through the normal application failure path so that it ultimately becomes unhandled, or handled by the application from the root.
Is there any way to tell the WebBrowser
control to stop sinking the exceptions and just forward them the natural and expected way? Or is there some hacky way to throw an exception through native boundaries?
I have my project in expressjs and Mongoose(with mongodb). I have multiple roles of users - admin, manager, user
I want few fields of each table to be accessible by manager while others not. by default user would not have any edit access, admin would have full access. One way is to make this controls in each controller function by looking at the role of user. Is there any easy way of doing it such as checking if the user has controls before saving once for each table so as to avoid duplication of business logic.
My ordersschema is as follows. I dont want customer info to be adited without admin permission.
var OrderSchema = new Schema({ order_type: { type: String, trim: true }, customer_phone: { type: String, trim: true } }); var managerAccess = [order_type];
My user model is as follows(more fields not added)
var UserSchema = new Schema({ firstName: { type: String, trim: true, default: '', validate: [validateLocalStrategyProperty, 'Please fill in your first name'] }, roles: { type: [{ type: String, enum: ['user', 'admin'] }], default: ['user'] }, })
-14467546 0 At the begining of your fragment shader source file (the very first line) put this:
#version 140
This means that you are telling the GLSL compiler that you use the version 1.40 of the shading language (you can, of course, use a higher version - see Wikipedia for details).
Alternatively, if your OpenGL driver (and/or hardware) doesn't support GLSL 1.40 fully (which is part of OpenGL 3.1), but only GLSL 1.30 (OpenGL 3.0), you can try the following:
#version 130 #extension GL_ARB_uniform_buffer_object : require
However, this one will work only if your OpenGL 3.0 driver supports the GL_ARB_uniform_buffer_object extension.
Hope this helps.
-25630404 0 C++ Multiple Static Functions With Same Name But Different ArgumentsIt appears as though I stumbled across something odd while trying to write my own wrapper for the freeglut api. Basically, I am writing my own little library to make using freeglut easier. One of the first things that I am doing is attempting to implement my own Color class which will be fed into "glClearColor". I am also having it so that you can enter the colors in manually; this means that I will have mutliple static methods with the same name but different parameters/arguments. I tried to compile this afterwards but recieved an error that makes me think that the compiler cant decide which method to use—which is odd considering the two methods in question are still different. One takes a Color3 class and the other a Color4.
Here is some source:
GL.H
#pragma once #include "Vector3.h" #include "Color3.h" #include "Color4.h" #include <string> class GL { public: static void initializeGL(int argc, char* argv); static void initializeDisplayMode(unsigned int displayMode); static void initializeWindowSize(int width, int height); static void createWindow(std::string title); static void mainLoop(); static void translate(const Vector3 &location); static void translate(float x, float y, float z); static void rotate(double rotation, float x, float y, float z); static void rotate(double rotation, const Vector3& axis); static void color3(const Color3 &color); static void color4(const Color4 &color); static void begin(); static void end(); static void pushMatrix(); static void popMatrix(); static void enable(int enableCap); static void viewport(); static void polygonMode(); static void matrixMode(); static void clearColor(const Color3 &color); static void clearColor(float red, float green, float blue); static void clearColor(float red, float green, float blue, float alpha); static void clearColor(const Color4 &color); static void vertex3(const Vector3 &location); static void vertex3(float x, float y, float z); static void loadIdentity(); static void perspective(); static void depthFunction(); };
GL.cpp
#include "GL.h" #include "freeglut.h" void GL::clearColor(const Color3 &color) { glClearColor(color.getRed,color.getGreen,color.getBlue, 1.0f); } void GL::clearColor(float red, float green, float blue) { glClearColor(red, green, blue, 1.0f); } void GL::clearColor(float red, float green, float blue, float alpha) { } void GL::clearColor(const Color4 &color) { }
And here is my compiler error:
1>------ Build started: Project: GameEngineToolkit, Configuration: Debug Win32 ------ 1> Main.cpp 1>c:\the capsule\c++\get\gameenginetoolkit\gameenginetoolkit\main.cpp(47): error C2665: 'GL::clearColor' : none of the 4 overloads could convert all the argument types 1> c:\the capsule\c++\get\gameenginetoolkit\gameenginetoolkit\gl.h(610): could be 'void GL::clearColor(const Color4 &)' 1> c:\the capsule\c++\get\gameenginetoolkit\gameenginetoolkit\gl.h(607): or 'void GL::clearColor(const Color3 &)' 1> while trying to match the argument list '(Color3 *)' 1> GL.cpp 1>c:\the capsule\c++\get\gameenginetoolkit\gameenginetoolkit\gl.cpp(8): error C3867: 'Color3::getRed': function call missing argument list; use '&Color3::getRed' to create a pointer to member 1>c:\the capsule\c++\get\gameenginetoolkit\gameenginetoolkit\gl.cpp(8): error C3867: 'Color3::getGreen': function call missing argument list; use '&Color3::getGreen' to create a pointer to member 1>c:\the capsule\c++\get\gameenginetoolkit\gameenginetoolkit\gl.cpp(8): error C3867: 'Color3::getBlue': function call missing argument list; use '&Color3::getBlue' to create a pointer to member 1> Generating Code... ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
As you can see, it seems that the compiler cant decide between using the Color3 function or the color4 function; I dont understand why because it should be obvious which one to choose(the Color3 one is the one I am using in my main).
As per request, here is my Color3 class:
Color3.h
#pragma once class Color3 { public: Color3(); Color3(float red, float green, float blue); void setRed(float red); void setGreen(float green); void setBlue(float blue); float getRed(); float getGreen(); float getBlue(); Color3 getColor(); ~Color3(); private: float red; float green; float blue; };
Color3.cpp
#include "Color3.h" Color3::Color3() { } Color3::Color3(float red, float green, float blue) { setRed(red); setGreen(green); setBlue(blue); } Color3::~Color3() { } float Color3::getRed() { return red; } float Color3::getGreen() { return green; } float Color3::getBlue() { return blue; } void Color3::setBlue(float blue) { this->blue = blue; } void Color3::setGreen(float green) { this->green = green; } void Color3::setRed(float red) { this->red = red; } Color3 Color3::getColor() { return *this; }
The Solution:
Use pointers.
GL.cpp
#include "GL.h" #include "freeglut.h" void GL::clearColor(Color3* color) { glClearColor(color->getRed(),color->getGreen(),color->getBlue(), 1.0f); } void GL::clearColor(float red, float green, float blue) { glClearColor(red, green, blue, 1.0f); } void GL::clearColor(float red, float green, float blue, float alpha) { } void GL::clearColor(Color4* color) { }
GL.H
#pragma once #include "Vector3.h" #include "Color3.h" #include "Color4.h" #include <string> class GL { public: static void initializeGL(int argc, char* argv); static void initializeDisplayMode(unsigned int displayMode); static void initializeWindowSize(int width, int height); static void createWindow(std::string title); static void mainLoop(); static void translate(const Vector3 &location); static void translate(float x, float y, float z); static void rotate(double rotation, float x, float y, float z); static void rotate(double rotation, const Vector3& axis); static void color3(const Color3 &color); static void color4(const Color4 &color); static void begin(); static void end(); static void pushMatrix(); static void popMatrix(); static void enable(int enableCap); static void viewport(); static void polygonMode(); static void matrixMode(); static void clearColor(Color3* color); // Use pointers instead static void clearColor(float red, float green, float blue); static void clearColor(float red, float green, float blue, float alpha); static void clearColor(Color4* color); // Same thing; no error. =P static void vertex3(const Vector3 &location); static void vertex3(float x, float y, float z); static void loadIdentity(); static void perspective(); static void depthFunction(); };
-40190814 0 How to save geolocation(displayed with Googlemaps) in local storage and load it later I have a problem with geolocation and local storage. So this bellow is my code. Excuse me that some of the text is in cyrillic but this is because that is homework of mine and I am from Bulgaria. It is not important what does the text say. You need to know only that first button is Get, second - Save, third one - Load. So I had to make first button to show my location with Google Maps - that's OK. I made it work. The tricky part is next. With the second button "Save" I have to save the data from geolocation into local Storage. And when clicking on the third button Load - the location saved in local Storage should come visible again in the (div id="map). I tried using different suggestions but every time something is not working. Please if someone can help me with an ideal at least. And the most important thing I am not allowed to use JQuery, only Java Script. If you have questions and you don't understand any part of the code please ask me and I'll be happy to explain or rewrite it. I want to thank you in advance for your help. P.S. I am beginner in coding, that's the reason I may ask stupid questions.Please have patience.
var x = document.getElementById("map"); function getLocation() { if (navigator.geolocation) { x.style.visibility = "visible"; navigator.geolocation.getCurrentPosition(showPosition, showError); } else { x.innerHTML = "Geolocation is not supported by this browser."; } } function showPosition(position) { var latlon = position.coords.latitude + "," + position.coords.longitude; var img_url = "https://maps.googleapis.com/maps/api/staticmap?center=" + latlon + "&zoom=14&size=400x300&sensor=false"; document.getElementById("map").innerHTML = "<img src='" + img_url + "'>"; } function showError(error) { switch (error.code) { case error.PERMISSION_DENIED: x.innerHTML = "User denied the request for Geolocation." break; case error.POSITION_UNAVAILABLE: x.innerHTML = "Location information is unavailable." break; case error.TIMEOUT: x.innerHTML = "The request to get user location timed out." break; case error.UNKNOWN_ERROR: x.innerHTML = "An unknown error occurred." break; } }
#text { width: 100%; margin-bottom: 15px; } #buttons { width: 100%; background-color: #8c8c8c; color: white; border: 2px solid #8c8c8c; padding-top: 2px; } #map { width: 100%; border: 2px solid #8c8c8c; border-bottom-right-radius: 10px; border-bottom-left-radius: 10px; visibility: hidden; background-color: #cccace; } .buttons { border-top-left-radius: 15px; border-bottom-right-radius: 15px; }
<body> <div id="text">Домашна върху HTML5 API & Rounded Corners</div> <div id="buttons"> Местоположение: <input type="button" class="buttons" value="Вземи" onclick="getLocation()" /> <input type="button" class="buttons" value="Запази" onclick="saveLocation" /> <input type="button" class="buttons" value="Зареди" onclick="loadLocation" /> </div> <div id="map"></div> </body>
That code is not very good IMO since it only relies on jQuery instead of using the grid API. You can use the change event to detect row changes, get the selected rows with the select
methd and the data items with the dataItem
method.
So you can start with something like this:
$("#states").kendoGrid({ selectable: "multiple", dataSource: { data: usStates }, change: function() { var that = this; var html = ""; this.select().each(function() { var dataItem = that.dataItem(this); html += "<option>" + dataItem.name +"</option>"; }); $("#select").html(html); } });
(demo)
-20203250 0Presumably you want it to behave with the same fixity as >>=
, so if you load up GHCi and type
> :info (>>=) ... infixl 1 >>=
You could then define your operator as
infixl 1 |>= (|>=) :: Monad m => a -> (a -> m b) -> m b a |>= b = return a >>= b
But, if your monad preserves the monad laws, this is identical to just doing b a
, so there isn't really a need for the operator in the first place.
I'd also suggest using do notation:
naming path = do modTime <- getModificationTime path let str = formatTime defaultTimeLocale "%Y%m%d" modTime name = printf "%s_%s" (takeBaseName path) str replaceBaseName path name
-42174 0 netstat -b is a great answer, you may need to use the -a option as well.
Without -a netstat shows active connections, with -a it shows listening ports with no active clients as well.
-8031150 0 How can I pass messages to another thread without using a blocking queue?I have a pretty straight forward server (using kryonet). The clients are only storing the current state of the car (x,y,angle etc) and are sending requests of acceleration and turning.
The server is receiving the requests and adding them to a ArrayBlockingQueue that the physics thread drains and reads and updates.
When adding another player, the speed of the game slows down by almost double. I have ruled out a lot of things (I have all updates and package sending throttled at 60Hz.)
I am suspecting that using a blocking queue is blocking so much that it is causing the slowdown.
How can I send the client requests to the physics thread without blocking issues?
-26511427 0 PL/SQL procedure wont work. Help please?This is my procedure which compiles fine I am trying to get the release date and duration when i enter the films title:
create or replace PROCEDURE get_films (fname IN film.title%type, r_date OUT film.release_date%type, dur OUT film.f_duration%type) AS BEGIN SELECT release_date, f_duration into r_date, dur FROM FILM WHERE title = fname; EXCEPTION WHEN NO_DATA_FOUND THEN r_date:='';dur:=''; END get_films;
Its when I call it i get the errors:
set serveroutput on DECLARE ftit FILM.TITLE%type:=&Enter_Film_Title; frdate film.release_date%type; fdur film.f_duration%type; BEGIN GET_FILMS(ftit, frdat, fdur); DBMS_OUTPUT.PUT_LINE('Title Release_date F_Duration'); DBMS_OUTPUT.PUT_LINE(ftit||' '||frdate||' '||fdur); EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE(SQLCODE||SQLERRM); END;
errors:
old:EXECUTE GET_FILMS(&Enter_Title) new:EXECUTE GET_FILMS(Interstellar) Error starting at line : 17 in command - EXECUTE GET_FILMS(&Enter_Title) Error report - ORA-06550: line 1, column 17: PLS-00201: identifier 'INTERSTELLAR' must be declared ORA-06550: line 1, column 7: PL/SQL: Statement ignored 06550. 00000 - "line %s, column %s:\n%s" *Cause: Usually a PL/SQL compilation error. *Action:
-21984613 0 Top Navigation disappears with the scroll I would like to create a navigation menu with the top bar that disappears with the scroll. An example is this
As you can see in this theme, the menu continues to be high but the upper div disappears.
How could I do? Thanks in advance to all
PS: I'm using bootstrap 3
-21519313 0 RSS - displaying image, instead of enclosure?I have made a rss feed for my website, but right now the feed is not really displaying a image but just a link to the image as a enclosure. I would like to know what changes I need to make so I can actually display a image in the rss feed.
echo ' <item> <title>'.html_entity_decode($gag[story], ENT_COMPAT, "UTF-8").' - '.$thesitename.'</title> <description><![CDATA['.html_entity_decode($gag[story], ENT_COMPAT, "UTF-8").']]></description> <link>'.$thebaseurl.'/post/'.$gag[PID].'</link> <guid>'.$thebaseurl.'/post/'.$gag[PID].'/</guid>'; if($gag[pic] != ""){echo ' <enclosure type="image/jpeg" url="'.$thebaseurl.'/pdata/t/'.$gag[pic].'" length="1" />'; } echo '
-8360275 0 Calling AUGraphClose in the shutdown fixed this. Guess you can't have two open graphs with the same output unit in?
-10350373 0 luasoket http request got "connection refused"I am trying to use luasocket to make http "GET" request to "https://buy.itunes.apple.com/verifyReceipt" , it yields a "connection refused" , while I can access this URL from the the web browser either use python httplib. I doubted it is because the HTTPS protocal , but if i replace url with "https//www.google.com" , it works ok. so any1 has ideas on what the problem is ? much thx for ur answers
This is the code:
local http = require("socket.http") URL = "https://buy.itunes.apple.com/verifyReceipt" local response, httpCode, header = http.request(URL) print(response, httpCode, header)
-319480 0 Have a look at the patterns & practices Application Architecture Guide 2.0 (Beta 2 Release) on Codeplex. The patterns & practices division of Microsoft also has guidelines for naming etc.
-9926714 0Maven is a build/deploy tool. It is similar in use to cmake or ant. It can be plugged in eclipse via plugins, it can be used to deploy wars/jars to tomcat/jboss/websphere etc. It can run test suites and many more.
You should take a look at Maven In 5 Minutes.
http://maven.apache.org/guides/getting-started/maven-in-five-minutes.html
-16598287 0 JSON to NSDictionary literalI need to build an NSDictionary
that I can then parse with NSJSONSerialization
in order to get a nice JSON
formatted string.
The final output of my JSON needs to be something like:
"Viewport":{ "BottomRight":{ "Latitude":1.26743233E+15, "Longitude":1.26743233E+15 }, "TopLeft":{ "Latitude":1.26743233E+15, "Longitude":1.26743233E+15 } }
I figured it might be easiest to use NSDictionary
literals, but how would I create multi-level nested dictionaries doing it this way?
Also, I will need to be setting the lat and long values when creating the dictionary.
-20744549 0 webdriverjs: Expected string got an objectAfter discovering Mocha and webdriverjs, I wanted to give it a shot, after reading the readme.md
in https://github.com/camme/webdriverjs, so i began with a trivial test.
var webdriverjs = require("webdriverjs"), client = webdriverjs.remote(), expect = require("chai").expect; suite('Functional tests', function(done) { setup(function(done) { client.init().url('http://www.google.com', done); }); test('test if you can open a firefox page', function() { var inputType = client.getAttribute('#searchtext_home', 'type'); expect(inputType).to.be.a('string'); console.log(myString); }); teardown(function(done) { client.end(done); //done(); }); });
Get the input element of google and expect its type is text. I end up with an object in inputType
variable.
AssertionError: expected { Object (sessionId, desiredCapabilities, ...) } to be a string
-21219177 0 What does it mean that objc_msgSend() is passed "a pointer to the reciever's data"?In Apple's ObjC Runtime Guide, it describes what the objc_msgSend()
function does for dynamic dispatch:
- It first finds the procedure (method implementation) that the selector refers to. Since the same method can be implemented differently by separate classes, the precise procedure that it finds depends on the class of the receiver.
- It then calls the procedure, passing it the receiving object (a pointer to its data), along with any arguments that were specified for the method.
- Finally, it passes on the return value of the procedure as its own return value.
I was confused in the second step, where it mentioned "receiving object (a pointer to its data)
What is that?
Can somebody give me a illustration to clarify it?
-34836598 0you forgot to render the context
you need:
def index(request): template_name = "index/index.html" is_teamleader = request.user.groups.filter(name='TL').exists() is_employee = request.user.groups.filter(name='Employee').exists() context = { 'is_teamleader': is_teamleader, 'is_employee': is_employee } return render(request, template_name, context)
-31542736 0 You can add float: left
to your new element to give it the correct position, but don't forget to the a max-width
to your <ul>
so it doesn't push the other element out. Also I removed the margin
of the new element to make it fit within the black background.
#nav{ background-color: #222; } #nav_wrapper{ width: 960px; margin:0 auto; text-align: right; padding: 0; font-family: Arial; font-size: 18px; /* font: Batang; */ } @font-face { font: Batang; src: url('batang.tff'); } #nav_wrapper .current{ background-color: #333; } #nav ul{ list-style-type: none; padding: 0; margin: 0; max-width: 800px; } #nav ul li{ display: inline-block; } #nav ul li img{ vertical-align: middle; padding-left: 10px; } #nav ul li:hover{ background-color: #333; transition: all 0.4s; } #nav ul li a,visited{ color: #ccc; display: block; padding: 15px; text-decoration: none; } #nav ul li a:hover{ color; #ccc text-decoration: none; } #nav ul li:hover ul{ display: block; } #nav ul ul{ display: none; position: absolute; background-color: #333; border: 5px solid #222; border-top: 0; margin-left: -5px; min-width: 200px; text-align: left; } #nav ul ul li{ display: block; } #nav ul u li a,visited{ color; #ccc; } #nav ul ul li a:hover{ color: #099; transition: all 0.3s; } #nav_wrapper .logo{ position: relative; float: left; color: gold; font-size: 60px; font-family: Batang; margin: 0; }
<div id="nav_wrapper"> <div id="nav"> <p class="logo">IVERSEN</p> <ul> <li><a class="current" href="home.html">Hjem</a></li><li> <a href="#">Om</a></li><li> <a href="#">Kontakt</a></li><li> <a href="#">Projekter<img src="images\arrow.png"/></a> <ul> <li><a href="#">Batch</a></li> <li><a href="#">JavaScript</a></li> <li><a href="#">HTML/CSS</a></li> </ul> </div> </div>
I want to create a module (for example Users) in an advanced template application, that I could use it both in the backend (CRUD functionality) and frontend (login, profile)
Which is the right way of doing it, without having to create one module in backend and another in frontend and maybe a model in the common folder?
I want all files in one folder.
-11142187 0 How can I match the first unordered list from a string and select the first list items?I have a content string that starts with an unordered list I want to make a summary of this content on my homepage and I need to match the first unordered list and only show 5 list items in the preview, so I stated with matching the whole ul tag using this regex:
/<\s*ul[^>]*>(.*?)<\s*/\s*ul>/s
it works fine in regex tester online but I get Unknown modifier '\' and I don't know which one ? also after getting the whole unordered list how can I choose only the first 5 list items for example:
<ul class="mylist"> <li>Lorem Ipsum Dolor Sit Amet</li> <li>Lorem Ipsum Dolor Sit Amet</li> <li>Lorem Ipsum Dolor Sit Amet</li> <li>Lorem Ipsum Dolor Sit Amet</li> <li>Lorem Ipsum Dolor Sit Amet</li> <li>Lorem Ipsum Dolor Sit Amet</li> <li>Lorem Ipsum Dolor Sit Amet</li> <li>Lorem Ipsum Dolor Sit Amet</li> <li>Lorem Ipsum Dolor Sit Amet</li> <li>Lorem Ipsum Dolor Sit Amet</li> </ul>
and I want to create the same one with only the first 5 <li>
tags, so should I use regex or some other methods in php ?
and thanks in advance.
-12727231 0Your "myArray.length" is two. Thus the code passes through the inner "for" loop twice. The loop variable "row" is never used inside the inner "for". Thus the same thing is printed twice.
Take out the inner "for".
-15151275 0 How to send message to jboss-7 from jboss-5There are two applications.Earlier both the applications were running in jboss-5. Now one of them is going to get migrated to jboss7
Both the applications communicate with each other via JMS queues . From basic research I understand that we need to access the hornetq in jboss-7 by providing the URL the below way
private static final String PROVIDER_URL = "remote://localhost:4447";
Also i understand that in jboss-7 we need to access the queues with username and password ie, SECURITY_PRINCIPAL
But as far as I know these things cannot be achieved in jboss-5 . Please tell me, is there anyway I can send messages to the queue residing in jboss-7, from jboss-5 ??
-8051558 0There are several macros of this kind, but they are not directly available.
The page namespace templates describes how to set up namespace-level template files that automatically substitute some expressions (such as @USER@
or @DATE@
) when creating a new page in that directory. It should not be hard to adapt those to the format you desire.
Another choice would be adapt something from the var plugin so that the instructions it generates are converted and saved as text during a page preview or save. It would require converting the plugin from a "syntax" plugin to an "action" plugin.
-35329105 0 How to "select" multiple rows that have a certain variable value?I also want to be able to count/sum the number of these rows.
I can't seem to find this answer anywhere and it's so simple.
In Python it's something like:
df[df[value1]=="<value2>"].count()
How is this done in R
?
I am working on a dynamic tooltip...I'm stuck on how I can get the bottom position of #MyAuction-BidHistory
to appear just above my link a.my-auction-history
?
Here is my code so far:
var linkOffset = $('a.my-auction-history').offset().top; $('.my-auction-history').mouseover(function(e){ $.get('/auction/includes/new-bidhistory.asp?lplateid=' + pListedPlatesId + "&xx=" + t, function(data){ $('#MyAuction-BidHistory').css({'display':'block', 'opacity':'0', 'top':linkOffset }).animate({opacity:1}, 200).html(data); }); });
I only need to work out the Y co-ordinates as #MyAuction-BidHistory
has been position:absolute;
& has margin-left:300px;
Any help is greatly appreciated, Thanks
-25287926 0 Bootstrap NavBar stopped working <!doctype html> <html> <head> <title>Home Page</title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="main.css"/> <link rel="stylesheet" href="style.css"/> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <!-- Optional theme --> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> <header class ="navbar"> <div class="container navbar-inverse"> <nav role="navigation"> <div class="container-fluid"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">CASES4U</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav navbar-right"> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">iPhone <span class="caret"></span></a> <ul class="dropdown-menu" role="menu"> <li><a href="#">iPhone 3g/3gs</a></li> <li><a href="#">iPhone 4/4s</a></li> <li><a href="#">iPhone 5/5s</a></li> <li class="divider"></li> <li><a href="#">iPod</a></li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Samsung <span class="caret"></span></a> <ul class="dropdown-menu" role="menu"> <li><a href="#">Galaxy S 3</a></li> <li><a href="#">Galaxy S 4</a></li> <li><a href="#">Galaxy S 5</a></li> <li class="divider"></li> <li><a href="#">Galaxy Tab</a></li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">HTC <span class="caret"></span></a> <ul class="dropdown-menu" role="menu"> <li><a href="#">HTC Desire</a></li> <li><a href="#">HTC Desire HD</a></li> <li><a href="#">HTC One</a></li> <li class="divider"></li> <li><a href="#">HTC One M8</a></li> </ul> </li> </ul> </div><!-- /.navbar-collapse --> </div><!-- /.container-fluid --> </nav> </div> </header> </head> <body> <h1 class="cases-of-the-week"><center>Cases Of The Week</center></h1> <div class="container-row"> <div class="row"> <div class="col-sm-4 col-xs-12"> <div class="panel "> <div class="panel-heading"><center>iPhone Case</center></div> <div class="panel-body "> <div class="iPhone-Case-1"> <img src="iPhone-Case-Of-The-Week.png"width="260" height="290" /></div> <b><u><center>XTREME iPhone Case (iPhone 5/5s Case)</center></u></b> It may look like fluorescent armour, but that’s because it kinda is. The XTREME iPhone Case is packed with Reactive Protection Technology, made of XRD foam which stiffens on impact and absorbs 90% of the impact. There’s also a rigid outer polycarbonate shell and an inner shock-absorbing TPE insert, which combine to make this one of the safest havens for your iPhone 5s on the planet. </div> </div> </div> <div class="col-sm-4 col-xs-6"><div class="panel "> <div class="panel-heading"><center>Samsung Case</center></div> <div class="panel-body "> <div class="Samsung-Case-1"> <img src="Samsung-Case-Of-The-Week.png" width="260" height="290" /></div> <b><u><center>Spigen SGP Slim Armour Case (Samsung Galaxy S4 Case)</center></u></b> The Slim Armour case for the Samsung Galaxy S4 has been specifically designed and crafted to offer amazing protection despite being incredibly slim and beautiful in appearance. The TPU case features improved shock absorption on the top, bottom and corners to effectively protect the Galaxy against external impact. </div> </div></div> <div class="col-sm-4 col-xs-6"><div class="panel "> <div class="panel-heading"><center>HTC Case</center></div> <div class="panel-body "> <div class="HTC-Case-1"> <img src="HTC-Case-Of-The-Week.png"width="260" height="290" /></div> <b><u><center>Tough HTC One Case (HTC One Case)</center></u></b> You know the feeling. The heartbreak that immediately sets in as your phone smashes to the ground. Flashes of panic, pools of sweat and buckets of tears overwhelm your body. Protect yourself from future stress with the Tough case, providing dual layers of protection. Built to withstand sudden drops and accidental falls, the Tough case for the HTC One is the epitome of protection. </div> </div> </div> </div> <footer><center>CASES4U Inc</center></footer> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> </body> </html>
I recently started using bootstrap and it was going well. I was learning alot and i started using the navbar they have. I used it and it was going well i even made a quick phone case website everything was going well. Until i checked on my file and saw that my website had changed. I dont understand it was fine a day ago and i didnt touch anything. What website looks like now
-31736617 0I was looking for the a solution to the opposite problem where I needed a fixed width div in the centre and a fluid width div on either side so I came up with the following and thought I'd post it here in case anyone needs it.
HTML:
<div id="wrapper"> <div id="center"> This is fixed width in the centre </div> <div id="left" class="fluid"> This is fluid width on the left </div> <div id="right" class="fluid"> This is fluid width on the right </div> </div>
CSS:
#wrapper { clear: both; width: 100%; } #wrapper div { display: inline-block; height: 500px; } #center { background-color: green; margin: 0 auto; overflow: auto; width: 500px; } #left { float: left; } #right { float: right; } .fluid { background-color: yellow; width: calc(50% - 250px); }
If changing the width of the #center
element then you need to update the width property of .fluid
to:
width: calc(50% - [half of center width]px);
-101915 0 For those working with Windows API, there's a function which allows you to see if any debugger is present using:
if( IsDebuggerPresent() ) { ... }
Reference: http://msdn.microsoft.com/en-us/library/ms680345.aspx
-38614598 0 Please try below code once SELECT FORMAT(275, 'C', 'en-us') Output: $275.00 SELECT FORMAT(275, 'C0', 'en-us') Output: $275
Your fiddle illuminates the actual issue:
content = "<input type='button' value='Add' onclick='addme(\"" + addedTitle + "\")' />" document.getElementById("display").innerHTML = content;
The problem is that the above code will generate the following:
<input type='button' value='Add' onclick='addme("some'string")' />
You'll notice this has a single quote inside of your onclick
which is single quoted. This is what is breaking. You can escape the single quote with \
.
However, a better approach would be to get rid of the inline onclick
and do it this way:
var input = $("<input type='button' value='Add'/>").click(function(){ addme(addedTitle); }); $("#display").append(input);
http://jsfiddle.net/bxxmhe03/6/
-119264 0I use the http://webthumb.bluga.net service for thumbnail generation. Robust, powerful, easy to use, and very reasonable rates. I have a high traffic production website using this service and it works very well. Given the difficulty of creating a robust web screenshot service, it's nice to have someone else do the hard work.
-19386682 0 Count re-Occurrence of a string - VB.NETWhat method is best to count the following, Each line is a string created by a loop.
Jane Jane Matt Matt Matt Matt Jane Paul
In the end i would like to know : Jane = 3, Matt = 4, Paul = 1. Would i use an array or a loop ?
-9713623 0It looks like you want to create an intent and then start an activity with it. You can use the context from "collection" which you are already accessing. Here's some code which should get you going again:
public void onClick(View v) { Context context = collection.getContext(); Intent intent = new Intent(context, DashboardActivity.class); context.startActivity(intent); }
Note that you'll probably have to make collection become final.
-1411472 0Correct - the positive lookbehinds will not work.
But, just as some general information about regex in Javascript, here's a couple pointers for you.
You don't have to use the RegExp object - you can use pattern literals instead
var regex = /^[a-z\d]+$/i;
But if you use the RegExp object, you have to escape your backslashes since your pattern is now locked in a string.
var regex = new RegExp( '^[a-z\\d]+$', 'i' );
The primary benefit of the RegExp object is if there is a dynamic bit to your pattern, for example
var max = 4; var regex = new RegExp( '\d{1,' + max + '}' );
-5419977 0 I think it's simply a bug in how the javah
outputs its actual classpath. What happens is that it has a bunch of places where it searches for built-in classes, and apart from them, it also uses the stuff in $CLASSPATH
. When it prints the actual classpath used, they do something like this (pseudo code, assuming implicitEntries
is a list of builtin classpath entries, and explicitEntries
is a list of the the directories specified in $CLASSPATH
):
print implicitEntries.join(pathSeparator) + explicitEntries.join(pathSeparator)
where it should have been
print implicitEntries.join(pathSeparator) + pathSeparator + explicitEntries.join(pathSeparator)
The following works fine for me:
$ ls Sasl.class Sasl.java $ javah -classpath . -o javasasl.h -jni -verbose Sasl [ Search Path: /usr/java/jdk1.6.0/jre/lib/resources.jar:/usr/java/jdk1.6.0/jre/lib/rt.jar:/usr/java/jdk1.6.0/jre/lib/sunrsasign.jar:/usr/java/jdk1.6.0/jre/lib/jsse.jar:/usr/java/jdk1.6.0/jre/lib/jce.jar:/usr/java/jdk1.6.0/jre/lib/charsets.jar:/usr/java/jdk1.6.0/jre/classes/. ] [Creating file javasasl.h] [search path for source files: [.]] [search path for class files: [/usr/java/jdk1.6.0/jre/lib/resources.jar, /usr/java/jdk1.6.0/jre/lib/rt.jar, /usr/java/jdk1.6.0/jre/lib/sunrsasign.jar, /usr/java/jdk1.6.0/jre/lib/jsse.jar, /usr/java/jdk1.6.0/jre/lib/jce.jar, /usr/java/jdk1.6.0/jre/lib/charsets.jar, /usr/java/jdk1.6.0/jre/classes, /usr/java/jdk1.6.0/jre/lib/ext/dnsns.jar, /usr/java/jdk1.6.0/jre/lib/ext/localedata.jar, /usr/java/jdk1.6.0/jre/lib/ext/sunpkcs11.jar, /usr/java/jdk1.6.0/jre/lib/ext/sunjce_provider.jar, .]] [loading ./Sasl.class] [loading /usr/java/jdk1.6.0/lib/ct.sym(META-INF/sym/rt.jar/java/lang/Object.class)] [loading /usr/java/jdk1.6.0/lib/ct.sym(META-INF/sym/rt.jar/java/lang/Throwable.class)] [loading /usr/java/jdk1.6.0/lib/ct.sym(META-INF/sym/rt.jar/java/lang/Class.class)] [done in 585 ms] $ ls javasasl.h Sasl.class Sasl.java
Now, since the header file generation doesn't seem to work for you... are you sure you have Sasl.class
in the current directory? javah
works with byte code files, not Java source files.
Does anybody see any drawbacks? It should be noted that you can't remove anonymous methods from an event delegate list, I'm aware of that (actually that was the conceptual motivation for this).
The goal here is an alternative to:
if (onFoo != null) onFoo.Invoke(this, null);
And the code:
public delegate void FooDelegate(object sender, EventArgs e); public class EventTest { public EventTest() { onFoo += (p,q) => { }; } public FireFoo() { onFoo.Invoke(this, null); } public event FooDelegate onFoo;
}
-40197537 0Since you are on UNIX, you can use jot
with arguments from bash integer expansion:
jot -r 1 $((10 ** 15)) $((((10 ** 15)) * 2))
Generates numbers like:
1595866171875968
-38822670 0 You are using incorrect syntax for batchWrite, try following
$response = $dynamoDb->batchWriteItem([ 'RequestItems' => [ 'mytable' => [ [ 'PutRequest' => [ 'Item' => [ 'id' => array('S' => '123abc'), 'value' => array('N' => '1'), ] ], 'PutRequest' => [ ///Entire PutRequest array need to be repeated not just item array/// 'Item' => [ 'id' => array('S' => '123abc'), 'value' => array('N' => '2'), ] ], ], ], ], ]);
Apart from that, the difference between single insert and multiple inserts would be the call to connect with DynamoDB, in batchPut you will send entire array at once whereas in single insert it will connect to DB each time it tries to perform any operation.
In general, you can use Batch to process things faster.
Here is the refernce link for batchWrite syntax
Hope that helps.
-41069712 0If you don't like map you can always use a list comprehension:
s = [str(i) for i in x] r = int("".join(s))
-4749296 0 Best way to allow admin to build objects for Admin My objective is to allow Admins the right to sign Users up for a Project.
Currently, Users can sign themselves up for Projects.
So I was thinking in order to allow Admin to do this.. do something like this :
haml
= link_to "Project Signup", card_signups_path + "?user=#{user.id}", :class => "button"
And pass the params[:user] so I can replace this controller with this :
if params[:user] @card_signup = User.find(params[:user]).build_card_signup else @card_signup = current_user.build_card_signup end
The trouble is though.. this is a 3 part signup process, and its loaded VIA AJAX, so I can't pass the ?user=#{user.id}
in any of the steps after the first.. ( at least not by the same convention that I already did, or know how to )
What kind of strategy would you employ in this?
-13898280 0Well to answer my own question, Pear:Cache-Lite does the trick.
-1532938 0I find that typically a repeated CTE gets no performance improvements.
So for instance, if you use a CTE to populate a table and then the same CTE to join to in a later query, no benefit. Unfortunately, CTEs are not snapshots and they literally have to be repeated to be used in two separate statements, so they tend to be evaluated twice.
Instead of CTEs, I often use inline TVFs (which may contain CTEs), which allows proper re-use, and are not any better or worse than CTEs in my SPs.
In addition, I also find that the execution plan can be bad if the first step alters the statistics such that the execution plan for the second step is always inaccurate because it is evaluated before any steps are run.
In this case, I look at manually storing intermediate results, ensuring that they are indexed properly and splitting up the process into multiple SPs and adding WITH RECOMPILE to ensure that later SPs have plans that are good for the data which they are actually going to operate on.
-38004638 0 Notify the Service if the Activity is DownSometimes my app crashes for some reason and I have no control over it. I want to let the service know when the app crashes and do some other process.
Is it possible to do that?
By the way, starting from Lollipop, getRunningTasks
is deprecated.
Thanks.
-30308488 0Upgrade you Calabash-Android version to the latest one. 0.4.20 is a very old release and does not support crosswalk webviews.
-11508938 0how can I make sure that all of the async code in my initializer(s) is complete before doing anything else in the application?
Don't use the initialize:after
event. Instead, trigger your own event from the success
call, and then bind your app start up code from that one.
MyApp.addInitializer(function (options) { $.ajax({ url: options.apiUrl + '/my-app-api-module', type: 'GET', contentType: 'application/json; charset=utf-8', success: function (results) { MyApp.Resources.urls = results; // trigger custom event here MyApp.vent.trigger("some:event:to:say:it:is:done") } }); }); // bind to your event here, instead of initialize:after MyApp.vent.bind('some:event:to:say:it:is:done', function (options) { // initialization is done...close the modal dialog if (options.initMessageId) { $.noty.close(options.initMessageId); } if (Backbone.history) { Backbone.history.start(); } console.log(MyApp.Resources.urls); });
This way you are triggering an event after your async stuff has finished, meaning the code in the handler will not run until after the initial async call has returned and things are set up.
-15397551 0Is there a way to automatically notify the developers of all the super-projects to update the submodule
No.
A submodule is a clone of an upstream repo, nested in a parent repo.
It is a downstream repo compared to the original repo you cloned as a submodule.
And in a distributed environment, you simply don't know of the downstream repos.
You only know of the upstream repo.
See "Definition of “downstream” and “upstream”".
As mentioned in "Update git submodule", you would need to go in the submodule and git pull
directly in there in order to update said submodule.
The symbol '>>' is an operator. The writer of the String class included this operator to only take primitive types and of course the String class type.
You have two options:
Look up overloading operator if you really want to have fun.
-12322904 0 Liferay: get PortletID and companyID from init()Maybe trough PortletConfig in init(PortletConfig)
The thing is that using
((PortletConfigImpl) portletConfig).getPortletId();
is not allowed anymore because adding portal-impl.jar in package.properties gives throws an exception when trying to execute build ant target, saying that this is not allowed anymore
For companyID I directly have no idea where to start. I am using currently
long companyId = CompanyLocalServiceUtil.getCompanies().get(0).getCompanyId();
but as soon as I got more than one company it will fail
If only I could get Portlet object somehow, I think it would be enough to get both portletId and companyId
-7235783 0I broke it down a bit for clarity, but this should do the trick.
$("#checkbox_1").click(function() { var checked = $("#checkbox_1").attr("checked"); var selectVal; if (checked) selectVal = 1; else selectVal = "All"; $("#dropdown").val(selectVal); });
-31163347 0 Remove MainActivity
just use startActivity(i)
This is the code i am using to extract data in my controller which i am using it in my chartjs:
$startdate = request('startdate') ?: \Carbon\Carbon::now()->startOfYear(); $enddate = request('enddate') ?: \Carbon\Carbon::now(); return complaintRegistrationModel::with('complaintmoderelation') ->select(DB::raw(DB::raw('count(*) as complaints')), DB::raw('modeID')) ->whereBetween('updated_at', array($startdate, $enddate)) ->groupBy('modeID') ->pluck('modeID', 'complaints');
As you can see, I am using foreign key modeID
from table tblcomplaintregistration
...what i want to do is i want to get the modeName
associated with the modeID
which is stored in another table call tblmode
. So my chart should give modeName
in my x-axis instead of modeID
. Please help me out. Thank you
UPDATE
ok i was able to solve it by making some changes in the query like this. Hope some might find it useful.
return \App\complaintRegistrationModel::select(\Illuminate\Support\Facades\DB::raw(DB::raw('count(*) as complaints')), \Illuminate\Support\Facades\DB::raw('(select modeName from cr_pltblcomplaintmode where complaintmodeID = modeID) as modeName')) ->whereBetween('updated_at', array($startdate, $enddate)) ->groupBy('modeName') ->pluck('complaints', 'modeName');
-32735559 0 Ok, I see you need it's recursive.
public static String repeater(int x, String word) { if (x == 0) { return ""; } else { return word.charAt(0) + repeater(x - 1, word); } }
How is this?
For understanding this recursion, it is working like nested parentheses of Mathematics.
"H" + ("H" + ("H" + ("H" + ("H" + ("H" + (""))))))
-967264 0 Conditional Routing? I have a simple partial view. The main part of which is listed below. How can I have the ActionLinks resolve properly when this partial view is rendered on a page that is managed by a different controller. In other words - this partial view shows Project Areas for a given Project. What if this PV shows up on a page being managed by the Project Controller. The Default route behavior here would try to have the code execute the /Project/Edit or Project/Detail . Thats not really what I need. Instead I need it to go to /ProjectArea/Edit for example. How is that accomplished in this case?
<% foreach (var item in Model) { %> <tr> <td> <%= Html.ActionLink("Edit", "Edit", new { id=item.ProjectAreaId }) %> | <%= Html.ActionLink("Details", "Details", new {id=item.ProjectAreaId })%> </td> <td> <%= Html.Encode(item.Name) %> </td> </tr> <% } %>
-6899758 0 A crude approach (while guessing what you're trying to do):
#!/usr/bin/env python import pprint revisions = [ ['01.02.2010','abc','qwe'], ['02.02.2010','abc','qwe'], ['03.02.2010','aaa','qwe'], ['04.02.2010','aaa','qwe'], ['05.02.2010','aaa','qwe'], ['06.02.2010','aaa','dsa'], ] uniq, seen = [], set() # sets have O(1) membership tests for rev in revisions: if tuple(rev[1:]) in seen: continue else: seen.add(tuple(rev[1:])) uniq.append(rev) pprint.pprint(uniq) # prints: # [['01.02.2010', 'abc', 'qwe'], # ['03.02.2010', 'aaa', 'qwe'], # ['06.02.2010', 'aaa', 'dsa']]
-1067568 0 Determine reason of System.AccessViolationException We are having nondeterministic System.AccessViolationException thrown from native code. It's hard to reproduce it, but sometimes it happens. I'm not sure if I can "just debug it" since the time needed for access violation is about 2 hours and there is no guarantees that access violation will happen.
The native library is used by managed wrappers. It's used from java through JNI and it's used from .NET through IKVM'ed JNI. The problem was only reproduced during from IKVM'ed code, but the data sets is different and there is no way to test java application with data used by IKVM'ed application.
I have sources for everything, but (if possible) I want to avoid making large number of changes.
I believe native call stack will provide enough information about reason of this access violation.
Is there any effective ways of determining the reason of this access violation?
I think the ideal solution for me is some changes in code or process environment, so it will crash with memory dump in case of this access violation, so I can make that changes and just wait.
-20520937 0if you know how to do it for one data.frame
then just use lapply
on your list of dats.frames
e.g.
#create your new columns function as it would work for one data.frame foo <- function(DF){ DF$new1 <- distm(x,y)....etc DF$new2 <- .......etc DF$new3 <- cor(x,y).......etc return(DF) }
Then lapply over the list to return a list of data.frames
with the new columns:
DFlist <- list(DF1, DF2, DF3) lapply(DFlist, foo)
-17298862 0 JSP debugging in IntelliJ IDEA using the Tomcat Maven Plugin We used to have Tomcat
run configuration in IntelliJ. This deployed our webapp to a locally installed tomcat instance, and let us debug both java classes and jsp files.
Now we've made the switch to Maven, and we now run our Tomcat instance using the tomcat7 maven plugin with the maven goal: tomcat7:run-war
Debugging our java classes works perfectly, however (due to large amounts of legacy code) we also need to be able to debug JSP files.
Is it possible to debug JSPs in IntelliJ when an embedded Tomcat is launched from the maven plugin?
-21266638 0LocalStorage (in Chrome) is in the %LocalAppData%
directory, which is under the user's account. Internet Explorer stores them under %userprofile%
Precise location varies among browsers but is always within a user folder.
So no, LocalStorage will not propagate across users.
-33053508 0The reason beyond that is that the bytecode (.class files) used by your Eclipse debugger doesn't contain any information about method parameters name. That's the way the JDK is compiled by default.
The Eclipse debugger implements a workaround for method parameters, naming them "arg0", "arg1", etc. and thus enabling you to inspect them in the "Variables" view. Unfortunately, I don't think there is such a workaround for local method variables...
Some other tickets in StackOverflow advise to rebuild yourself the JRE based on source code of the JDK, e.g.: debugging not able to inspect the variables.
-36720519 0Maybe another solution would be:
#include <iostream> using namespace std; int colonne; int ligne; void initDamier (int **damier, int ligne, int colonne) { for (int i = 0; i < ligne; ++i){ for (int j = 0; j < colonne; ++j){ damier[i][j]=0; //0=case vide } } }
-
void afficheDamier (int **damier, int ligne, int colonne) { for (int i = 0; i < ligne; ++i) { cout<<endl; for (int j = 0; j < colonne; ++j) { cout<<damier[i][j]<<"|"; } } cout<<endl; }
-
int main() { int a,b; cout<<"Entrez le nombre de ligne du damier:"<<endl; cin>>a; ligne=a; cout<<"Entrez le nombre de colonne du damier:"<<endl; cin>>b; colonne=b; int** damier = new int*[colonne]; for(int i=0;i<colonne;i++) damier[i] = new int[ligne]; initDamier(damier,ligne, colonne); afficheDamier(damier, ligne, colonne); for(int i=0;i<colonne;i++) delete damier[i]; delete[] damier; return 0; }
-11930250 0 The other answers are technically correct on the compiler error, but miss a subtle point: fun
is used incorrectly. It appears to be intended as a local variable that collects results in fun.pairs
. However, std::for_each
can copy fun
instead, and then fun.pairs
is not updated.
Correct solution: Fun fun = std::for_each(Packs, Packs + SHARE_PRIZE, Fun());
.
I have a registration application which has the "KeyChar" event inside it, and it works great ! but when i give the same lines of code in this application it gives me Operator '=='/'!=' cannot be applied to operands of type 'char' and 'string'
Can't seem to figure out why it works in the other application but not here! Any help is much appreciated !
private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { SqlConnection DBConnection = new SqlConnection("Data Source=DATABASE;Initial Catalog=imis;Integrated Security=True"); SqlCommand cmd = new SqlCommand(); Object returnValue; string txtend = textBox1.Text; //string lastChar = txtend.Substring(txtend.Length - 1); if (e.KeyChar == "L") { DBConnection.Open(); } if (DBConnection.State == ConnectionState.Open) { if (textBox1.Text.Length != 7) return; { //cmd.CommandText = ("SELECT last_name +', '+ first_name +'\t ('+major_key+')\t' from name where id =@Name"); cmd.CommandText = ("SELECT last_name +', '+ first_name from name where id =@Name"); cmd.Parameters.Add(new SqlParameter("Name", textBox1.Text.Replace(@"L", ""))); cmd.CommandType = CommandType.Text; cmd.Connection = DBConnection; // sqlConnection1.Open(); returnValue = cmd.ExecuteScalar() + "\t (" + textBox1.Text.Replace(@"L", "") + ")"; DBConnection.Close(); if (listBox1.Items.Contains(returnValue)) { for (int n = listBox1.Items.Count - 1; n >= 0; --n) { string removelistitem = returnValue.ToString(); if (listBox1.Items[n].ToString().Contains(removelistitem)) { listBox1.Items.RemoveAt(n); //listBox1.Items.Add(removelistitem+" " +TimeOut+ Time); } } } else listBox1.Items.Add(returnValue); System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(fullFileName); foreach (object item in listBox1.Items) SaveFile.WriteLine(item.ToString()); SaveFile.Flush(); SaveFile.Close(); textBox1.Clear(); if (listBox1.Items.Count != 0) { DisableCloseButton(); } else { EnableCloseButton(); } Current_Attendance_Label.Text = "Currently " + listBox1.Items.Count.ToString() + " in attendance."; e.Handled = true; } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// else ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// { returnValue = textBox1.Text.Replace(@"*", ""); if (e.KeyChar == "*") return; { if (listBox1.Items.Contains(returnValue)) { for (int n = listBox1.Items.Count - 1; n >= 0; --n) { string removelistitem = returnValue.ToString(); if (listBox1.Items[n].ToString().Contains(removelistitem)) { //listBox1.Items.RemoveAt(n); } } } else listBox1.Items.Add(returnValue); textBox1.Clear(); System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(fullFileName); foreach (object item in listBox1.Items) SaveFile.WriteLine(item.ToString()); SaveFile.Flush(); SaveFile.Close(); if (listBox1.Items.Count != 0) { DisableCloseButton(); } else { EnableCloseButton(); } Current_Attendance_Label.Text = "Currently " + listBox1.Items.Count.ToString() + " in attendance."; e.Handled = true; } } }
-39123566 0 Something like this.
select name,math as Grade from your_table union all select name,English as Grade from your_table union all select name,Arts as Grade from your_table
-26590298 0 Is this what you are looking for
var json = {"userid":"12345","cmpyname":"stackoverflow", "starrays": [{"transaction":"7272785","value2":"GOOGLE"}, //Array [0] {"transaction":"85785272","value2":"YAHOO"}, //Array [1] {"transaction":"4774585","value2":"REDIFF"}], //Array [2] "value3":"95345"} if(json["starrays"].length > 0 && (json["starrays"][0].transaction != undefined && json["starrays"][0].value2 != undefined)) { $('#outer').show(); $('#val').html(json["starrays"][0].value2); $('#amt').html(json["starrays"][0].transaction); }
-893757 0 Exporting X.509 certificate WITHOUT private key (.NET C#) I thought this would be straightforward but apparently it isn't. I have a certificate installed that has a private key, exportable, and I want to programmatically export it with the public key ONLY. In other words, I want a result equivalent to selecting "Do not export the private key" when exporting through certmgr and exporting to .CER.
It seems that all of the X509Certificate2.Export methods will export the private key if it exists, as PKCS #12, which is the opposite of what I want.
Is there any way using C# to accomplish this, or do I need to start digging into CAPICOM?
Thanks,
Aaron
-27471858 0You could set the properties in the controller instead of using the script tag
You´ll have to add a custom button
<button type="submit" ng-click="pay()" class="stripe-button-el" style="visibility: visible;"><span style="display: block; min-height: 30px;">Pay with Card</span></button>
And in the controller:
var handler = StripeCheckout.configure({ image: "https://stripe.com/img/documentation/checkout/marketplace.png", key:'pk_test_' }); $scope.pay = function(){ handler.open({ name: 'Example Product', description: 'Example Product ' + $scope.price, amount: $scope.price * 100 }); e.preventDefault(); };
This work as expected:
http://jsfiddle.net/ppq1orso/3/
-4427655 0 Keyword BOGUS in phpI'm wondering what the word "BOGUS" means in the following object.
I'm running a script on the command line, sending a object back over SOAP. I expect back:
object(stdClass)#2 (2) { ["distance"]=> string(5) "13726" ["time"]=> string(3) "622" }
But the first time I ran it, I got this back:
object(stdClass)#2 (2) { ["distance"]=> object(stdClass)#3 (1) { ["BOGUS"]=> string(5) "13726" } ["time"]=> object(stdClass)#4 (1) { ["BOGUS"]=> string(3) "622" } }
This only happened once, I can't duplicate it. But I'm intrigued and wondering if anyone knows what it means. Thanks.
-19591622 0Already a descusion carried about this please check the link. Delete a particular local notification
-28537454 0I found a solution by thinking a bit different.
This is eventually the function:
public function getPriceLines($pricelinematerial = 0, $year = 0, $week = 0) { if ($year === 0) { $year = (int)date('Y'); } if ($week === 0) { $week = (int)date('W'); } $query = $this->getEntityManager()->createQuery(' SELECT pgp FROM ACME\Bundle\PricelistBundle\Entity\PricelistMaterialPrice pgp WHERE pgp.pricelistmaterial = :pricelistmaterial AND pgp.year <= :year AND pgp.week <= :week ORDER BY pgp.year DESC, pgp.week DESC, pgp.id DESC ')->setParameters(array('pricelistmaterial' => $pricelistmaterial, 'week' => $week, 'year' => $year)); $query->setMaxResults(1); try { $result = $query->getSingleResult(); } catch (\Doctrine\ORM\NoResultException $e) { $result = null; } return $result; }
-21056210 0 Apple already did that: The CLLocationManager property desiredAccuracy with value kCLLocationAccuracyBestForNavigation will "Use the highest possible accuracy and combine it with additional sensor data. This level of accuracy is intended for use in navigation applications that require precise position information at all times and are intended to be used only while the device is plugged in."
-18446332 0 how to play two mp4 videos through gstreamer pipeline?I would like to create a gstreamer pipeline to play two mp4 videos back to back. is it possible to play using gst-launch? can I use multifilesrc for this purpose ?
Please show me path to play two videos back to back.
Thanks in advance !
-22338852 0The reason this is showing in the action menu is because you have android:showAsAction="ifRoom"
in your xml file. remove that and you should be good.
You know how to get the RTB.Text vs RTB.Rtf right?
Here is some documentation you might enjoy (or not).
Once you know the difference between those, you get the text, use that to build the rtf string, and then assign that string into the Rtf.
To modify the colors in your rtf string, you should check the documentation on how to format text with rtf. Here is the first google result I found.
Good Luck.
-2117755 0ResolveUrl("~/Resources/R1.png")
Where '~' is used to represent the root of the application in which the current page/control sits.
Or if the resource is external to the current application but is still found within the virtual directory hierarchy, you can use ResolveUrl("/Resources/R1.png")
-35599024 0 Varnish 4.0.1, Apache, Centos 7, Plesk 12, Wordpress with w3 total cache - Varnish not caching htmlI set up varnish on my site the other day and I don't believe it is working correctly as the age shows as 0:
The url we checked: pbsgroups.deep-image.co.uk HTTP/1.1 200 OK Date: Wed, 24 Feb 2016 09:57:14 GMT Server: Apache Link: <http://pbsgroups.deep-image.co.uk/wp-json/>; rel="https://api.w.org/", <http://pbsgroups.deep-image.co.uk/>; rel=shortlink Expires: Wed, 24 Feb 2016 10:57:15 GMT Pragma: public Cache-Control: max-age=3600, public X-Powered-By: PleskLin X-Pingback: http://pbsgroups.deep-image.co.uk/xmlrpc.php Vary: Accept-Encoding Set-Cookie: iSLuxE=1; expires=Wed, 24-Feb-2016 12:57:14 GMT; Max-Age=10800 Last-Modified: Wed, 24 Feb 2016 09:57:15 GMT Etag: 33984224b175af821c75fc660dbd42a8 X-Mod-Pagespeed: 1.10.33.5-0 Content-Encoding: gzip Content-Length: 7851 Content-Type: text/html; charset=UTF-8 X-Varnish: 655877 Age: 0 Via: 1.1 varnish-v4 Connection: keep-alive
Static content works perectly:
The url we checked: pbsgroups.deep-image.co.uk/wp-includes/css/dashicons.min.css?ver=4.4.2 HTTP/1.1 200 OK Date: Wed, 24 Feb 2016 09:34:34 GMT Server: Apache Content-Length: 28526 Last-Modified: Thu, 18 Feb 2016 11:04:30 GMT ETag: "b438-52c0954a5d637-gzip" Vary: Accept-Encoding,User-Agent Cache-Control: max-age=31536000, public Expires: Thu, 23 Feb 2017 09:08:56 GMT X-Powered-By: W3 Total Cache/0.9.4.1 Pragma: public X-Original-Content-Length: 46136 Content-Encoding: gzip X-Content-Type-Options: nosniff Content-Type: text/css X-Varnish: 361406 820497 Age: 21 Via: 1.1 varnish-v4 Connection: keep-alive
This is what isvarnishworking.com has got to say on this:
Varnish appears to be responding at that url, but the Cache-Control header's "max-age" value is less than 1, which means that Varnish will never serve content from cache at this url.
Here is a copy of my .htaccess (made with w3 total cache):
## EXPIRES CACHING ## ExpiresActive On ExpiresByType image/jpg "access 1 year" ExpiresByType image/jpeg "access 1 year" ExpiresByType image/gif "access 1 year" ExpiresByType image/png "access 1 year" ExpiresByType application/pdf "access 1 month" ExpiresByType application/x-shockwave-flash "access 1 month" ExpiresByType image/x-icon "access 1 year" ExpiresDefault "access 2 days" ## EXPIRES CACHING ## # BEGIN W3TC CDN <FilesMatch "\. (asf|asx|wax|wmv|wmx|avi|bmp|class|divx|doc|docx|eot|exe|gif|gz|gzip|ico|jpg|jpeg|jpe|json|mdb|mid|midi|mov|qt|mp3|m4a|mp4|m4v|mpeg|mpg|mpe|mpp|otf|odb|odc|odf|odg|odp|ods|odt|ogg|pdf|png|pot|pps|ppt|pptx|ra|ram|svg|svgz|swf|tar|tif|tiff|ttf|ttc|wav|wma|wri|woff|xla|xls|xlsx|xlt|xlw|zip|ASF|ASX|WAX|WMV|WMX|AVI|BMP|CLASS|DIVX|DOC|DOCX|EOT|EXE|GIF|GZ|GZIP|ICO|JPG|JPEG|JPE|JSON|MDB|MID|MIDI|MOV|QT|MP3|M4A|MP4|M4V|MPEG|MPG|MPE|MPP|OTF|ODB|ODC|ODF|ODG|ODP|ODS|ODT|OGG|PDF|PNG|POT|PPS|PPT|PPTX|RA|RAM|SVG|SVGZ|SWF|TAR|TIF|TIFF|TTF|TTC|WAV|WMA|WRI|WOFF|XLA|XLS|XLSX|XLT|XLW|ZIP)$"> <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{HTTPS} !=on RewriteRule .* - [E=CANONICAL:http://pbsgroups.deep-image.co.uk {REQUEST_URI},NE] RewriteCond %{HTTPS} =on RewriteRule .* - [E=CANONICAL:https://pbsgroups.deep-image.co.uk%{REQUEST_URI},NE] </IfModule> <IfModule mod_headers.c> Header set Link "<%{CANONICAL}e>; rel=\"canonical\"" </IfModule> </FilesMatch> <FilesMatch "\.(ttf|ttc|otf|eot|woff|font.css)$"> <IfModule mod_headers.c> Header set Access-Control-Allow-Origin "*" </IfModule> </FilesMatch> # END W3TC CDN # BEGIN W3TC Browser Cache <IfModule mod_mime.c> AddType text/css .css AddType text/x-component .htc AddType application/x-javascript .js AddType application/javascript .js2 AddType text/javascript .js3 AddType text/x-js .js4 AddType text/html .html .htm AddType text/richtext .rtf .rtx AddType image/svg+xml .svg .svgz AddType text/plain .txt AddType text/xsd .xsd AddType text/xsl .xsl AddType text/xml .xml AddType video/asf .asf .asx .wax .wmv .wmx AddType video/avi .avi AddType image/bmp .bmp AddType application/java .class AddType video/divx .divx AddType application/msword .doc .docx AddType application/vnd.ms-fontobject .eot AddType application/x-msdownload .exe AddType image/gif .gif AddType application/x-gzip .gz .gzip AddType image/x-icon .ico AddType image/jpeg .jpg .jpeg .jpe AddType application/json .json AddType application/vnd.ms-access .mdb AddType audio/midi .mid .midi AddType video/quicktime .mov .qt AddType audio/mpeg .mp3 .m4a AddType video/mp4 .mp4 .m4v AddType video/mpeg .mpeg .mpg .mpe AddType application/vnd.ms-project .mpp AddType application/x-font-otf .otf AddType application/vnd.ms-opentype .otf AddType application/vnd.oasis.opendocument.database .odb AddType application/vnd.oasis.opendocument.chart .odc AddType application/vnd.oasis.opendocument.formula .odf AddType application/vnd.oasis.opendocument.graphics .odg AddType application/vnd.oasis.opendocument.presentation .odp AddType application/vnd.oasis.opendocument.spreadsheet .ods AddType application/vnd.oasis.opendocument.text .odt AddType audio/ogg .ogg AddType application/pdf .pdf AddType image/png .png AddType application/vnd.ms-powerpoint .pot .pps .ppt .pptx AddType audio/x-realaudio .ra .ram AddType application/x-shockwave-flash .swf AddType application/x-tar .tar AddType image/tiff .tif .tiff AddType application/x-font-ttf .ttf .ttc AddType application/vnd.ms-opentype .ttf .ttc AddType audio/wav .wav AddType audio/wma .wma AddType application/vnd.ms-write .wri AddType application/font-woff .woff AddType application/vnd.ms-excel .xla .xls .xlsx .xlt .xlw AddType application/zip .zip </IfModule> <IfModule mod_expires.c> ExpiresActive On ExpiresByType text/css A31536000 ExpiresByType text/x-component A31536000 ExpiresByType application/x-javascript A31536000 ExpiresByType application/javascript A31536000 ExpiresByType text/javascript A31536000 ExpiresByType text/x-js A31536000 ExpiresByType text/html A3600 ExpiresByType text/richtext A3600 ExpiresByType image/svg+xml A3600 ExpiresByType text/plain A3600 ExpiresByType text/xsd A3600 ExpiresByType text/xsl A3600 ExpiresByType text/xml A3600 ExpiresByType video/asf A31536000 ExpiresByType video/avi A31536000 ExpiresByType image/bmp A31536000 ExpiresByType application/java A31536000 ExpiresByType video/divx A31536000 ExpiresByType application/msword A31536000 ExpiresByType application/vnd.ms-fontobject A31536000 ExpiresByType application/x-msdownload A31536000 ExpiresByType image/gif A31536000 ExpiresByType application/x-gzip A31536000 ExpiresByType image/x-icon A31536000 ExpiresByType image/jpeg A31536000 ExpiresByType application/json A31536000 ExpiresByType application/vnd.ms-access A31536000 ExpiresByType audio/midi A31536000 ExpiresByType video/quicktime A31536000 ExpiresByType audio/mpeg A31536000 ExpiresByType video/mp4 A31536000 ExpiresByType video/mpeg A31536000 ExpiresByType application/vnd.ms-project A31536000 ExpiresByType application/x-font-otf A31536000 ExpiresByType application/vnd.ms-opentype A31536000 ExpiresByType application/vnd.oasis.opendocument.database A31536000 ExpiresByType application/vnd.oasis.opendocument.chart A31536000 ExpiresByType application/vnd.oasis.opendocument.formula A31536000 ExpiresByType application/vnd.oasis.opendocument.graphics A31536000 ExpiresByType application/vnd.oasis.opendocument.presentation A31536000 ExpiresByType application/vnd.oasis.opendocument.spreadsheet A31536000 ExpiresByType application/vnd.oasis.opendocument.text A31536000 ExpiresByType audio/ogg A31536000 ExpiresByType application/pdf A31536000 ExpiresByType image/png A31536000 ExpiresByType application/vnd.ms-powerpoint A31536000 ExpiresByType audio/x-realaudio A31536000 ExpiresByType image/svg+xml A31536000 ExpiresByType application/x-shockwave-flash A31536000 ExpiresByType application/x-tar A31536000 ExpiresByType image/tiff A31536000 ExpiresByType application/x-font-ttf A31536000 ExpiresByType application/vnd.ms-opentype A31536000 ExpiresByType audio/wav A31536000 ExpiresByType audio/wma A31536000 ExpiresByType application/vnd.ms-write A31536000 ExpiresByType application/font-woff A31536000 ExpiresByType application/vnd.ms-excel A31536000 ExpiresByType application/zip A31536000 </IfModule> <IfModule mod_deflate.c> <IfModule mod_setenvif.c> BrowserMatch ^Mozilla/4 gzip-only-text/html BrowserMatch ^Mozilla/4\.0[678] no-gzip BrowserMatch \bMSIE !no-gzip !gzip-only-text/html BrowserMatch \bMSI[E] !no-gzip !gzip-only-text/html </IfModule> <IfModule mod_headers.c> Header append Vary User-Agent env=!dont-vary </IfModule> AddOutputFilterByType DEFLATE text/css text/x-component application/x-javascript application/javascript text/javascript text/x-js text/html text/richtext image/svg+xml text/plain text/xsd text/xsl text/xml image/x-icon application/json <IfModule mod_mime.c> # DEFLATE by extension AddOutputFilter DEFLATE js css htm html xml </IfModule> </IfModule> <FilesMatch "\.(css|htc|less|js|js2|js3|js4|CSS|HTC|LESS|JS|JS2|JS3|JS4)$"> FileETag MTime Size <IfModule mod_headers.c> Header set Pragma "public" Header append Cache-Control "public" Header unset Set-Cookie Header set X-Powered-By "W3 Total Cache/0.9.4.1" </IfModule> </FilesMatch> <FilesMatch "\.(html|htm|rtf|rtx|svg|svgz|txt|xsd|xsl|xml|HTML|HTM|RTF|RTX|SVG|SVGZ|TXT|XSD|XSL|XML)$"> FileETag MTime Size <IfModule mod_headers.c> Header set Pragma "public" Header append Cache-Control "public" Header set X-Powered-By "W3 Total Cache/0.9.4.1" </IfModule> </FilesMatch> <FilesMatch "\.(asf|asx|wax|wmv|wmx|avi|bmp|class|divx|doc|docx|eot|exe|gif|gz|gzip|ico|jpg|jpeg|jpe|json|mdb|mid|midi|mov|qt|mp3|m4a|mp4|m4v|mpeg|mpg|mpe|mpp|otf|odb|odc|odf|odg|odp|ods|odt|ogg|pdf|png|pot|pps|ppt|pptx|ra|ram|svg|svgz|swf|tar|tif|tiff|ttf|ttc|wav|wma|wri|woff|xla|xls|xlsx|xlt|xlw|zip|ASF|ASX|WAX|WMV|WMX|AVI|BMP|CLASS|DIVX|DOC|DOCX|EOT|EXE|GIF|GZ|GZIP|ICO|JPG|JPEG|JPE|JSON|MDB|MID|MIDI|MOV|QT|MP3|M4A|MP4|M4V|MPEG|MPG|MPE|MPP|OTF|ODB|ODC|ODF|ODG|ODP|ODS|ODT|OGG|PDF|PNG|POT|PPS|PPT|PPTX|RA|RAM|SVG|SVGZ|SWF|TAR|TIF|TIFF|TTF|TTC|WAV|WMA|WRI|WOFF|XLA|XLS|XLSX|XLT|XLW|ZIP)$"> FileETag MTime Size <IfModule mod_headers.c> Header set Pragma "public" Header append Cache-Control "public" Header unset Set-Cookie Header set X-Powered-By "W3 Total Cache/0.9.4.1" </IfModule> </FilesMatch> # END W3TC Browser Cache # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress
The only thing that I could see different between the static files and html was that the html pages were sending cookies out, so I tried amending my default.vcl to unset cookies as follows:
sub vcl_recv { if ( !( req.url ~ ^/admin/) ) { unset req.http.Cookie; } }
I'm completely baffled by this now, so any help would be greatly appreciated
-1073610 0<%= myfunction(); %>
would be used to output the return value of myfunction
in a page.
<%# myfunction(); %>
would be used to output the return value of myfunction
in a control that is data bound (for example, inside an asp repeater control).
Take a look at this overview for more information on data binding.
-12930378 0 Fluid width for container of inline, non-wrapping elementsI'm having a little CSS trouble.
I have some div elements structured like the following example. There are a dynamic number of class="block" divs, each with a fixed width:
<div class="outer-container"> <div class="inner-container"> <div class="block">text</div> <div class="block">text</div> <div class="block">text</div> <!-- More "block" divs here --> </div> </div>
My goal is to find a CSS-based solution that will.
class="block"
divs inline, without them wrapping to new lines.class="inner-container"
divs like the one above, each displayed as its own line."shrink-wrap"
to match the width of its contents.Any suggestions?
-11075254 0 Passing js array to PHPPossible Duplicate:
Passing a js array to PHP
i'm stuck jQuery $.post() method, i can't access my through PHP $_POST and I can't figure out why.
Here is the js:
<script type="text/javascript"> var selectedValues; $("td").click(function() { $(this).toggleClass('selectedBox'); selectedValues = $.map($("td.selectedBox"), function(obj) { return $(obj).text(); }); // $.post('/url/to/page', {'someKeyName': variableName}); //exemple $.post('handler.php', {'serializedValues' : JSON.stringify(selectedValues)}, function(data) { //debug } ); }); </script>
And here is the PHP file:
<?php if(isset($_POST['serializedValues'])) { var_dump($_POST['serializedValues']); $originalValues = json_decode($_POST['serializedValues'], 1); print_r($originalValues); } ?>
When I issue a console.log(selectedValues) after selecting some of the td element, it return me this for exemple:
[" 3 ", " 4 "]
Something else, when I inspect the sent header through XHR, i get this:
serializedValues:[" 3 "," 4 "]
And finally, in php var_dump($_POST) still returns me nothing :(
Some hints ? Thanks in advance :)
-36102332 0I am just curious: how is
val 2 = 123
understood by Scala?
You can think of val 2 = 123
as:
123 match { case 2 => 2 }
The variable name part in Scala isn't always a simple name, it can also be a pattern, for example:
val (x, y) = (1, 2)
Will decompose 1 and 2 to x and y, respectively. In scala, everything which is allowed after a case statement is also allowed after val and is translated to a pattern match.
From the specification (emphasis mine):
Value definitions can alternatively have a pattern as left-hand side. If p is some pattern other than a simple name or a name followed by a colon and a type, then the value definition
val p = e
is expanded as follows:
(Skipping to the relevant example):
If p has a unique bound variable x:
val x = e match { case p => x }
This is the reason the compiler doesn't emit a compile time error. There is a lengthy discussion of the subject in this google group question.
-23390899 0I've done the exact same thing few weeks ago. I used the System.DirectoryServices.ActiveDirectory
library, and used the Domain
and DomainController
objects to find what you are looking for.
Here is the code I'm using:
public static class DomainManager { static DomainManager() { Domain domain = null; DomainController domainController = null; try { domain = Domain.GetCurrentDomain(); DomainName = domain.Name; domainController = domain.PdcRoleOwner; DomainControllerName = domainController.Name.Split('.')[0]; ComputerName = Environment.MachineName; } finally { if (domain != null) domain.Dispose(); if (domainController != null) domainController.Dispose(); } } public static string DomainControllerName { get; private set; } public static string ComputerName { get; private set; } public static string DomainName { get; private set; } public static string DomainPath { get { bool bFirst = true; StringBuilder sbReturn = new StringBuilder(200); string[] strlstDc = DomainName.Split('.'); foreach (string strDc in strlstDc) { if (bFirst) { sbReturn.Append("DC="); bFirst = false; } else sbReturn.Append(",DC="); sbReturn.Append(strDc); } return sbReturn.ToString(); } } public static string RootPath { get { return string.Format("LDAP://{0}/{1}", DomainName, DomainPath); } } }
And then, You simply call DomainManager.DomainPath
, everything is initialized once (it avoids resource leaks) or DomainName
and so on. Or RootPath, which is very useful to initialize the root DirectoryEntry
for DirectorySearcher
.
I hope this answers your question and could help.
-29483203 0You have an extra colon in one of your parameter array keys:
$query_params = array( ':username' => $username, ':password' => $password, ':salt' => $salt, ':email' => $email, ':level:' => $level // this should just be ':level' );
As a side note - if you individually bind the parameters instead of passing as a whole array, you should get a more discriminating error message:
$query = "...."; $stmt = $db->prepare($query); $stmt->bindParam(":username", $username); ... $result = $stmt->execute();
-35731063 1 Compare two columns of two different dataframes Recently, I switched from matlab to python with pandas. It has been working great, but i am stuck at solving the following problem efficiently. For my analysis, I have to dataframes that look somewhat like this:
dfA = NUM In Date 0 2345 we 1 01/03/16 1 3631 we 1 23/02/16 2 2564 we 1 12/02/16 3 8785 sz 2 01/03/16 4 4767 dt 6 01/03/16 5 3452 dt 7 23/02/16 6 2134 sz 2 01/03/16 7 3465 sz 2 01/03/16
and
dfB In Count_Num 0 we 1 3 1 sz 2 2 2 dt 6 3 3 dt 7 1
What I would like to perform is a an operation that sums all 'Num' for all "In" in dfA and compares it with the "Count_num" in dfB. Afterwards, I would like to add an column to dfB to return if the comparison is True or False. In the example above, the operation should return this:
dfB In Count_Num Check 0 we 1 3 True 1 sz 2 2 False 2 dt 6 1 True 3 dt 7 1 True
My approach:
With value_counts() and pd.DataFrame, I constructed the following dfC from dfA dfC =
In_Number In_Total 0 we 1 4 1 sz 2 3 2 dt 6 1 3 dt 7 1
Then I merged it with dfB to check it afterwards if the values are the same by comparing the columns within dfB. In this case, I have to end dropping the columns. Is there a better/faster way to do this? I think there is a way to do this very efficiently with one of pandas great functions. I've tried to look into lookup
and map
, but I can not make it work.
Thanks for the help!
-11045699 0You could use HTTP authentication which uses plain text to send user name and password, so to protect it you could use SSL.
An excellent article could be found here
-14922537 0 verilog array referencingI have this module. The question is gameArray[0][x][y-1]
doesn't work. What is the correct way to perform this kind of operation? Basically it is similar to C++ syntax but can not get it to work.
module write_init_copy( input clk, input gameArray [1:0][63:0][127:0], writecell, processedcell, input [5:0] x, input [6:0] y, input initialize, copyover, output reg done_initialize, done_copy, done_writecell); always@(posedge clk) begin if(writecell == 1) begin gameArray[1][x][y] <= processedcell; done_writecell <= 1; end else if(initialize == 1) begin end end endmodule
-37575287 0 How to get data from json file for net-snmp trap? I have json file and i am exporting file into another file using require i see the data but when i print the value obj.oid
from json object it returns undefined any idea why ?
app.js
var snmp = require ("net-snmp"); var session = snmp.createSession ("127.0.0.1", "public"); var oids = require('./oids'); var obj = JSON.stringify(oids); console.log("OIDS",obj.oid)
oids.json
{ "oid": "1.3.6.1.2.1.1.4.0", "type": "snmp.ObjectType.OctetString", "value": "user.name@domain.name" }
-4571926 0 Cache list of ids to check before querying database I have a Asp.Net Mvc application that has a default route pattern of /controller/action/id
.
This means the user could simply put any ID in the url if they are savy enough to figure it out. I could handle the exceptions, redirect the user to an error page (and I am) or any number of other solutions. There are only about 1200 possible valid IDs. I was considering caching a list of these IDs at the application level to check against before querying the database to save the expense of making a connection and handling the exceptions.
Does anyone have a good argument as to why this is a bad solution?
-38313504 0You can avoid division by zero while maintaining performance by using advanced indexing:
x = np.arange(-500, 500) result = np.empty(x.shape, dtype=float) # set the dtype to whatever is appropriate nonzero = x != 0 result[nonzero] = 1/x[nonzero] result[~nonzero] = 0
-37799934 0 You can do it easily by different view types. For Example -
class MyData{ String text; boolean isHeader; } public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { ArrayList<MyData> allData; class ViewHolder0 extends RecyclerView.ViewHolder { ... } class ViewHolder2 extends RecyclerView.ViewHolder { ... } @Override public int getItemViewType(int position) { // Just as an example, return 0 or 2 depending on list(let assume 0 for header 1 for data // Note that unlike in ListView adapters, types don't have to be contiguous return allData.get(position).isHeader?0:1; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { switch (viewType) { case 0: return new ViewHolder0(header view); case 1: return new ViewHolder2(data view); ... } } }
And if data is updated then just update your dataList and call notifyDataSetChange() on the adapter.
Hope it will help you :)
-30836150 0This is how I made the above example work, note Im using ember-cli
. Instead of creating my store with the DS.RESTAdapter.create()
, or in my case, Im using DS.LSAdapter
, I create my store in a initializer like this:
app.LsStore = DS.Store.extend({ adapter: '-ls', }); app.register('store:lsstore', app.LsStore); app.register('adapter:-ls', DS.LSAdapter);
This basically registers a lsstore
and a adapter:-ls
on the container. Then I can inject my store into the application's route
or controller
, and this will try to find the adapter using adapter:-ls
.
You have probably used the dir
attribute/CSS set to rtl
instead of proper CSS alignment.
The dir
attribute:
This attribute specifies the base direction of directionally neutral text (i.e., text that doesn't have inherent directionality as defined in [UNICODE]) in an element's content and attribute values. It also specifies the directionality of tables.
As you can see this is not limited to alignment.
Use CSS alignment/positioning to align HTML controls.
-26367211 0 How to get the terminal leaves of a Wikipedia root categoryI want to get only the leaves a wikipedia category but not sure how. I can get all the leaves by
SELECT ?subcat WHERE { ?subcat skos:broader* category:Buildings_and_structures_in_France_by_city . }
This gives me all intermediate leaves (such as Category:Buildings_and_structures_in_Antibes) but I want to get just the last/bottom leaves of the tree. Leaves that can not be split anymore. How can I do this?
-1110786 0Web Services, in general, are meant to be cross-platform. What would a Java program do with a System.Type from .NET?
Also, what part of Type would you like to see serialized, and how would you like to see it deserialized?
-21297062 0 IFrame form submittal opens in frame, needs to open in new windowTrying to resolve an issue using a 3rd party form that unfortunately has to use an iframe to be embedded in the article content. When a user submits their email address, the thank you page opens up in the space taken up by the iframe instead of the page / a new window. I tried using the following JS script to no avail:
<script type="text/javascript"> // If "&_parent=URL" is in this page's URL, then put URL into the top window var match = /_parent=(.+)/.exec(window.location.href); if (match != null) { top.location = match[1]; } </script>
The page in question:
http://restoringqualityoflifeblog.org/subscribe/
Thanks!
-21877273 0According to hibernate DTD, This should solve your problem
<natural-id> <component name="location"> <property name="countryISO2"/> <property name="city"/> </component> </natural-id>
and you should remove <component>
that's at bottom of the mapping.
I know there is already an accepted answer for this question, but this same question was asked here:
MouseAdapter: which pattern does it use?
See there for more deatils, but the MouseAdapter adapts the very awkaward MouseListener interface into a more usable form.
-4526852 0 Need help implementing a special edge detectorI'm implementing an approach from a research paper. Part of the approach calls for a major edge detector, which the authors describe as follows:
Note that this NOT Canny edge detection -- they don't bother with things like non-maximum suppression, etc. I could of course do this with Canny edge detection, but I want to implement things exactly as they are expressed in the paper.
That last step is the one I'm a bit stuck on.
Here is exactly what the authors say about it:
After obtaining the binary edge map from the edge detection process, a binary morphological operation is employed to remove isolated edge pixels, which might cause false alarms during the edge detection
Here's how things are supposed to look like at the end of it all (edge blocks have been filled in black):
Here's what I have if I skip the last step:
It seems to be on the right track. So here's what happens if I do erosion for step 4:
I've tried combinations of erosion and dilation to obtain the same result as they do, but don't get anywhere close. Can anyone suggest a combination of morphological operators that will get me the desired result?
Here's the binarization output, in case anyone wants to play around with it:
And if you're really keen, here is the source code (C++):
#include <cv.h> #include <highgui.h> #include <stdlib.h> #include <assert.h> using cv::Mat; using cv::Size; #include <stdio.h> #define DCTSIZE 8 #define EDGE_PX 255 /* * Display a matrix as an image on the screen. */ void show_mat(char *heading, Mat const &m) { Mat clone = m.clone(); Mat scaled(clone.size(), CV_8UC1); convertScaleAbs(clone, scaled); IplImage ipl = scaled; cvNamedWindow(heading, CV_WINDOW_AUTOSIZE); cvShowImage(heading, &ipl); cvWaitKey(0); } /* * Get the DC components of the specified matrix as an image. */ Mat get_dc(Mat const &m) { Size s = m.size(); assert(s.width % DCTSIZE == 0); assert(s.height % DCTSIZE == 0); Size dc_size = Size(s.height/DCTSIZE, s.width/DCTSIZE); Mat dc(dc_size, CV_32FC1); cv::resize(m, dc, dc_size, 0, 0, cv::INTER_AREA); return dc; } /* * Detect the edges: * * Sobel operator * Thresholding * Morphological operations */ Mat detect_edges(Mat const &src, int T) { Mat sobelx = Mat(src.size(), CV_32FC1); Mat sobely = Mat(src.size(), CV_32FC1); Mat sobel_sum = Mat(src.size(), CV_32FC1); cv::Sobel(src, sobelx, CV_32F, 1, 0, 3, 0.5); cv::Sobel(src, sobely, CV_32F, 0, 1, 3, 0.5); cv::add(cv::abs(sobelx), cv::abs(sobely), sobel_sum); Mat binarized = src.clone(); cv::threshold(sobel_sum, binarized, T, EDGE_PX, cv::THRESH_BINARY); cv::imwrite("binarized.png", binarized); // // TODO: this is the part I'm having problems with. // #if 0 // // Try a 3x3 cross structuring element. // Mat elt(3,3, CV_8UC1); elt.at<uchar>(0, 1) = 0; elt.at<uchar>(1, 0) = 0; elt.at<uchar>(1, 1) = 0; elt.at<uchar>(1, 2) = 0; elt.at<uchar>(2, 1) = 0; #endif Mat dilated = binarized.clone(); //cv::dilate(binarized, dilated, Mat()); cv::imwrite("dilated.png", dilated); Mat eroded = dilated.clone(); cv::erode(dilated, eroded, Mat()); cv::imwrite("eroded.png", eroded); return eroded; } /* * Black out the blocks in the image that contain DC edges. */ void censure_edge_blocks(Mat &orig, Mat const &edges) { Size s = edges.size(); for (int i = 0; i < s.height; ++i) for (int j = 0; j < s.width; ++j) { if (edges.at<float>(i, j) != EDGE_PX) continue; int row = i*DCTSIZE; int col = j*DCTSIZE; for (int m = 0; m < DCTSIZE; ++m) for (int n = 0; n < DCTSIZE; ++n) orig.at<uchar>(row + m, col + n) = 0; } } /* * Load the image and return the first channel. */ Mat load_grayscale(char *filename) { Mat orig = cv::imread(filename); std::vector<Mat> channels(orig.channels()); cv::split(orig, channels); Mat grey = channels[0]; return grey; } int main(int argc, char **argv) { assert(argc == 3); int bin_thres = atoi(argv[2]); Mat orig = load_grayscale(argv[1]); //show_mat("orig", orig); Mat dc = get_dc(orig); cv::imwrite("dc.png", dc); Mat dc_edges = detect_edges(dc, bin_thres); cv::imwrite("dc_edges.png", dc_edges); censure_edge_blocks(orig, dc_edges); show_mat("censured", orig); cv::imwrite("censured.png", orig); return 0; }
-33454385 0 No. Symbols must be accessed using bracket notation.
Dot notation is only used for string
keys that follow certain rule patterns, mostly about being a valid identifier.
Symbols are not strings, they are a whole something else entirely.
Short rational: One of the design goals of symbols is that they can not clash with property names, that makes them safe to use.
So, if you had an object like this
var = { prop1: "Value" };
And you created a symbol called prop1
, how could you tell the two apart, and access them differently, using just object notation?
I want to replace one scene with another with fade out - fade in effect.(old scene fades out(to the black screen),and then new scene fades in).
i found solution manually to decrease opacity of one scene and then launch
[[CCDirector sharedDirector] replaceScene:[HelloWorld scene]];
But i suppose there is another solution with the use of actions. Please, help me)
-23583492 0 GET paramets in CRON jobI have a FOR loop for parsing xml file as parts, but I using a $_GET paramets to receive variable sending at the end of loop in URL (meta http-equiv="Refresh" content="0; url...). In Web browser everything works fine but I want to use CRON job to do it automatically. So it is possible to do something like this? I'll be very grateful for any advice or example
My code:
$name = 'tmp_add_xml'; if(isset($_GET['file'])){ $xmlfile = 'import/'.$_GET['file'].'.xml'; } else { $xmlfile = 'import/'.$name.'.xml'; $xmlurl = 'URL_XML_FILE'; $downxml = file_get_contents($xmlurl); file_put_contents($xmlfile, $downxml); } $xml = simplexml_load_file($xmlfile); $xml_offer = $xml->xpath("//offer"); $total = count($xml_offer); if(isset($_GET['x']) && isset($_GET['exist']) && isset($_GET['added'])){ $x = $_GET['x']; $product_exist = $_GET['exist']; $product_added = $_GET['added']; } else { $x = $product_exist = $product_added = 0; } $limit = $x+1000; for($z = $x; $z <= $limit; $z++){ $productid = $xml_offer[$z]->id; if(mysql_num_rows(mysql_query("SELECT reference FROM ps_product WHERE reference = '".$productid."'")) > 0){ $product_exist++; } else { $product_added++; } if($z==$total){ echo 'Import 100%'; exit; } elseif($z==$limit){ print '<meta http-equiv="Refresh" content="0; url='.$_SERVER['PHP_SELF'].'?x='.($x+1).'&file='.$name.'&exist='.$product_exist.'&added='.$product_added.'">'; exit; } $x++; }
URL: script_name.php?x=VARIABLE&file=VARIABLE&exist=VARIABLE&added=VARIABLE
-8677069 0It's typically not a problem unless a) you have a lot of customers frequently making purchases (good for you! :)), and b) you change your prices very frequently
The solution is:
a) change prices (or, more generally, change ANYTHING) off-hours, when customers aren't likely to be using the system
... and/or ...
b) schedule a "maintenance window", during which you lock out user sessions in order to change prices, items and/or schema (the customary approach).
-36806947 0 Ng-repeat not updating with array changesI have looked over this issue for many hours and read many other questions that seem entirely the same and I have tried every one of their solutions, but none seem to work.
I have an array of objects (instructionObj.instructions
) and those objects get repeated with ng-repeat
and their template is a directive.
<div instruction-directive ng-repeat="i in instructionsObj.instructions"> </div>
I then allow the items to be sorted using Jquery UI sortable.
var first, second; $( ".sort" ).sortable({ axis: "y", start: function( event, ui ) { first = ui.item.index(); }, stop: function( event, ui ) { second = ui.item.index(); console.log(first + " " + second); rearrange(first, second); $scope.$apply(); } });
I then access the start and end index of the object being moved and rearrange the array accordingly:
function rearrange(f, s){ $timeout(function () { $scope.instructionsObj.instructions.splice(s, 0, $scope.instructionsObj.instructions.splice(f, 1)[0]); $scope.$apply(); }); }
All of this works great most of the time. The one scenario I have found a failure is when rearranging the objects as such (one column is the current position of all objects displayed on the screen):
a | b | c | d | a
b | c | d | c | b
c | d | b | b | d
d | a | a | a | c
The last step should be a, d, c, b. But it changes to a, b, d, c.
However, when I go back to my previous view and come back the correct configuration is displayed, all is well. As you can see I have tried $timeout
and $apply()
and many other things, but none seem to work.
I know this is a DOM updating issue because I can log the array and see that it is different (correct) from what the DOM shows (incorrect). Any help would be appreciated.
Update:
I am even using <pre ng-bind="instructionsObj.instructions|json</pre>
to show the exact layout of the array and it is always correct. My mind is blown.
I use DB2 Express-C. I have ON INSERT trigger on a table, where I insert the new row into another table. Is there a way not to insert the new row into the table on which the trigger is defined?
Any help is appreciated, thank you
-8678839 0You can do this easily by using regexp to match the string and to replace the corresponding parts. As you mentioned that you'd want to do this with jQuery I am assuming you have jQuery already on your site, but if you don't I wouldn't recommend adding it for this.
Instead of explaining further what to do, I've pasted the code below and commented each step, which should make it quite clear what's going on:
// bind onchange and keypress events to the width and height text boxes $('#txtwidth, #txtheight').bind('change keypress', function(){ // define the regexp to which to test with, edit as needed var re = /\/Content\/Image\/([0-9]+)\/[0-9]+\/[0-9]+\//, // store url and its value to a variable so we won't have to retrieve it multiple times url = $('#url'), val = url.val(); // test if regexp matches the url if (!re.test(val)) { // doesn't match return; } // we got this far, so it did match // replace the variables in the regexo val = val.replace(re, "/Content/Image/$1/" + $("#txtwidth").val() + "/" + $("#txtheight").val() + "/"); // put it back into the input field url.val(val); });
example: http://jsfiddle.net/niklasvh/wsAcq/
-30807706 0You can always remove all untracked (and unignored) files with git clean -f
. To be safe, run git clean -n
first to see which files will be deleted.
That's not a stupid question! I believe what is meant by "strings that it cannot handle" is actually, "strings which are not in a valid format", which I take to mean "strings that contain symbols that we don't know." (I'm going off of slide 14 of this presentation, which I found by just googling Turing 'implicitly reject'
).
So, if we do use that definition, then we need to simply create a Turing machine that accepts an input if it contains a symbol not in our valid set.
Yes, there are other possible interpretations of "strings that it cannot handle", but I'm fairly sure it means this. It obviously could not be a definition without constraints, or else we could define "strings that it cannot handle" as, say, "strings representing programs that halt", and we'd have solved the halting problem! (Or if you're not familiar with the halting problem, you could substitute in any NP-complete problem, really).
I think the reason that the idea of rejecting strings the Turing machine cannot handle was introduced in the first place is so that the machine can be well defined on all input. So, say, if you have a Turing machine that accepts a binary number if it's divisible by 3, but you pass in input that is not a bianry number (like, say, "apple sauce"), we can still reason about the output of the program.
-18592902 0 Writing UART ApplicationI have been asked to understand the 16550A UART for Linux (3.10 Kernel)and write some test case on its functional blocks.But before that only i am facing lot of troubles in understanding the code flow of the same as it is very big ( I am following kernel 3.10 version) with multiple entry points and exit points.So i thought of writing a UART Application (C Program) having two threads which will transmit and receive characters to the UART port and understand the code flow by printing the log messages. Now I am not getting how to start writing application which would do the same. Also If anyone can help me in getting the first part of the my task (writing test cases) that would be great. And also can you provide me with some of the good links related to UART. Thanks
-24831384 0Looks like I need a couple plugins and something like this will work
http://a-developer-life.blogspot.com/2011/06/jasmine-part-2-spies-and-mocks.html
-9273958 0 how can i save "read " error output in shell script?I write a bash file in which i used read
command to read data from a file.
If the file wasn't there I want to save the error into a text file. I tried:
read myVariable < myFile 2> errorFile.txt
it doesn't work, and many other efforts faild such as:
myVar=`read myVariable < myFile`
-9770210 0 Yes - If I understand your question correctly you should be able to add a mapping in your local hosts file to point that domain at your IIS webserver.
e.g.
10.0.0.x my.example.hostname
(where x is obviously a number)
We use this configuation internally when developing multiple sites on our local machines - each site is bound to a specific hostname and all these hostnames have mappings in the 'hosts' file to 127.0.0.1
The same principal applies here, if I've understood the question correctly :)
-12498073 0I figured out how to solve the issue: in the X class, add this to the to_dict() method:
... if value is None: continue if key == 'metaData': array = list() for data in value: array.append(data.to_dict()) output[key] = array elif isinstance(value, SIMPLE_TYPES): output[key] = value ...
Though I'm not really sure how to automate this case where it's not based off key, but rather whenever it encounters a list of custom objects, it first converts each object in the list to_dict() first.
-24938293 0 nodeschool Streams adventure [HTTP SERVER]I found a bit of intriguing behavior on an exercise about nodejs.
The aim is to transform POST data of a request to uppercase and send back using stream.
My problem is I'm not having the same behavior between these two pieces of code (the transform function just take the buf
and queue
it to uppercase) :
var server = http.createServer(function (req, res) { var tr = through(transform); if (req.method === 'POST') { req.pipe(tr).pipe(res); } });
var tr = through(transform); var server = http.createServer(function (req, res) { if (req.method === 'POST') { req.pipe(tr).pipe(res); } });
The first one is correct and gives me :
ACTUAL EXPECTED ------ -------- "ON" "ON" "THEM" "THEM" "BUT," "BUT," ...
My version with the tr
var outside :
ACTUAL EXPECTED ------ -------- "QUICK." "QUICK." "TARK'S" "TARK'S" "QUICK." !== "BIMBOOWOOD" "TARK'S" !== "BIMBOOWOOD" "BIMBOOWOOD" !== "SO" "BIMBOOWOOD" !== "SO" ...
For info the transform function
:
function transform(data) { this.queue(data.toString().toUpperCase()); }
-39923202 0 You should keep in mind that "good OO" is mainly about behavior of objects. Objects (and classes) exist to "map" some "concept out of reality" into the "model" that you make the base of your application.
Thus: you don't use inheritance to save a line of code here or there. You put the "B extends A" tag on B because that is the reasonable thing to do guided by your model.
Given that: your idea of making a tall dog a furniture is a very nice example for people using inheritance for the completely wrong reasons!
Thus: simply forget about this idea; and do as the comments suggest: create reasonable interfaces, and put those classes where they make sense.
-4052499 0 Existing List of W3C complient html attributeIt's there a place i can see wich attribute are w3c on all HTML Element, div,p,a,li,hr etc ...
I check on w3cshool but find nothing.
I need a list where they said someting like ... id : (div, a , hr , etc ...), class (div, a , hr , etc) ...
-16259845 0 FullCalendar is adding space after events with a URLI'm using a pretty basic JQuery plugin called FullCalendar to add easy to use calendar to my website. I've mostly had no troubles until now. The main problem is that when you add a url to events in the event object it puts an unnecessary amount of space under it. Further, it works just fine with the url when the title is less than 6 or 7 characters or so. But when you have a a few words it adds the space. I really can't figure this out.
I've imported the stylesheet and js file.
<link rel='stylesheet' type='text/css' href='fullcalendar.css' /> <script type='text/javascript' src='jquery.js'></script> <script type='text/javascript' src='fullcalendar.js'></script>
I also have a simple script to set up the calendar and to create two events.
$(function() { /* initialize the calendar -----------------------------------------------------------------*/ var date = new Date(); var d = date.getDate(); var m = date.getMonth(); var y = date.getFullYear(); var calendar = $('#calendar').fullCalendar({ buttonText: { prev: '<i class="icon-chevron-left"></i>', next: '<i class="icon-chevron-right"></i>' }, header: { left: 'prev,next today', center: 'title', right: '' }, events: [ { title: 'All', start: new Date(y, m, 1), url: 'single-event.php' }, { title: 'All Day Event', start: new Date(y, m, 1), url: 'index.html' }] }); })
Here is a link to the same problem - why is there extra space between url-tagged events?
and to the documentation http://arshaw.com/fullcalendar/docs/usage/
-30224687 0It looks like you are sending two independent events (two calls to tracker.send). One with only custom dimensions and one without custom dimensions. The first event is invalid as it is missing required event category and action so Analytics will ignore it. The second is valid event but its missing the custom dimensions. You should send only one event instead:
tracker.send(new HitBuilders.EventBuilder() .setCategory("customCategory") .setAction("customAction") .setLabel("customLabel") .setCustomMetric(cm.getValue(), metricValue) .setCustomDimension(cd.getValue(), dimensionValue) .build());
-1908352 0 Well I usually use the object explorer and go to the table I want and then look under Keys. You can widen the object explorer to see the fullname of the key. If it is named properly it probably has the table name of both the primary key and foreign key tables in it. If not you can script it to see. I had to search to find this relationships window you were talking about becasue I would never use the design window as we script all changes.
-107502 0Obviously Google are major users of Grid Computing; all their search service relies on it, and many others.
Engines such as BigTable are based on using lots of nodes for storage and computation. These are commercially very useful because they're a good alternative to a small number of big servers, providing better redundancy and cost effective scaling.
The downside is that the software is fiendishly difficult to write, but Google seem to manage that one ok :)
So anything which requires big storage and/or lots of computation.
-18820870 0 Information required regarding OpensipI am a newbie in programming world.
I want to experiment with sip protocol and make c program.
trying to use opensip from http://www.opensips.org.
but I am not able to install it properly.
I am using ubuntu 13.04 linux system.
Can anybody guide me for its installation, and give me some simple example to understand sip programming more clearly.
So that i will have a right direction to start in.
The code you've posted will run on the Hadoop master node. scaldingTool.run(args)
will trigger your job, which would trigger the jobs that execute on task nodes.
Here is some related code which works for me (I have very long file names and paths):
for d in os.walk(os.getcwd()): dirname = d[0] files = d[2] for f in files: long_fname = u"\\\\?\\" + os.getcwd() + u"\\" + dirname + u"\\" + f if op.isdir(long_fname): continue fin = open(long_fname, 'rb') ...
Note that for me it only worked with a combination of all of the following:
Prepend '\\?\' at the front.
Use full path, not relative path.
Use only backslashes.
In Python, the filename string must be a unicode string, for example u"abc", not "abc".
Also note, for some reason os.walk(..)
returned some of the directories as files, so above I check for that.
You are saving your model query results in a specific key(assistiti) inside the array $data, and then you are fetching the whole array in the foreach loop. This way, you got to loop through the specific array, inside the array $data:
foreach($data['assistiti'] as $post){ $nome = $post->nome; $cognome = $post->cognome; $tribunale = $post->tribunale; $tbl .= '<tr><td style="border:1px solid #000;text-align:center">'.$nome.'</td>'; $tbl .= '<td style="border:1px solid #000;text-align:center">'.$cognome.'</td>'; $tbl .= '<td style="border:1px solid #000;text-align:center">'.$tribunale.'</td> </tr>'; ;} $pdf->writeHTML($tbl_header.$tbl.$tbl_footer , true, false, false, false, '');
-36534009 0 Try launching XCode directly - often after an update XCode will require you to accept a new EULA before it will launch, which can prevent other apps from launching XCode (or its components) automatically.
-5236157 0A reverse_iterator internally stores a normal iterator to the position after its current position. It has to do that, because rend() would otherwise have to return something before begin(), which isn't possible. So you end up accidentally invalidating your base() iterator.
-14664111 0 How do I style RootElementI need a way to style Monotouch Dialogs RootElement. I need to change the background and font color.
I'm have created a custom RootElement as below
public class ActivityRootElement : RootElement { public ActivityRootElement (string caption) : base (caption) { } public ActivityRootElement(string caption, Func<RootElement, UIViewController> createOnSelected) : base (caption, createOnSelected) { } public ActivityRootElement(string caption, int section, int element) : base (caption, section, element) { } public ActivityRootElement(string caption, Group group) : base (caption, group) { } public override UITableViewCell GetCell (UITableView tv) { tv.BackgroundColor = Settings.RootBackgroundColour; return base.GetCell (tv); } protected override void PrepareDialogViewController(UIViewController dvc) { dvc.View.BackgroundColor = Settings.RootBackgroundColour; base.PrepareDialogViewController(dvc); } }
I am then calling the custom root element as below passing in a custom DialogController
section.Add (new ActivityRootElement(activity.Name, (RootElement e) => { return new ActivityHistoryDialogViewController (e,true); }));
The root Element style is not been applied. Any help would be apprciated!!
-1385371 0 Comparsion between Pixel Bender(in Flash) and Pixel Shaders(in Silverlight)Can someone explain the different between Pixel Bender in Flash and Pixel Shader(HLSL) in Silverlight in terms of programming flexibility and run-time performance?
-24568329 0 svn: Repository moved permanently please relocateI was trying to do a svn unlock by giving the below command
svn unlock http://test.server.com/svn/test/server/linux/issue/conf/config.java
svn: Repository moved permanently to 'http://test.server.com/svn/test/server/linux/issue/conf; please relocate
I think I did a mess. I am not able to access now.
-35538912 0 Peewee select with circular dependencyI have two models Room
and User
. Every user is assigned to exactly one room and one of them is the owner.
DeferredUser = DeferredRelation() class Room(Model): owner = ForeignKeyField(DeferredUser) class User(Model): sessid = CharField() room = ForeignKeyField(Room, related_name='users') DeferredUser.set_model(User)
Now, having sessid
of the owner I'd like to select his room and all assigned users. But when I do:
(Room.select(Room, User) .join(User, on=Room.owner) .where(User.sessid==sessid) .switch(Room) .join(User, on=User.room))
It evaluates to:
SELECT "t1".*, "t2".* # skipped column names FROM "room" AS t1 INNER JOIN "user" AS t2 ON ("t1"."owner_id" = "t2"."id") INNER JOIN "user" AS t2 ON ("t1"."id" = "t2"."room_id") WHERE ("t2"."sessid" = ?) [<sessid>]
and throws peewee.OperationalError: ambiguous column name: t2.id
as t2
is defined twice.
What I actually need to do is:
room = (Room.select(Room) .join(User.sessid=sessid) .get()) users = room.users.execute()
But this is N+1 query and I'd like to resolve it in a single query like:
SELECT t1.*, t3.* FROM room AS t1 INNER JOIN user AS t2 ON t1.owner_id = t2.id INNER JOIN user as t3 ON t3.room_id = t1.id WHERE t2.sessid = ?;
Is there a peewee way of doing this or I need to enter this SQL query by hand?
-7067904 0Well, you could:
fxp
is basically a glorified zip
anyway, so this shouldn't be terribly difficult. I don't know how to stop my countdown from counting up. I used countdown.js
and jquery.min.js
attached to my script. What should I add to accomplish this? Here is my sample code:
<?php $query = "select length_queue, extract(year from (ia_time)), extract(month from (ia_time)), extract(day from (ia_time)), ia_time, serving_time, hour(waiting_time), minute(waiting_time), second(waiting_time) from sys_table"; $i = 0; $dsplay = mysql_query($query); while($row = mysql_fetch_row($dsplay)) { $hr = $row[6]; $min = $row[7]; $sec = $row[8]; ?> <tr> <th height="33"><strong><?php echo $row[0]; ?></strong></td> <th><?php echo $row[4]; ?></td> <th><?php echo $row[5]; ?></td> <th><span id="countdown-holder_<?=$i?>" class="ct" ></span></td> </tr> <script type="text/javascript"> $('.ct').each(function(){ var clock = document.getElementById("countdown-holder_<?=$i++?>"), targetDate = new Date(2016, 02, 27, <?php echo $hr;?>, <?php echo $min;?>, <?php echo $sec;?>) ; clock.innerHTML = countdown(targetDate).toString(); setInterval(function(){ clock.innerHTML = countdown(targetDate).toString(); }, 1000); }); // end of function </script> <?php } // END of while loop ?>
-4060332 0 On Android it's best to use AsyncTask to execute tasks in the background while (progressively) updating UI with results from this task.
Edited:
After checking code I think your Handler works correctly. Probably problem is in UpdateDisplay()
. Since you are updating display from background thread, make sure you call [view.postInvalidate()][2]
after you're done updating your View.
SQLite itself does not require that every parameter is bound explicitly; the default value is NULL.
If the database driver you're using forces you to set all parameters, just set them to NULL.
If index statistics are enabled, SQLite can recompile statements whenever new parameters have been set. In this case, the execution plan might not be the same as you would get for actual parameter values.
-4483791 0You definitely should try Gibraltar. You can combine it with PostSharp and your performantce monitoring will be a piece of cake. Just look into the following code example:
[GTrace] public Connection ConnectToServer(Server server) { ConnectionStatus connectionStatus = server.TryConnect(); return connectionStatus; }
And the result in log will look like the following:
Starting method call (you can see passed arguments)
Ending method call
No crap in code, only thing you need is one attribute. Attrubutes can be used for whole project excluding not needed methods, on namespases, classes or just on any methos you need. Enjoy!
Edit Forgot to mention that Gibraltar has a very rich client and support any metrics you ever need, it's just too powerfull:
I Solved My problem.
Simply add extension=mongo.so in the php.ini file here etc/php5/cli.
-36100253 0You are using the wrong API.
You should be calling _ensureIndex
on your collection.
If the Delphi function is declared as being stdcall
, why would you declare it in C# as cdecl
?
This is the cause of the stack imbalance. Change your C# declaration to use the stdcall
convention to match the Delphi declaration.
[UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate double WriteRate(object data);
-22221362 0 we can set an empty array to the Filtering select widgets store.
dijit.byId('widgetId').store.data.splice(0,dijit.byId('widgetId').store.data.length);
or simply,
dijit.byId('widgetId').store.data = [];
Or you can set the store itself as null. (But, to add new options after this, you need to recreate the store again, before adding up the new options).
dijit.byId('widgetId').store = null;
-8026669 0 As a reference for future users:
Don't forget to also INSTALL the framework you target! (I, myself, thought that because all the folders (v4.0x, v2.0X, etc.) were there I had all frameworks. NOT! It turns out I only had the .NET 4.0 client profile installed on my system and could not find the System.Web, even though the right framework was targeted.
Anyway, download your needed .net framework here: .NET Frameworks Microsoft Downloads
-6312307 0For the applet to find the libraries, they must be reachable by HTTP. Putting them in the library directory of you web application does not help.
-15099432 0I added a project file and some other small changes which are needed to build ZXing.Net for PCL. You can get it from the source code repository at codeplex. You have to build your own version because at the moment there is no pre built binary. Next version will include it. The restriction of the PCL version is that you have to deal with RGB data. You can't use platform specific classes like Bitmap, WriteableBitmap, BitmapSource or Color32.
-13606840 0 VBA MailMerge length > 255i'm trying to use MailMerge with Word 2010.
I have a TAB delimited file database.dat which looks like the following:
ID Name Street 1 John FooBar 1 2 Smith FooBar 2
This file is used in Word with the following VBA Code:
ActiveDocument.MailMerge.OpenDataSource Name:="C:/database.dat", _ ConfirmConversions:=False, ReadOnly:=False, LinkToSource:=True, _ AddToRecentFiles:=False, Revert:=False, Format:=wdOpenFormatAuto
I can use the fields from the file now in the text. So everything works fine.
The Problem:
I need to do some further elaboration with the data in VBA, so I fetch the MergeField Value with:
Function getInfoField(mergefield As String) On Error GoTo MergeFieldNotFound: getInfoField = ActiveDocument.MailMerge.DataSource.DataFields(mergefield).Value GoTo EndFunc MergeFieldNotFound: getInfoField = "" EndFunc: End Function
But if the length of a merge field value exceeds 255 characters it is cut off. So if I insert
MsgBox Len(ActiveDocument.MailMerge.DataSource.DataFields(mergefield).Value)
It outputs 255 for a String with e.g. 500 chars.
But directly in the word document, all 500 chars are shown for the merge field.
Question:
How can I get more than 255 chars out of the merge field in VBA?
-29677502 0Perhaps you could simplify and use ng-switch
instead.
Something like this:
<ul ng-switch="expression"> <li ng-switch-when="firstThing">my first thing</li> <li ng-switch-when="secondThing">my second thing</li> <li ng-switch-default>default</li> </ul>
Alternatively, maybe you could use ng-if
or ng-show
instead of ng-hide
, eg:
<p ng-if="HideAddNew">it's here!</p> <p ng-if="!HideAddNew">it's not here.</p>
Edit
If I understand what you're trying to achieve exactly, I would use ng-show
with an ng-click
:
Controller:
$scope.addNew = false;
View:
<button ng-show="!addNew" ng-click="addNew = true">Add New</button> <button ng-show="addNew" ng-click="save()">Save</button> <button ng-show="addNew" ng-click="addNew = false">Cancel</button>
-18162650 0 Here:
struct integer* x= malloc(sizeof(int) * 100);;
you are allocating memory for the structure (i.e. the pointer and the int), but not for the array.
The moment you try to assign to x->arr[j]
, you have undefined behaviour.
The relevant part for you is the following one:
You should only grant permission to use the PHP filter to people you trust.
There are always risk of exposing a site to possible attacks when writing code, and in fact the Drupal security team's task is to report security holes to the module maintainers to fix them.
With the PHP filter, the more immediate risk is that users who use it have access to any database table. It would be easy for somebody to change the user account's password, change the ownership of a node, etc.
but i can't find any tutorial which links sql server with cordova app, all i can find is with SQLite or MySQL. I want to connect my local DB with the app directly.
Currently there is no way to connect to sql server
directly in Cordova.
You need to implement a service layer for data exposion of your database. You can leverage mssql for node if you are familar with javascript. Alternatively, ASP.Net Web API is a good choice, if you are more familar with .Net
.
Whatever the technology you use to build the service layer. It will eventually be consumed by your cordova app through Ajax.
-23993911 0I am not sure whether there is simple way of passing values from View to Controller in Kendo UI Grid. But i have followed the below way in third party MVC Grid to pass the checkbox values. You can bind this function to button click event. It could be too long for simple operation. May be it could be useful for you which you can optimize for your needs.
function PostData(sender, args) { var tempCheckedRecords = new Array(); var gridobj = $find("Grid1"); // getting Grid object. Modify it for KendoUI grid. if (sender.checked == true) { ... //retrieve the records here tempCheckedRecords.push(records[0]); // pass the selected records in the array } var tempRecords = new Array(); $.each(tempCheckedRecords, function (index, element) { var record = {}; record["Column0"] = element.IsSelected; // column names in Grid record["Column1"] = element.TestPointName; // you can get the text box values in the element. record["Column2"] = element.PassThreshold; tempRecords.push(record); }); var params = {}; var visibleColumns = gridobj.get_VisibleColumnName(); $.each(tempRecords, function (i, record) { $.each(visibleColumns, function (j, value) { params["Test[" + i + "]." + this] = record[value]; }); }); $.ajax({ type: 'post', url: "/configuration/testplan/Add", datatype: 'json', data: params, success: function (data) { return data; } }); }
-15266133 0 Why does PMD suggest making fields final? I created Android application and run static analysis tool PMD on it. And what I don't get is why it is giving me warning and says to declare fields final when possible like in this example.
final City selectedItem = (City) arg0.getItemAtPosition(arg2); new RequestSender(aaa).execute(xxx, selectedItem.getId());
It just starts inner AsyncTask instance. Is it good style to declare it final and why? For the sake of readability, I created a new object, but PMD says it should be final.
-8603024 0According to your logic, it is impossible for both conditions to run at the same time. However, I'm sure you've run this script multiple times. Sometimes with IF, sometimes with ELSE. It doesn't seem like you're ever clearing the $_SESSION variables.
Solution: Right after you use the $_SESSION['save'] or $_SESSION['error'] variables, unset them.
unset($_SESSION['save']);
or
unset($_SESSION['error]');
-7926733 0 system %x{ wget #{item['src']} }
Edit: This is assuming you're on a unix system with wget :) Edit 2: Updated code for grabbing the img src from nokogiri.
-21804151 0Long story short: I built my own custom container for that. It provides the ability to switch between tabs, as well as pushing new ViewControllers on each tab. Kind of like a hybrid between UINavigationController and UITabBarController.
If you need a more detailed answer on that please let me know.
-22637195 0Should be like this:
And then this:
It is surprisingly simple. Make sure you've selected the right section.
-8024349 0You should create a custom SearchResult
class with a property that returns the full path.
The class should override ToString()
and return the text you want to display in the listbox.
You can then put instances of your class directly into the listbox, and cast an item from the listbox back to the class to get the property.
-32574686 0It should be as easy as adding the file to your extension target/project so that both are part of the same module. Same module means internal scope and the constant should be accessible from the other file automatically.
-18115356 0You need to check the exit code of every adb statement you are running before moving onto the next
This post here details checking exit codes with bash Bash Beginner Check Exit Status
which includes this (changed for your example)
function test { "$@" status=$? if [ $status -ne 0 ]; then echo "error with $1" exit "$status" fi return $status } test adb shell uiautomator runtest myTest.jar -c com.myTest.TestClass1 test adb shell uiautomator runtest myTest.jar -c com.myTest.TestClass2
You can also tell Jenkins to use bash by adding a shebang to the first line of your script
#!/bin/bash
-23386742 0 XPath is not finding element XPath I created:
.//*[@id='stepCongrats']/div[2]/div[3]/div[2]/ul/li[1]/span
using this xPath I am getting message: NoSuchElementException
Below is my html code:
<div id="stepCongrats"> <div id="ancillary-congratulations"></div> <div id="elephant"></div> <div class="sect"> <div class="s-header"></div> <div class="s-nav"></div> <div class="s-body"> <div class="s-policyholder"></div> <div class="s-policyinfo"> <ul> <li> <h6> Policy number </h6> <span> 247-000-001-13 </span>
-7587080 0 I get mostly 2 calls at the same time (1 for each thread), followed by a one second pause. What is wrong?
That's exactly what you should expect from your implementation. Lets say the time t starts at 0 and the rate is 1:
Thread1 does this:
lock.acquire() # both threads wait here, one gets the lock current_time = time.time() # we start at t=0 interval = current_time - last_time[0] # so interval = 0 last_time[0] = current_time # last_time = t = 0 if interval < rate: # rate = 1 so we sleep time.sleep(rate - interval) # to t=1 lock.release() # now the other thread wakes up # it's t=1 and we do the job
Thread2 does this:
lock.acquire() # we get the lock at t=1 current_time = time.time() # still t=1 interval = current_time - last_time[0] # interval = 1 last_time[0] = current_time if interval < rate: # interval = rate = 1 so we don't sleep time.sleep(rate - interval) lock.release() # both threads start the work around t=1
My advice is to limit the speed at which the items are put into the queue.
-31239515 0Try the following.
Posts.find({"permalink":"udrskijwddhigfwhecxn"},{fields:{"comments":{"$slice":10}}})
The projection in Meteor is specified by fields.
-24001849 0 Dependency Injection / Polymorphism in Objective CCan I use Objective C protocols
the same way I would use Java interfaces
for Dependency Injection or Polymorphism?
It seems like I cannot. Note that in (1) below I have to type the property as the implementation rather than as the protocol. I get a compiler error if I use the protocol as the property
type.
(1) The object to have dependencies injected into:
#import <Foundation/Foundation.h> #import "FOO_AccountService.h" #import "FOO_BasicAccountService.h" @interface FOO_ServiceManager : NSObject @property (nonatomic, strong) FOO_BasicAccountService <FOO_AccountService> *accountService; ... @end
(2) The protocol:
#import <Foundation/Foundation.h> #import "FOO_Service.h" @protocol FOO_AccountService <FOO_Service> ... @end
(3) The implementation:
#import <Foundation/Foundation.h> #import "FOO_BasicService.h" #import "FOO_AccountService.h" @interface FOO_BasicAccountService : FOO_BasicService <FOO_AccountService> ... @end
-37650742 0 You can find the 3d convex hull of all the vertex. Using the points of the convex hull you can form the faces of the convex hull. Then incline one by one all the faces parallel to x-axis. Then find the min x/y/z and max x/y/z along each face rotation.Calculate the volume using min x/y/z and max x/y/z. Find the index corresponding to the minimum volume. Rotate back this volume using the rotation you used for the corresponding face. This problem is similar to the 2d problem of minimum area rectangle. For minimum area rectangle the reference is http://gis.stackexchange.com/questions/22895/how-to-find-the-minimum-area-rectangle-for-given-points
-38806433 0 Why cant i use this code to use digital signature on my file?$lol = system("sudo gpg --clearsign asd.txt;");
Is it because I need the password for the gpg??
sudoers:
root ALL=(ALL) NOPASSWD:ALL
apache ALL=(ALL) NOPASSWD:ALL
www-data ALL=(ALL) NOPASSWD:ALL
-4557738 0Function specialization is weird and almost non-existent. It's possible to fully specialize a function, while retaining all types - i.e. you're providing a custom implementation of some specialization of the existing function. You can not partially specialize a templated function.
It's likely that what you're trying to do can be achieved with overloading, i.e.:
template <typename T> T foo(T arg) { return T(); } float foo(int arg) { return 1.f; }
-33080812 0 For a PA to be deterministic it must follow at least the following rule:
If there is an epsilon transition from a state q, there must not be any alphabet transition from that state.
So in your case, if there isn't any other rule, the PA is deterministic.
-19692339 0 Java button and listener not working in syncTrying to add a button to an already made program in JAVA. It converts temperature from Fahrenheit to celsius. My button won't show up. I'm missing something. The idea is that you will be able to both press enter or the button to have a result. There's the main part of the program:
import javax.swing.JFrame; public class Fahrenheit { public static void main (String[] args) { JFrame frame = new JFrame ("Fahrenheit"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); FahrenheitPanel panel = new FahrenheitPanel(); frame.getContentPane().add(panel); frame.pack(); frame.setVisible(true); frame.getContentPane().add(panel); frame.pack(); frame.setVisible(true); } }
Then in a separate file:
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class FahrenheitPanel extends JPanel { private JLabel inputLabel, outputLabel, resultLabel; private JButton push; private JTextField fahrenheit; //----------------------------------------------------------------- // Constructor: Sets up the main GUI components. //----------------------------------------------------------------- public FahrenheitPanel() { inputLabel = new JLabel ("Enter Fahrenheit temperature:"); outputLabel = new JLabel ("Temperature in Celsius: "); resultLabel = new JLabel ("---"); fahrenheit = new JTextField (5); fahrenheit.addActionListener (new TempListener()); add (inputLabel); add (fahrenheit); add (outputLabel); add (resultLabel); //Here's some button code push = new JButton ("Push!!!"); push.addActionListener (new ButtonListener()); add (push); setPreferredSize (new Dimension(300, 75)); setBackground (Color.red); } private class ButtonListener implements ActionListener { private class TempListener implements ActionListener { //-------------------------------------------------------------- // Performs the conversion when the enter key is pressed in // the text field. //-------------------------------------------------------------- public void actionPerformed (ActionEvent event) { int fahrenheitTemp, celsiusTemp; String text = fahrenheit.getText(); fahrenheitTemp = Integer.parseInt (text); celsiusTemp = (fahrenheitTemp-32) * 5/9; resultLabel.setText (Integer.toString (celsiusTemp)); } } } }
-33760227 0 How to configure Frag3 to treat packages as Windows packages on a specyfic hosts? For example I have host addresses: 3.3.3.3 and 3.3.3.33. How to configure Frag3 preprocessor to treat packages that goes to those adressess like/with a typical Windows defragmentation politics?
-31141319 0Fix your gradle file the following way
defaultConfig { applicationId "package.com.app" minSdkVersion 8 //this should be lower than your device targetSdkVersion 21 versionCode 1 versionName "1.0" }
-37652386 0 I have done the same for my application. So here a brief overview what i have done:
Save the data (C#/Kinect SDK):
How to save a depth Image:
MultiSourceFrame mSF = (MultiSourceFrame)reference; var frame = mSF.DepthFrameReference.AcquireFrame(); if (frame != null ) { using (KinectBuffer depthBuffer = frame.LockImageBuffer()) { Marshal.Copy(depthBuffer.UnderlyingBuffer, targetBuffer,0, DEPTH_IMAGESIZE); } frame.Dispose(); }
write buffer to file:
File.WriteAllBytes(filePath + fileName, targetBuffer.Buffer);
For fast saving think about a ringbuffer.
ReadIn the data (Matlab)
how to get z_data:
fid = fopen(fileNameImage,'r'); img= fread(fid[IMAGE_WIDTH*IMAGE_HEIGHT,1],'uint16'); fclose(fid); img= reshape(img,IMAGE_WIDTH,MAGE_HEIGHT);
how to get XYZ-Data:
For that think about the pinhole-model-formula to convert uv-coordinates to xyz (formula).
To get the cameramatrix K you need to calibrate your camera (matlab calibration app) or get the cameraparameters from Kinect-SDK (var cI= kinectSensor.CoordinateMapper.GetDepthCameraIntrinsics();
).
coordinateMapper
with the SDK:
The way to get XYZ from Kinect SDK directly is quite easier. For that this link could help you. Just get the buffer by kinect sdk and convert the rawData with the coordinateMapper
to xyz. Afterwards save it to csv or txt, so it is easy for reading in matlab.
How can I reinitialize a timeval struct from time.h?
I recognize that I can reset both of the members of the struct to zero, but is there some other method I am overlooking?
-27142253 0 Include parent page slug in permalink for postsI have created a page called Blog and set it as the blog posts page from the wordpress settings.when I create the posts and publish the url structure is like
mysite.com/postname
i would like it to be like
mysite.com/blog/postname
so i edited the custom permalink structure to
mysite.com/blog/%postname%/
which is working.But i have another custom post type called Work now the permlink structure for work goes like
mysite.com/blog/work/workname
it was
mysite.com/work/workname
before i edited the permalink custom structure.
Is there any help to make it the way i want.ie..
mysite.com/blog/postname
&
mysite.com/work/workname
Please help Thanks!!
Edit
my website is
http://jointviews.com/blog/work/best-school-bus-tracking-system/
http://jointviews.com/blog/building-long-term-relationships-with-customers-using-digital-media/
i have register the post type as follows
function work_register() { $labels = array( 'name' => _x('Work', 'post type general name'), 'singular_name' => _x('Work Item', 'post type singular name'), 'add_new' => _x('Add New', 'work item'), 'add_new_item' => __('Add New Work Item'), 'edit_item' => __('Edit Work Item'), 'new_item' => __('New Work Item'), 'view_item' => __('View Work Item'), 'search_items' => __('Search Work'), 'not_found' => __('Nothing found'), 'not_found_in_trash' => __('Nothing found in Trash'), 'parent_item_colon' => '' ); $args = array( 'labels' => $labels, 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'query_var' => true, 'menu_icon' => get_stylesheet_directory_uri() . '/article16.png', 'rewrite' => true, 'capability_type' => 'post', 'hierarchical' => true, 'menu_position' => null, 'supports' => array('title','editor','thumbnail') ); register_post_type( 'work' , $args ); //register_taxonomy("categories", array("work"), array("hierarchical" => true, "label" => "Categories", "singular_label" => "Category", "rewrite" => true)); }
-5362375 0 I am not completely sure what you want to achieve, exactly. But you can do something like:
IsHandled = ev => { ev(this, args); return args.Handled; };
Even though I am not sure this is more readable, faster, cleaner, or anything like that. I would just go with something like
if (ErrorConfiguration != null) ErrorConfiguration(this, args); if (!args.Handled) error(this, args);
-38164308 0 Debug mex code using visual studio Hi I have written a mex file and I would like to debug it using visual studio 2010. I followed steps mentioned in Mathwork website :
http://www.mathworks.com/help/matlab/matlab_external/debugging-on-microsoft-windows-platforms.html
I have also read following posts:
how to debug MATLAB .mex32/.mex64 files with Visual Studio 2010
I should mention that I can compile mex with -g code successfully but when I insert the breakpoint it says: the breakpoint cannot be currently hit. No symbols have been loaded for this document.
Then when I run the mex code from Matlab, it does not create any break point and it does not do the debugging.
According to the following : Fixing "The breakpoint will not currently be hit. No symbols have been loaded for this document." When I go to debug--> windows--> module--> next to matlab says cannot find or open the PDB file. I do not understand what he means when he says
" In normal projects, the assembly and its .pdb file should always have been copied by the IDE into the same folder as your .exe. The bin\Debug folder of your project. Make sure you remove one from the GAC if you've been playing with it."
my Matlab is located in C:\Program Files\MATLAB\R2012a and the mex and pdb file is in C:\Documents\Matlab file but I copied the pdb file (I do not know it is necessary or not) to Matlab workspace. The Matlab current folder that code is running is also C:\Documents\Matlab. Can anyone please help me to solve this problem.
Can anyone please hel me to solve this problem?
-16463874 0 Create a larger matrix in special caseI have two vectors:
A=[1 2 3 4] B=[3 5 3 5]
I want to find a matrix from these vectors like this:
you can suppose that c
is a plot matrix
, where the x-axis is A
and y-axis
is B
:
c = 0 4 0 4 3 0 3 0 0 0 0 0 0 0 0 0
or:
c1= 0 1 0 1 1 0 1 0 0 0 0 0 0 0 0 0
My question is how to create it automatically because I have large vectors.
-36364796 0 __weak typeof(self) weakSelf = self OR __weak MyObject *weakSelf = self?What is preferable to use here and why?
__weak typeof(self) weakSelf = self;
or
__weak MyObject *weakSelf = self;
Obviously, __weak id weakSelf = self;
would be the least desirable, as we would not get type checking, is that correct?
However, between the first two... which is desirable and why?
Also, any reason to use __typeof instead of typeof, if clang supports using typeof?
-17625315 0When installing rancid, clogin was placed in /usr/lib/rancid/bin/clogin
, which wasn't in my path. It still runs from the command line just fine, though.
I had to create my own ~/.cloginrc file, and chmod 700 ~/.cloginrc
before it would let me run the command.
This was on Ubuntu 12.04.
A basic run-through, I installed it via apt-get install rancid
. Then I had to add these lines to my (non-existent) ~/cloginrc:
add user 192.168.11.1 admin add password 192.168.11.1 MyPassword
Then at the command line, I typed:
/usr/lib/rancid/bin/clogin 192.168.11.1
It performed the login process for me, based on the IP address.
That's pretty much it, though I might point out you could even leave your .cloginrc
empty and just type /usr/lib/rancid/bin/clogin -u admin -p MyPassword 192.168.11.1
instead.
Here is a sample ~/.cloginrc
from their GitHub:
https://github.com/dotwaffle/rancid-git/blob/master/cloginrc.sample
-1356260 0You can use JavaScript with a little help from jQuery Library to post to an .aspx page. I wrote an example for PHP here http://stackoverflow.com/questions/1353678. The javascript part would stay the same, but on the server side you would have to read the query string to read in the variables using Request.querystring. Also If you want to return JSON data you will have to change the response type to be plain text rather HTML. Like this:
context.Response.ContentType = "text/plain";
-16030417 0 Forget about performance in this comparison; it would take a truly massive enum for there to be a meaningful performance difference between the two methodologies.
Let's focus instead on maintainability. Suppose you finish coding your Direction
enum and eventually move on to a more prestigious project. Meanwhile, another developer is given ownership of your old code including Direction
- let's call him Jimmy.
At some point, requirements dictate that Jimmy add two new directions: FORWARD
and BACKWARD
. Jimmy is tired and overworked and does not bother to fully research how this would affect existing functionality - he just does it. Let's see what happens now:
1. Overriding abstract method:
Jimmy immediately gets a compiler error (actually he probably would've spotted the method overrides right below the enum constant declarations). In any case, the problem is spotted and fixed at compile time.
2. Using a single method:
Jimmy doesn't get a compiler error, or even an incomplete switch warning from his IDE, since your switch
already has a default
case. Later, at runtime, a certain piece of code calls FORWARD.getOpposite()
, which returns null
. This causes unexpected behavior and at best quickly causes a NullPointerException
to be thrown.
Let's back up and pretend you added some future-proofing instead:
default: throw new UnsupportedOperationException("Unexpected Direction!");
Even then the problem wouldn't be discovered until runtime. Hopefully the project is properly tested!
Now, your Direction
example is pretty simple so this scenario might seem exaggerated. In practice though, enums can grow into a maintenance problem as easily as other classes. In a larger, older code base with multiple developers resilience to refactoring is a legitimate concern. Many people talk about optimizing code but they can forget that dev time needs to be optimized too - and that includes coding to prevent mistakes.
Edit: A note under JLS Example §8.9.2-4 seems to agree:
-7162895 0Constant-specific class bodies attach behaviors to the constants. [This] pattern is much safer than using a
switch
statement in the base type... as the pattern precludes the possibility of forgetting to add a behavior for a new constant (since the enum declaration would cause a compile-time error).
You can solve this using MultiDataTriggers. Just make sure that you place them in the correct order, as I recall, the last trigger that meets all criteria takes precedence.
-39581342 0 #if - #else - #endif breaking F# ScriptUsing Visual Studio 2015 Update 3 and fsi.exe
from F# v4.0 I' trying to run this script:
//error.fsx #if INTERACTIVE let msg = "Interactive" #else let msg = "Not Interactive" #endif let add x y = x + y printfn "%d" (add 1 2)
Output: error.fsx(12,15): error FS0039: The value or constructor 'add' is not defined
If I then comment out the #if
-#else
-#endif
block, it works fine:
// fixed.fsx //#if INTERACTIVE // let msg = "Interactive" //#else // let msg = "Not Interactive" //#endif let add x y = x + y printfn "%d" (add 1 2)
Output: 3
I'm sure I'm doing something wrong (rather than this being a bug) but I can't for the life of me figure out how to make this work.
Thoughts?
-33477519 0 Oracle Column Not Allowed Here Default ValueThe problem is about the DEFAULT value using a sequence on line 4.
CREATE OR REPLACE SEQUENCE CHANNEL_SEQ START WITH 1 INCREMENT BY 1; CREATE TABLE "CHANNEL" ( "ID_CHANNEL" NUMBER(18,0) DEFAULT CHANNEL_SEQ.NEXTVAL, "IS_ACTIVE" VARCHAR2(1 CHAR) NOT NULL, "BATCH_SIZE" NUMBER(3,0) NOT NULL, "MAX_DOCS_IN_PROCESS" NUMBER(4,0) NOT NULL, "RECEIVER_ID" NUMBER(18,0) NOT NULL, "LAST_POS_SESSION_TIME" DATE, CONSTRAINT "PK_CHANNEL" PRIMARY KEY ("ID_CHANNEL"), CONSTRAINT "FK_RECEIVER_ID_CHANNEL" FOREIGN KEY ("RECEIVER_ID") REFERENCES "MSG_OUT"("MSG_OUT_ID"), CONSTRAINT "CHK_IS_ACTIVE" CHECK (IS_ACTIVE IN ('Y', 'N')) );
The error messages are :
"SQL Error: ORA-00984: column not allowed here"
All help and hints are welcome.
-13832020 0When you put inverted commas round something it makes it into a string, so 'month'
means the word this, whereas month
means the value in the variable called month.
Your program will stop giving you that particular error if you remove the '
s:
D = input() A = ( (14 - month) /12) Y = ( Year - A ) MonthProblem = ( month + 12 * A - 2 ) week = ( (D + Y + Y/4 - Y/100 + Y/400 + 31 * MonthProblem/12) % 7 )
Had you defined the values of month
etc before?
if max_oms
is a parameter
(i.e. a constant, and it probably is one) you can do:
CHARACTER(LEN=20) :: filename(max_xoms,2) = RESHAPE(SOURCE=(/'XobsXOM0.txt','XobsXOM1.txt','XobsXOM2.txt','XobsXOM3.txt','XobsXOM4.txt', & 'XobsXOM5.txt','XobsXOM6.txt','XobsXOM7.txt','XobsXOM8.txt','XobsXOM9.txt', & 'XobsXOS0.txt','XobsXOS1.txt','XobsXOS2.txt','XobsXOS3.txt','XobsXOS4.txt', & 'XobsXOS5.txt','XobsXOS6.txt','XobsXOS7.txt','XobsXOS8.txt','XobsXOS9.txt'/), & SHAPE=(/max_xoms,2/))
otherwise move
filename = RESHAPE(SOURCE=(/'XobsXOM0.txt','XobsXOM1.txt','XobsXOM2.txt','XobsXOM3.txt','XobsXOM4.txt', & 'XobsXOM5.txt','XobsXOM6.txt','XobsXOM7.txt','XobsXOM8.txt','XobsXOM9.txt', & 'XobsXOS0.txt','XobsXOS1.txt','XobsXOS2.txt','XobsXOS3.txt','XobsXOS4.txt', & 'XobsXOS5.txt','XobsXOS6.txt','XobsXOS7.txt','XobsXOS8.txt','XobsXOS9.txt'/), & SHAPE=(/max_xoms,2/))
to the position of a first executable statement.
Generally, avoid DATA
in Fortran 90 and later.
I'd like to know how to use strtok
to find values, so is this possible to use strtok(mystring, "")
or no?
I want split this : mystring
--> %3456
I want split into 2 parts : "%"
and "3456"
. Is this possible? how can I do that?
I am trying to grep ip addresses from one file and remove the contents of the grep from a second file with a single command.
The masterfile has
header x.x.x.x header x.x.x.x header2 y.y.y.y header2 y.y.y.y header3 z.z.z.z header3 z.z.z.z
The tempfile has
x.x.x.x x.x.x.x y.y.y.y y.y.y.y z.z.z.z z.z.z.z
Attempt
grep "header" masterfile | sed 's/^.* //' | sed -i "" '/$/d' tempfile
Would also like to remove the empty line after the sed command removes an entry.
-18724237 0 Collection was modified error when looping through list and removing itemsI have the following:
tempLabID = lstLab; foreach (string labID in lstLab) { if (fr.GetFileRecipients(fsID).Contains(labID)) { tempLabID.Remove(labID); } }
When I debug and watch lstLab and I get to tempLabID.remove() it changes lstLab to 0 from 1, and then in turn, when it gets back to the foreach I get an error saying the collection has been modified.
I can't understand why it's happening. I am modifying a different collection.
-13469787 0 How to specify page size in dynamically in yii view?How to specify page size in dynamically in yii view?(not a grid view) In my custom view page there is a search option to find list of users between 2 date i need 2 know how to specify the page size dynamically? If number of rows less than 10 how to hide pagination ?
please check screen-shoot
I dont want the page navigation after search it confusing users..
my controller code
$criteria=new CDbCriteria(); $count=CustomerPayments::model()->count($criteria); $pages=new CPagination($count); // results per page $pages->pageSize=10; $pages->applyLimit($criteria); $paymnt_details=CustomerPayments::model()->findAll($criteria); $this->render('renewal',array('paymnt_details'=>$paymnt_details,'report'=>$report,'branch'=>$branch,'model'=>$model,'pages' => $pages,)); }
my view Link
-27944589 0if string is: $str = '"World"';
ltrim()
function will remove only first Double quote.
Output: World"
So instead of using both these function you should use trim()
. Example:
$str = '"World"'; echo trim($str, '"');
Output-
World
-6390650 0 It should just work; I believe the problem is that the attributes are inverted (I will take a note to raise a clearer error in this case) - it should be :
[ProtoContract, ProtoInclude(14, typeof(Update))] class Annoucement { } [ProtoContract] class Update : Announcement { }
i.e. the base needs to know about the descendants. Not I removed the discriminator from serialization, as that is redundant if it relates directly to the object type - it handles this internally via the ProtoInclude
and will create the correct type for you. Each type needs to know only about the direct subtypes, i.e.
A - B - C - D - E - F
here A needs to know about B and D; B needs to know about C; D needs to know about E and F.
Note that a "what is this" enum is a good idea here, but there is no need for it to be a field - a virtual property without a field may be more appropriate. If I have misundersood and the message-type doesn't relate to the object-type, then ignore me ;p
Also: public fields - don't do it. Think of the kittens... It will work, but properties are preferred (in general, I mean; nothing to do with protobuf-net).
-10578609 0 Generic extension method for an array does not compilePopulating a request object for a web-service, I need to dynamically add items to some arrays.
I hoped to simplify it by implementing an extension method:
public static class ArrayExtensions<T> where T : class { public static T[] Extend<T>(T[] originalArray, T addItem) { if (addItem == null) { throw new ArgumentNullException("addItem"); } var arr = new[] { addItem }; if (originalArray == null) { return arr; } return originalArray.Concat(arr).ToArray(); } }
So that this old code:
if (foo.bazArr == null) { foo.bazArr = new[] { baz }; } else { foo.bazArr = new[] { baz }.Concat(foo.bazArr).ToArray(); // (i know this inserts the new item at the beginning, but that's irrelevant, order doesn't matter) }
could be rewritten as:
foo.bazArr = foo.bazArr.Extend(baz); // won't compile
The error is: 'System.Array' does not contain a definition for 'Extend' and no extension method 'Extend' accepting a first argument of type 'System.Array' could be found (are you missing a using directive or an assembly reference?)
Whereas calling the extension method directly like so:
foo.bazArr = ArrayExtensions<someService.bazType>.Extend(foo.bazArr, baz);
compiles fine.
Why is that so? Why can't the compiler infer the type on its own here, if the array is strongly-typed?
EDIT - correct code below:
public static class ArrayExtensions { public static T[] Extend<T>(this T[] originalArray, T addItem) where T : class { if (addItem == null) { throw new ArgumentNullException("addItem"); } var arr = new[] { addItem }; if (originalArray == null) { return arr; } return originalArray.Concat(arr).ToArray(); // although Concat is not recommended for performance reasons, see the accepted answer } }
For this popular question, here's another good simple example:
public static class Extns { // here's an unbelievably useful array handling extension for games! public static T AnyOne<T>(this T[] ra) where T:class { int k = ra.Length; int r = Random.Range(0,k); return ra[r]; // (add your own check, alerts, etc, to this example code) } }
and in use ..
someArrayOfSoundEffects.AnyOne().Play(); someArrayOfAnimations.AnyOne().BlendLeft(); winningDisplay.text = successStringsArray.AnyOne() +", " +playerName; SpawnEnormousRobotAt( possibleSafeLocations.AnyOne() );
and so on. For any array it will give you one random item. Used constantly in games to randomise effects etc. The array can be any type.
-21138303 0I found out what the problem is: Because I'm using D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY
, it does notwork with D3DPOOL_MANAGED. I switched it to D3DPOOL_DEFAULT and it worked.
What does your curl
call look like? You can use subprocess.call()
to run a shell command from a python script.
Here's an example of downloading two images:
script.py
import subprocess data = [ ("homer.jpg", "http://upload.wikimedia.org/wikipedia/en/0/02/Homer_Simpson_2006.png"), ("bart.jpg", "http://upload.wikimedia.org/wikipedia/en/a/aa/Bart_Simpson_200px.png") ] for datum in data: subprocess.call(["curl", "-o", datum[0], datum[1]])
The subprocess.call()
function takes a list of arguments so in my example it translates to running the following commands from a terminal:
curl -o "homer.jpg" "http://upload.wikimedia.org/wikipedia/en/0/02/Homer_Simpson_2006.png"
curl -o "bart.jpg" "http://upload.wikimedia.org/wikipedia/en/a/aa/Bart_Simpson_200px.png"
DS-5 displays only the core registers by default. To display NEON and other system registers, you have to manually add them by either clicking the Browse
Button or typing the name of register in the text box beside Browse
button.
Detailed documentation is available at http://ds.arm.com/developer-resources/ds-5-documentation/arm-ds-5-debugger-user-guide/registers-view
-16675541 0Marmalade EDK is Extension Development Kit of Marmalade SDK, which is a set of tool to bring native functionality of the platform, on which the application is deployed.
The code is written in native supported language, for example for Android it's Java and for iOS it's Objective C.
EDK is currently supported for Android, iOS, Windows and OSX only. There's no support for Windows phone 8 and BB10 yet.
I have about 20 different variables and i want to compare this variables with each other to check weather they are equal or not.
Example
$var1 = 1; $var2 = 2; $var3 = 1; $var4 = 8; . . . $var10 = 2;
Now i want to check...
if($var1 == $var2 || $var1 == $var3 || $var1 == $var4 || ......... || $var2 == $var3 || $var2 == $var4 || ............. || $var8 = $var9 || $var8 == $var10 ||...) { echo 'At-least two variables have same value'; }
I am finding for an easy to do this. Any Suggestions?
-3458570 0Put the tags into an array. Each array being respectively called Post A / Post B etc. Then use array_diff_assoc()
, to figure out how different the arrays are.
But really, Ivars solution would work better, this is easier to understand though :)
-4586806 0Do this:
$(e).find(".myclass").something();
or the slightly shorter, yet less efficient version:
$(".myclass", e).something();
The reason you can't use +
is that your e
is a DOM element, which is not a useful type for concatenation into a selector string, since you end up with something like:
"[object HTMLInputElement] .myclass"
-21955672 0 void move_digits(int a) { int digits = 0; int b = a; while(b / 10 ){ digits++; b = b / 10; } for (int i = 0; i < digits; ++i) { int c = a / 10; int d = a % 10; int res = c + pow(10, digits) * d; printf("%d\n", res); a = res; } printf("\n"); } int main() { move_digits(12345); }
-11269070 0 Assuming you've populated a list of ListIDs (listOfIDs) in a separate query:
var accounts = from a in db.Accounts where !listOfIDs.Contains(a.ListID) select a; db.Accounts.RemoveAll(accounts); db.SubmitChanges();
-18822891 0 If you don't know on which server your database is stored, there's no way we can know it better than you.
According to your comment, your database is on the machine where your code gets executed. Then HOST = localhost
You essentially need to get the row id from the selected ListView item. Using the row id you can easily delete that row:
String where = "_id = " + _id; db.delete(TABLE_NAME, where, null);
After deleting the row item make sure you get the ListView adapter cursor and do a requery. If you don't you will not see the updated table, hence updated ListView.
-17857348 0 Autofiltering records in grid in asp.net according to keywordsI want to search some items in a grid in asp.net C#. While i search for the records that I want to I don't want to hit the search button and then the grid will get filtered. I want that the grid should get filtered with the records that match the keyword that I am entering. I guess this can be done using html5 or j query. I am not able to exactly phrase my search for google.
Pleas help. Thanks in advance.
-40201250 0The problem was solved after I imported CA certificate in JRE certificate store:
keytool -importcert -alias startssl -keystore $JAVA_HOME/jre/lib/security/cacerts -storepass changeit -file ca.der
-2458422 0 Point 1: I think you need at least some quotes around the connection string:
myProcess.StartInfo.Arguments = "/mode:fullgeneration \"/c:"+cs+"\" project:School ...";
But do examine the resulting Arguments string in the debugger to see if everything is allright.
For point 2, see this SO question.
-5193297 0 Mail settings in Web.configIs it possible to set a "to" attribute in the mailSettings
element in the Web.config file?
The Excel object model is fully documented on MSDN. Here is the Excel 2010 Application object. Use the links in the left navigator to view properties and members.
http://msdn.microsoft.com/en-us/library/ff194565.aspx
Move up the navigator tree to Reference to see all the objects.
http://msdn.microsoft.com/en-us/library/ff846392.aspx
-17354168 0 Scanner class is skipping linesI'm new to programing and I'm having a problem with my scanner class. This code is in a loop and when the loop comes around the second, third whatever time I have it set to it skips the first title input. I need help please why is it skipping my title scanner input in the beginning?
System.out.println("Title:"); list[i].title=keyboard.nextLine(); System.out.println("Author:"); list[i].author=keyboard.nextLine(); System.out.println("Album:"); list[i].album=keyboard.nextLine(); System.out.println("Filename:"); list[i].filename=keyboard.nextLine();
-20145535 0 Code -
drop table #a drop table #b select * into #a from [databasename1].information_schema.columns a --where table_name = 'aaa' select * into #b from [databasename2].information_schema.columns b -- add linked server name and db as needed --where table_name = 'bbb' select distinct( a.table_name), b.TABLE_SCHEMA+ '.' + (b.table_name) TableName,b.TABLE_CATALOG DatabaseName from #a a right join #b b on a.TABLE_NAME = b.TABLE_NAME and a.TABLE_SCHEMA = b.TABLE_SCHEMA where a.table_name is null-- and a.table_name not like '%sync%'
-4877342 0 fields: [{name: 'Time', mapping: 'Time', type: 'int'}] fields: [{name: 'Time', type: 'int'}]
BTW In the case of an identity mapping you can leave it out. These two cases will give you the same results.
-15540379 0Using the Scala debugger
through the remote connector works.
But if you want to avoid to go back and forth between sbt
and Eclipse
, you can load your project in Scala IDE
using sbteclipse, and then run your specs2 tests from inside Scala IDE
, in debug mode, using the JUnit launcher.
setTimeout(function() { window.location.href = "/NewPage.aspx"; }, 2000);
.wrapper { background-color: red; width: 100%; -webkit-animation-name: example; /* Chrome, Safari, Opera */ -webkit-animation-duration: 2s; /* Chrome, Safari, Opera */ animation-name: example; animation-duration: 2s; } @-webkit-keyframes example { 0% { opacity: 100; filter: alpha(opacity=1000); /* For IE8 and earlier */ } 100% { opacity: 0.0; filter: alpha(opacity=0); /* For IE8 and earlier */ } } /* Standard syntax */ @keyframes example { 0% { opacity: 100; filter: alpha(opacity=1000); /* For IE8 and earlier */ } 100% { opacity: 0.0; filter: alpha(opacity=0); /* For IE8 and earlier */ } }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class='wrapper'> <div>Home Page</div> </div>
There's a new project, NLib, which can do this much faster:
if (input.IndexOfNotAny(new char[] { 'y', 'm', 'd', 's', 'h' }, StringComparison.OrdinalIgnoreCase) < 0) { // Valid }
-35867617 0 jqGrid add buttons for add/edit/delete in toolbar not working I have tried to implement the code for adding buttons in jqGrid toolbar from the example site http://www.guriddo.net/demo/bootstrap/ but I'm surprised to find that it isn't working for me. Searched for a couple of hours but I can't figure it out. Here is my code:
<script type="text/javascript"> $(function () { var gridDataUrl = '@Url.Action("JsonCategories", "AdminNomCategory")' var grid = $("#reportsGrid").jqGrid({ url: gridDataUrl, datatype: "json", mtype: 'POST', colNames: [ '@Html.DisplayNameFor(model => model.CategoryGuid)', '@Html.DisplayNameFor(model => model.CategoryName)', '@Html.DisplayNameFor(model => model.CategoryDescription)' ], colModel: [ { name: 'CategoryGuid', index: 'CategoryGuid', width: 10, align: 'left', classes: "nts-grid-cell", hidden: true }, { name: 'CategoryName', index: 'CategoryName', width: 10, align: 'left', classes: "nts-grid-cell" }, { name: 'CategoryDescription', index: 'CategoryDescription', width: 10, align: 'left', classes: "nts-grid-cell" } ], rowNum: 20, rowList: [10, 20, 30], height: 450, width: 1140, pager: '#pager', /*jQuery('#pager'),*/ sortname: 'CategoryGuid', toolbarfilter: true, viewrecords: true, sortorder: "asc", caption: "Categories", ondblClickRow: function (rowid) { var gsr = jQuery("#reportsGrid").jqGrid('getGridParam', 'selrow'); if (gsr) { var CategoryGuid = grid.jqGrid('getCell', gsr, 'CategoryGuid'); window.location.href = '@Url.Action("Edit", "AdminNomCategory")/' + CategoryGuid } else { alert("Please select Row"); } }, @*onSelectRow: function (rowid) { var gsr = jQuery("#reportsGrid").jqGrid('getGridParam', 'selrow'); if (gsr) { var CategoryGuid = grid.jqGrid('getCell', gsr, 'CategoryGuid'); window.location.href = '@Url.Action("Edit", "AdminNomCategory")/' + CategoryGuid } else { alert("Please select Row"); } }*@ }); //jQuery("#reportsGrid").jqGrid('navGrid', '#pager', { edit: true, add: true, del: true }); var template = "<div style='margin-left:15px;'><div> Customer ID <sup>*</sup>:</div><div> {CustomerID} </div>"; template += "<div> Company Name: </div><div>{CompanyName} </div>"; template += "<div> Phone: </div><div>{Phone} </div>"; template += "<div> Postal Code: </div><div>{PostalCode} </div>"; template += "<div> City:</div><div> {City} </div>"; template += "<hr style='width:100%;'/>"; template += "<div> {sData} {cData} </div></div>"; $('#reportsGrid').navGrid('#pager', // the buttons to appear on the toolbar of the grid { edit: true, add: true, del: true, search: false, refresh: false, view: false, position: "left", cloneToTop: false }, //// options for the Edit Dialog { editCaption: "The Edit Dialog", template: template, errorTextFormat: function (data) { return 'Error: ' + data.responseText } }, // options for the Add Dialog { template: template, errorTextFormat: function (data) { return 'Error: ' + data.responseText } }, // options for the Delete Dailog { errorTextFormat: function (data) { return 'Error: ' + data.responseText } } ); grid.jqGrid('filterToolbar', { searchOnEnter: true, enableClear: false }); jQuery("#pager .ui-pg-selbox").closest("td").before("<td dir='ltr'>Rows per page </td>"); grid.jqGrid('setGridHeight', $(window).innerHeight() - 450); }); $(window).resize(function () { $('#reportsGrid').jqGrid('setGridHeight', $(window).innerHeight() - 450); }); </script>
I am using jqGrid 4.4.4 and ASP.NET. The thing I noticed, is that on the example page, the buttons are located inside a div with an id like 'jqGridPagerLeft', but on my page, that div has no id. So I went looking inside the jqGrid source but I'm lost and I can't figure out why it doesn't have an id allocated.
Any clues? I just want to add the buttons to the bottom toolbar. Thx!
-12756918 0As Ahmad says, you need to compile your code with API Level 14 in order to use the constant "ICE_CREAM_SANDWICH". The thing is that at compilation time those constants are changed into their respective values. That means that at runtime any device won't see the "ICE_CREAM_SANDWICH" constant but the value 14 (even if it is a device with Froyo 2.2 installed).
In other words, in your code:
Integer version = Build.VERSION_CODES.ICE_CREAM_SANDWICH;
in the device:
Integer version = 14;
It is not exactly like that, but you get the idea.
-13158927 0Persistent login are not possible with Apps Script as Apps Script can not interact with browser objects like cookies etc. Apps Script is intended to work only with Google Accounts.
-10560872 0If you really want to do it in Goliath I'd suggest creating a plugin and doing it in there. Create a queue in the config and have the plugin pop items from the queue and send the mail.
-36549504 0The problem is that when more elements are added to a vector it may resize itself. When this happens all elements are moved to a new location and all existing pointers and references to elements get invalidated.
There are containers that do not invalidate iterators when new elements are added, such as std::list
and boost::stable_vector
.
I.e. boost::stable_vector<Segment>
or std::list<Segment>
instead of std::stable<Segment>
would fix the issue, provided you do not require contiguous storage of Segment
elements.
Would a slightly different structure of global app state help you? For example:
const appState = { subApps: { subApp1: {}, subApp2: {}, // etc. }, currentSubApp: 'subApp2', }; const subApp2State = appState.subApps[appState.currentSubApp];
On the other hand, if your subApps are completely independent of the parent-app, you could let them use whatever structure they want (their own redux store for example, different from the one of the parent-app) and simply integrate them in React wrapper-components, like this:
import SubApp from '...anywhere...'; const SubAppWrapper = React.createClass({ componentDidMount: function() { this.subApp = new SubApp({ containerElement: this.refs.containerDiv, // other params }); }, componentWillUnmount: function() { this.subApp.destroy(); }, render: function() { return ( <div ref="containerDiv"></div> ); }, });
-11262031 0 kohana view from what controller? I have a view that could be called from any of 3 actions from one controller. But, that view should be slightly different depending on what action caused it (it should display 3 icons or 2 or one depending on action called). Can I check in the view what action caused it so I can use if statement to check whether display each icon or not?
Thank you.
-36434512 0you can use ROW_NUMBER
;with cte as ( select x.pt_year, x.pt_month, x.pt_amount, y.fp_earnedprem from ( select sum(a.amount) as pt_amount , va.ACCT_YEAR as pt_year, va.ACCT_MONTHINYEAR as pt_month, ptp.PTRANS_CODE as pt_code from fact_policytransaction a join VDIM_ACCOUNTINGDATE va on a.ACCOUNTINGDATE_ID=va.ACCOUNTINGDATE_ID join DIM_POLICYTRANSACTIONTYPE ptp on a.POLICYTRANSACTIONTYPE_ID=ptp.POLICYTRANSACTIONTYPE_ID group by va.ACCT_YEAR, va.ACCT_MONTHINYEAR, ptp.PTRANS_CODE ) as x join ( select sum(fp.EARNED_PREM_AMT) as fp_earnedprem , dm.MON_YEAR as fp_year, dm.MON_MONTHINYEAR as fp_month from fact_policycoverage fp join dim_month dm on fp.MONTH_ID=dm.MONTH_ID group by dm.MON_YEAR, dm.MON_MONTHINYEAR ) as y on x.pt_year = y.fp_year and x.pt_month = y.fp_month where x.pt_year=2016 and x.pt_month=6 ) , Rn as ( select * , ROW_NUMBER() over (partition by pt_year, pt_month order by pt_year, pt_month) as RoNum from cte ) select pt_year, pt_month, pt_amount , IIF(RoNum = 1, fp_enarnedprem, 0) from Rn order by pt_year, pt_month
the main part is your own query, I only added below section and a line on top and moved order by to the bottom.
) , Rn as ( select * , ROW_NUMBER() over (partition by pt_year, pt_month order by pt_year, pt_month) as RoNum from cte ) select pt_year, pt_month, pt_amount , IIF(RoNum = 1, fp_enarnedprem, 0) from Rn order by pt_year, pt_month
-24354951 0 The problem with the current code isn't completely clear to me as I don't know what doesn't happen what should happen or vice versa. So I'm still guessing a bit. But I see you are not implementing viewForHeaderInSection which is what I would use to implement custom headers. Also I think you need heightForHeaderInSection set to something different than 0 (obviously).
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { // Simple on the fly generated UIView, you could also return your own subclass of UIView UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 18)]; UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, tableView.frame.size.width, 18)]; [label setFont:[UIFont boldSystemFontOfSize:12]]; label.text = [arrHeaders objectAtIndex:section]; return view; } - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section; { // Should be same as UIView that you return in previous function return 18.0f; }
-2736978 0 Ok, finally I got it running by making the models closer to what I wanted to present to the user. But related to the topic of the question :
1) Nested forms/formsets are not a built-in Django feature, are a pain to implement by yourself, and are actually not needed... Rather, one should use forms' and formsets' prefixes.
2) Trying to work with forms not based on the models, process the data, then reinject it in the models, is much much more code than modifying the models a little bit to have nice model-based forms. So what I did is I modified the models like that :
class PortConfig(Serializable): port = models.ForeignKey(Port, editable=False) machine = models.ForeignKey("vmm.machine", editable=False) is_open = models.CharField(max_length=16, default="not_open", choices=is_open_choices) class Rule(Serializable): ip_source = models.CharField(max_length=24) port_config = models.ForeignKey(PortConfig)
Then I simply used a "model formset" for PortConfig
, and "model inline formset" for Rule
, with a PortConfig
as foreign key, and it went perfectly
3) I used this great JS library http://code.google.com/p/django-dynamic-formset/ to put the "add field" and "delete field" links ... you almost have nothing to do.
-15932162 0I believe this works and is the canonical repository of this kind of info. (If it doesn't, the page should be fixed!)
Yes, you can use gdb remotely.
To see printf output, try chrome:://system and expanding the ui_log.
-6097793 0 Can't "unselect" listview itemI was able to get the background changed of an individual listview item in a setOnItemClickListener with
view.setBackgroundResource(R.color.green);
I only need one selected at a time so when the other list items are clicked, I tried lv.invalidate()
and lv.getChildAt(0).invalidate()
but neither worked and the second causes null pointer exception. Any ideas for putting the color back?
You can use String#sub
to replace it:
'15%'.sub('%', '') #=> '15'
-14079373 0 can we Increase Netty Server performance by using limiting thread pool Can anybody help me to fix the correct thread pool size a according to the processor and RAM.
Can we fix the limit of worker thread for better performance ?
-30513908 0In Visual Studio 2013, and using googletest with the GoogleTestRunner extension: I couldn't properly debug via the Test Explorer's "Debug this test" menu. I had to debug into the unit test project's executable itself (right click on unit test project, hit Debug).
By "not properly debug" I mean: I was able to stop at a breakpoint, and see a data value by hovering over a variable in the code window - but I didn't get any typical debugger windows (call stack, autos, locals, modules, etc.) nor were there any such windows available under the Debug/Windows menu item!
Not sure if this is your problem, since you didn't specify whether you're using Visual Studio's built-in native C++ unit tests or not. But I believe it might be an issue with running tests inside the Test Explorer.
-446336 0Both of the big OSS DB's (MySQL and PostgreSQL) can scale to extremely large sites. The trick would be to plan from the start such that data can be broken up ("shard") into multiple DB servers and you can quickly find out which server you need to go to.
For example: users having nickname A-G go to server1, H-O to server2, etc. This way you can scale almost infinitely because when a server reaches the limit, you can just split it into smaller pieces.
-10240031 0Per the language spec, section 15.10:
"An array creation expression creates an object that is a new array whose elements are of the type specified by the PrimitiveType or ClassOrInterfaceType. It is a compile-time error if the ClassOrInterfaceType does not denote a reifiable type."
And per the language spec, section 4.7:
Because some type information is erased during compilation, not all types are available at run time. Types that are completely available at run-time are known as reifiable types.
A type is reifiable if and only if one of the following holds:
- It refers to a non-generic class or interface type declaration.
...
So put simply, "because the language says you can't". I understand the ultimate cause dealt with maintaining backward compatibility, but I'm not familiar with the details.
-40453328 0new_cards = [p if p in usr_card else 'removed' for deck in cards for p in deck]
should do it, although may need a bit of tweaking depending what exactly is going on in your code, I'm not too clear.
Let me recommend you a different, more efficient way to easily hook your keyboard:
First, use DllImport and PINvoke inorder to import GetASyncKeyState:
[DllImport("user32.dll")] static extern short GetAsyncKeyState(System.Windows.Forms.Keys vKey);
Then, you can just use the above function as you wish, such as:
public static bool IsKeyPushedDown(System.Windows.Forms.Keys vKey) { return 0 != (GetAsyncKeyState((int)vKey) & 0x8000); }
Best of luck.
EDIT: btw, If you want to use a barcode reader, you can also create one of your own, or take a look here or here.
-14695549 0Further to Ryan's point, you can see some info on using the bootstrap page on developerworks, you'll want to look at the views example gadget. Unfortunately you can only open a dialog in Connections, the EE style flyout is not available to gadgets on My Page.
-39700407 0Inserting some HTML content into a div
makes your arbitrary HTML automatically evaluated. What you should do instead is to parse your HTML string with something like this.
(defn parse-html [html] "Parse an html string into a document" (let [doc (.createHTMLDocument js/document.implementation "mydoc")] (set! (.-innerHTML doc.documentElement) html) doc ))
This is plain and simple ClojureScript, maybe using the Google Closure library would be more elegant if you want you can dig into the goog.dom namespace or someplace else inside the Google Closure API.
Then you parse your HTML string:
(def html-doc (parse-html "<body><div><p>some of my stuff</p></div></body>"))
So you can call Enfocus on your document:
(ef/from html-doc :mystuff [:p] (ef/get-text))
Result:
{:mystuff "some of my stuff"}
-38193571 0 I'm not exactly sure what would have caused your problem, however is is most likely due to a css/html nesting problem, where multiple css styles interact with the nested elements differently on different browsers? It is better to simply remove the button element in the html and just style the <a>
tag to look like a button. By doing this the code is less complicated, you should have fewer problems with styles and nested elements, and this is how most make link buttons anyway. Here is an example of how I made a link button in a recent project, some of the stylings are missing (custom fonts, etc) but it shows that you don't need the button tag, it works better without it, and how to make a button with just the <a>
tag.
.btn:link, .btn:visited { display: inline-block; padding: 10px 30px; font-weight: 300; text-decoration: none; color: white; border-radius: 200px; border: 3px solid #1A75BB; margin: 20px 20px 0px 0px; transition: background-color 0.2s, border-color 0.2s, color 0.2s; } .btn:hover, .btn:active { background-color: #14598e; border-color: #14598e; } .btn-full:link, .btn-full:visited { background-color: #1A75BB; margin-right: 20px; } .btn-full:hover, .btn-full:active { background-color: #14598e; } .btn-ghost:link, .btn-ghost:visited { color: black; border-color: #14598e; } .btn-ghost:hover, .btn-ghost:active { color:white; }
<a href="#section-one" class="btn btn-full">Why use AnyMath?</a> <a href="#section-two" class="btn btn-ghost">What problems can AnyMath solve?</a>
$("body")[0]; $("body").get(0);
Those both should get the DOM object from jQuery.
-4006096 0I don't see you doing anything wrong. I can't test this, don't have the setup right now. Bounds is a bit tricky, there's a bunch of code behind it that ensures that the form can't be displayed off-screen. As an alternative, you could set the Location property instead and override OnLoad() in SnippingTool to set the WindowState property.
-11919033 0 Why do I need to call removeView() in order to add a View to my LinearLayoutI am getting this error but I am not sure exactly why:
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
The part where I add the View is the line that the error is pointing to. I am providing my Adapter code in order for you guys to get a better picture of what I am doing and why I am getting this error. Please let me know if anymore info is needed. Thanks in advance.
Adapter
private class InnerAdapter extends BaseAdapter{ String[] array = new String[] {"12\nAM","1\nAM", "2\nAM", "3\nAM", "4\nAM", "5\nAM", "6\nAM", "7\nAM", "8\nAM", "9\nAM", "10\nAM", "11\nAM", "12\nPM", "1\nPM", "2\nPM", "3\nPM", "4\nPM", "5\nPM", "6\nPM", "7\nPM", "8\nPM", "9\nPM", "10\nPM", "11\nPM"}; TextView[] views = new TextView[24]; public InnerAdapter() { TextView create = new TextView(DayViewActivity.this); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 62, getResources().getDisplayMetrics()), 1.0f); params.topMargin = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1, getResources().getDisplayMetrics()); params.bottomMargin = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1, getResources().getDisplayMetrics()); create.setLayoutParams(params); create.setBackgroundColor(Color.BLUE); create.setText("Test"); views[0] = create; for(int i = 1; i < views.length; i++) { views[i] = null; } } @Override public int getCount() { // TODO Auto-generated method stub return array.length; } @Override public Object getItem(int position) { // TODO Auto-generated method stub return null; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if(convertView == null) { LayoutInflater inflater = LayoutInflater.from(parent.getContext()); convertView = inflater.inflate(R.layout.day_view_item, parent, false); } ((TextView)convertView.findViewById(R.id.day_hour_side)).setText(array[position]); LinearLayout layout = (LinearLayout)convertView.findViewById(R.id.day_event_layout); if(views[position] != null) { layout.addView((TextView)views[position], position); } return convertView; } }
XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="61dp" android:orientation="horizontal" > <LinearLayout android:layout_width="wrap_content" android:layout_height="61dp" android:orientation="vertical"> <TextView android:id="@+id/day_hour_side" android:layout_width="wrap_content" android:layout_height="60dp" android:text="12AM" android:background="#bebebe" android:layout_weight="0" android:textSize="10dp" android:paddingLeft="5dp" android:paddingRight="5dp"/> <TextView android:layout_width="match_parent" android:layout_height="1dp" android:layout_weight="0" android:background="#000000" android:id="@+id/hour_side_divider"/> </LinearLayout> <LinearLayout android:layout_width="0dp" android:layout_height="61dp" android:orientation="vertical" android:layout_weight="1"> <LinearLayout android:id="@+id/day_event_layout" android:layout_width="match_parent" android:layout_height="60dp" android:orientation="horizontal" ></LinearLayout> <TextView android:layout_width="match_parent" android:layout_height="1dp" android:background="#000000" android:id="@+id/event_side_divider" /> </LinearLayout> </LinearLayout>
-26688384 0 It seems to be related to a sort of "IE9 z-index" bug. I found this: http://icreatestuff.co.uk/blog/article/ie9-z-index-stacking-problem-or-something-stranger
and added a transparent 1x1 "fixer.png" to the navbar. Now it works immediately in IE9 without resizing. Glad, that I am using Firefox most of the times. :-)
-32053903 0 Rule in firewall for vmwareShould there be some sort of rule in the firewall that lets your vmware host server get out to the internet?
I have changed IP addressees, dns entries and still having an issue.
-1568058 1 Django: How do I make fields non-editable by default in an inline model formset?I have an inline model formset, and I'd like to make fields non-editable if those fields already have values when the page is loaded. If the user clicks an "Edit" button on that row, it would become editable and (using JavaScript) I would replace the original widgets with editable ones. I'd like to do something like this when loading the page:
for field in form.fields: if field.value: # display as text else: # display as my standard editable widget for this field
I see that inlineformset_factory
has an argument called formfield_callback
. I suspect that this could be useful, but so for I haven't found any documentation for it. Can anyone point me to some useful documentation for this, and how it can help me solve this problem?
You increment it
up to three times in the loop, before comparing against the end.
You erase without saving the new iterator.
Lots of side-effects.
The ordering of if(*it == *(--it)) {
isn't defined, so you might end up comparing an element against itself. (==
isn't a sequence point, so *it
and *(--it)
can be evaluated in either order).
You don't check for tableAndHand
being empty - you increment it
before checking.
As described in php manual
It is not necessary to initialize variables in PHP however it is a very good practice. Uninitialized variables have a default value of their type depending on the context in which they are used - booleans default to FALSE, integers and floats default to zero, strings (e.g. used in echo) are set as an empty string and arrays become to an empty array
if so then why its through error (notice) when try to access uninitialized variable? like
echo $x;
its return even in script following message
Notice: Undefined variable: x...
But When I declare $x
as NULL
then its not through any notice or error and working nicely
$x = NULL; echo $x;
Now My Question is Why its through notice if not declare like $x = NULL
or $x = ''
although undeclared variable initialized as NULL
which is clearly mentioned in Manual??
I have a script and many uninitialized variable there and experiencing this issue.
-11689684 0If the code appears again, then the attacker left some script, which, on request, runs the infecting procedure. Usually this script receives an encoded string of the malcode (e.g. in base64
), decodes it and executes via eval()
. You should find this file (it is most likely a PHP script) and remove it. To find it look at the log and search for suspicious requests (e.g. a single POST
request, transmitting base64
string is a very suspicious one).
I was writing sling unit test case for server side , where my test bundle is run by getting hit into the junit servlet , from the client side using the following piece of code. My test needs a running FTP server for the purpose , which i want to get embed into this function , by using @before and cleaning the dump by @after or any other best possible ways , how to do this with the runnable test class which invokes a junit servlet.
@RunWith(SlingRemoteTestRunner.class) public class FTPImporterTest extends SlingTestBase implements SlingRemoteTestParameters, SlingTestsCountChecker { /** * */ public static final String TEST_SELECTOR = "com.my.proj.FTPImporterTesting.FTPImporterServerTest"; public static final int TESTS_AT_THIS_PATH = 3; /** * */ public int getExpectedNumberOfTests() { return TESTS_AT_THIS_PATH; } public String getJunitServletUrl() { return getServerBaseUrl() + "/system/sling/junit"; } public String getTestClassesSelector() { return TEST_SELECTOR; } public String getTestMethodSelector() { return null; } public void checkNumberOfTests(int i) { Assert.assertEquals(TESTS_AT_THIS_PATH, i); } }
-10779737 0 Hi i think you should like this I check to your code and some modify and created easily code to your navi and logo Please Checked'
Css
.header, .navi, ul, li, a, span{ margin:0; padding:0; } .header{ overflow:hidden; z-index:5; } .logo{ position:relative; z-index:1; height:188px; width:100%; } .navi{ position:absolute; left:40%; right:0; z-index:2; top:148px; list-style:none; } li{ float:left; background:url('http://soteriabrighton.co.uk/test2/nav/images/top.png') no-repeat 10% 0; margin-left:2%; } .navi a{ background:url('http://s16.postimage.org/yqxo6bq6p/navi_left.png') no-repeat left top; padding-left:9px; color:#000; margin-top:27px; text-decoration:none; font-size:22px; float:left; border-radius:5px 0 0 5px; } .navi a span{ background:url('http://s17.postimage.org/ukpot5zcb/navi_right.png') no-repeat right top; padding-right:9px; float:left; line-height:38px; border-radius:0 5px 5px 0; } .navi a:hover span, .navi a:hover{ background:green; color:#fff; border-radius:5px; }
HTML
<div class="header"> <img src="http://soteriabrighton.co.uk/test2/logo.png" alt="" class="logo" /> <ul class="navi"> <li><a href="#"><span>home</span></a></li> <li><a href="#"><span>news</span></a></li> <li><a href="#"><span>forums</span></a></li> <li><a href="#"><span>articles</span></a></li> <li><a href="#"><span>contact</span></a></li> </ul> </div>
Live demo here http://jsfiddle.net/Kj2e9/
-30412074 0 Clickable links in android using eclipseI am trying to make strings in the text view clickable.My textview
consists of name of various online questions and i want them to redirect the user to the url of the question when clicked.Can anyone recommend changes to my code.
In the following code "result" is the final textview consisting of name of questions .
public class Http extends Activity { TextView httpStuff; HttpClient client; JSONObject json; final static String URL = "http://codeforces.com/api/user.status?handle="; String m = ""; public static String[] sarr = new String[200]; public static String[] name = new String[200]; public static int cnt = 0; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.httpex); httpStuff = (TextView)findViewById(R.id.tvHttp); client = new DefaultHttpClient(); new Read().execute("result"); } public JSONObject lastSub(String username) throws ClientProtocolException, IOException, JSONException { StringBuilder url = new StringBuilder(URL); url.append(username); HttpGet get = new HttpGet(url.toString()); int status = 0; HttpResponse r = client.execute(get); status = r.getStatusLine().getStatusCode(); if(status == 200) { HttpEntity e = r.getEntity(); String data = EntityUtils.toString(e); JSONObject last = new JSONObject(data); //JSONObject last = new JSONObject(data).getJSONArray("result").getJSONObject(0).getJSONObject("problem"); return last; } else { Toast.makeText(Http.this, "error", Toast.LENGTH_SHORT); return null; } } public class Read extends AsyncTask <String, Integer, String> { @Override protected String doInBackground(String... arg0) { // TODO Auto-generated method stub try { String add = "&from=1&count=100"; String input = (Mainapp.p); input = input.concat(add); json = lastSub(input); JSONArray array = json.getJSONArray("result"); String m1=null, m2=null, m3=null; String n1 = System.getProperty("line.separator"); int flag=0; for(int k=0; k<array.length() && cnt<15; k++) { JSONObject json1 = array.getJSONObject(k).getJSONObject("problem"); JSONObject v = array.getJSONObject(k); if(v.getString("verdict").contentEquals("OK")) { m1 = json1.getString("name"); m2= json1.getString("contestId"); m2= m2.concat("/"); m3= json1.getString("index"); m2 = m2.concat(m3); flag = 0; for(int i=0; i<cnt ; i++) { if (sarr[i].equals(m1)) { flag = 1; } } if(flag == 0) { m = m.concat(m1); m= m.concat(n1); sarr[cnt] = m1; name[cnt] = m2; cnt++; } } } return m; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (RuntimeException e) { e.printStackTrace(); } return "INVALID USER NAME"; } @Override protected void onPostExecute(String result) { // TODO Auto-generated method stub super.onPostExecute(result); httpStuff.setText(result); } } } }
-2698695 0 As noted, K is the loop's label. It allows you to identify a particular loop to aid readability, and also to selectively exit a specific loop from a set of nested enclosing ones (i.e. being a "goto"...shhh! :-)
Here's a contrived example (not compiled checked):
S : Unbounded_String; F : File_Type; Done_With_Line : Boolean := False; All_Done : Boolean := False; begin Open(F, In_File, "data_file.dat"); File_Processor: while not End_Of_File(F) loop S := Get_Line(F); Data_Processor: for I in 1 .. Length(S) loop Process_A_Character (Data_Char => Element(S, I), -- Mode in Line_Done => Done_With_Line, -- Mode out Finished => All_Done); -- Mode out -- If completely done, leave the outermost (file processing) loop exit File_Processor when All_Done; -- If just done with this line of data, go on to the next one. exit Data_Processor when Done_With_Line; end loop; end loop File_Processor; Close(F); end;
-28910929 0 You have several problems
You don't check if the file opened.
After fopen()
you must ensure that you can read from the file, if fopen()
fails, it returns NULL
so a simple
if (file == NULL) return -1;
would prevent problems in the rest of the program.
Your while
loop only contains one statement because it lacks braces.
Without the braces your while loop is equivalent to
while (fgets(buf, sizeof(buf), file)) { ptr = strtok(buf, "f"); }
You don't check that strtok()
returned a non NULL
value.
If the token is not found in the string, strtok()
returns NULL
, and you passed the returned pointers to atol
anyway.
That would cause undefined behavior, and perhaps a segementation fault.
You don't check if there was an argument passed to the program but you still try to compare it to a string. Also potential undefined behavior.
I don't know if the following program will do what you need since it's your own program, I just made it safer, avoided undefined behavior
#include <ncurses.h> #include <stdlib.h> #include <string.h> #include <stdio.h> int main(int argc, char * argv[]) { char buf[100]; char *ptr; char *ptr2; char *ptr3; char *ptr4; int a; int b; int c; int d; FILE *file; initscr(); cbreak(); noecho(); if (argc > 1) { file = fopen(argv[1], "r"); if (file == NULL) return -1; while (fgets(buf,100,file) != NULL) { ptr = strtok(str,"f"); ptr2 = strtok(NULL," "); ptr3 = strtok(NULL,"f"); ptr4 = strtok(NULL," "); if (ptr != NULL) a = atoi(ptr); if (ptr2 != NULL) b = atoi(ptr2); if (ptr3 != NULL) c = atoi(ptr3); if (ptr4 != NULL) d = atoi(ptr4); } } refresh(); getchar(); endwin(); return 0; }
-18801430 0 Create the class TasksController below in file: app\Controller\TasksController.php
You have called your file tasks_controller.php. Read the error carefully ;-)
The naming convention for controller files was updated in cakephp 2.0. Looks like you are using the old 1.x conventions
-39916656 0Try; /wd:Repository_Document_Reference/wd:ID[contains(@wd:type,"Document_ID")]
One problem is that totalwtax is not being calculated correctly because any items that are zero rated for tax are not included in the total. Changing the else clause to this:
else { double newprice = Double.parseDouble(price); totalwtax +=newprice; shoppingcart.put(item, price); }
Produces this output for your test case:
Please enter an item.standard Please enter the price for standard: 12.49 Would you like to continue to add items? (Type Y) for Yes and (Type N) for No.y Please enter an item.music Please enter the price for music: 14.99 Would you like to continue to add items? (Type Y) for Yes and (Type N) for No.y Please enter an item.discount Please enter the price for discount: 0.85 Would you like to continue to add items? (Type Y) for Yes and (Type N) for No.n Your cart contains the following at items with tax{music=16.489, standard=12.49, discount=0.85} Total Tax: 29.829
This still isn't exactly the same as the expected answer because the expected answer assumes some rounding in the calculation. You would either need to round the values yourself or it might be appropriate to use a Money class so that all the fractions of cents are correctly accounted for.
-370459 0 How can I copy files with ASP.Net using Vista and IIS7?I have a button on a website that creates a directory and copys a file. I developed it using Visual Studio 2008, ASP.Net 3.5. I am running Vista as my OS. The website uses identiy impersonation.
The functionality doesn't work ("Access to Path XYZ is denied") when:
The functionality works fine when [note Visual Studio run with Admin rights]:
I've never seen this behavior before, previously File.Copy type commands only cared that the rights on the folder being copied to were valid etc... (I have Everyone having full control while trying to debug this situation). It seems likely that the issue is having Admin rights or not? Or being logged in to the machine that it is running on?
What is happening here? Why does it work in the development environment and deployed to another machine, but not work when deployed on my own machine? Seems very odd, any help would be appreciated.
EDIT: I've added "Everyone" to all of the relvant directories and give that user Full Control, so there shouldn't be any permission issues?
-13554773 0It is a good way, but. You should not use just except
clause, you have to specify the type of the exception you are trying to catch. Also you can catch an error and continue the loop.
def scrape_all_pages(alphabet): try: pages = get_all_urls(alphabet) except IndexError: #IndexError is an example ## LOG THE ERROR IF THAT FAILS. for page in pages: try: scrape_table(page) except IndexError: # IndexError is an example ## LOG THE ERROR IF THAT FAILS and continue this loop
-20276863 0 The solution that uses Set
will probably be more readable, and easier to maintain - for example you avoid a whole class of problems when you modify your code like "what happens if I put a false
value in the map - will it break my code?".
As a side note, Java's HashSet
is quite inefficient memory-wise and actually uses a HashMap
under the covers. Still, in most cases it is code readability and maintainability that matters most and not implementation details like this.
in my web app the database has a blob(an xml file). The user is allowed to change the blob through a web interface. I take the blob show it in a html form, then the user can change some values and save it back. So the user submit request has a db save. Can I save the entry to a cache to speed up the submit request? But then there is a chance of loosing the changes? What is the fastest way to persist the blob in db?
-33124843 0 Trouble mounting a folder from host onto my docker imageI am trying to mount a folder from my host system to a docker container. I am aware of the -v
attribute of docker commands.
My command is:
docker run -v /home/ubuntu/tools/files/:/root/report -i -t --entrypoint /bin/bash my_image -s
But this does not seem to work, no files appear at my designated container folder. This is very frustrating as I will need to add files to my docker image at periodic intervals so just adding them to the build file at creation wont cut it.
-12871836 0 How to get return value from a function called which executes in another thread in TBB?In the code:
#include <tbb/tbb.h> int GetSomething() { int something; // do something return something; } // ... tbb::tbb_thread(GetSomething, NULL); // ...
Here GetSomething()
was called in another thread via its pointer. But can we get return value from GetSomething()
? How?
For some reason TCPDF is adding space to the left when I use writeHTML()
to print an unordered list. By default, the PDF has a margin of 5 (set with $pdf->SetMargins(5, 0, 10, true);
) but list items get indented.
I set $pdf->setCellPaddings(0,0,0,0);
already, which prevents with unwanted (minus-)space for <p>
tags, but obviously doesn´t affect lists.
The call:
$pdf->writeHTML('<ul><li>...</li></li>...</li></ul>');
The result:
Is there any option I miss?
-31200930 0You can use insert_batch
For Eg:
$data = array( array( 'title' => 'My title' , 'name' => 'My Name' , 'date' => 'My date' ), array( 'title' => 'Another title' , 'name' => 'Another Name' , 'date' => 'Another date' ) ); $this->db->insert_batch('mytable', $data); // Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date'), ('Another title', 'Another name', 'Another date')
-34817913 0 You can do that with JavaScript/jQuery.
<form id="myform"> ... </form> $(".category").change(function(){ value = $(this).val() $('.myform').attr('action', "/search/" + value) });
Remember to place the code in a $(document).ready()
listener.
Want to avoid JavaScript? You can get the value directly in the template. You cannot change that value if the user changes the dropdown value: in this case, your only chance is that of redirecting the user in your views.py
based on what he choose in the dropdown.
Remember: Django simply renders a page and sends it to the user. Whatever happens before a new call is made to your server is not in the possibilities of Django but those of JavaScript.
-18995078 0You will want to use an asp.net control called a GridView. When rendered, it becomes an HTML table. It can then be manipulated by CSS and Javascript.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.aspx
GridView not being an option, try using a Literal:
<asp:Literal ID="LiteralTable" runat="server"></asp:Literal>
Codebehind:
StringBuilder sb = new StringBuilder(); sb.Append("<table>"); for (int i = 1; i < 15; i++) { sb.Append("<tr class=\"clickable\"><td>" + FirstColumn[i] + "</td>" + "<td>" + SecondColumn[i] + "</td></tr>"); sb.Append("<tr class=\"expandable\"><td>Edit</td>" + "<td>More Info</td></tr>"); } sb.Append("</table>"); LiteralTable.Text = sb.ToString();
And then work your javascript (or jquery) magic:
$(".clickable").click().next().show();
And in this case just load your database into the array before calling the stringbuilder!
-25363660 0 How to sum range of cells with the same formulas in excelI got a range of cells that use the same formula:
=A1*IF(B1="Yes",1,0) =A2*IF(B2="Yes",1,0) ...
I would like to have one cell with the sum of all cells in a range of A1..A10
Any ideas?
Thanks
-25221754 0For making restaurant finder app , Follow following instructions like
Make sure that web services are ready (mainly JSON or XMl) then fetch them using either http://www.androidhive.info/2012/01/android-json-parsing-tutorial/ or http://www.androidhive.info/2011/11/android-xml-parsing-tutorial/ turtorial
and show them in list or on Google maps (For Google maps you need latitude and longitude of particular restaurant )
-21341337 0With/Without _ref:
For each of these pages:
You could use something like:
#include <stdio.h> static char *ipToStr (unsigned int ip, char *buffer) { sprintf (buffer, "%d.%d.%d.%d", ip >> 24, (ip >> 16) & 0xff, (ip >> 8) & 0xff, ip & 0xff); return buffer; } int main (void) { char buff[16]; printf ("%s\n", ipToStr (0x7d162f7dU, buff)); return 0; }
which produces:
125.22.47.125
-18463291 0 How to generate entities from database schema using doctrine-orm-module and zf2 I am using "doctrine/doctrine-orm-module": "0.7.0" with ZF2.
Once I create Entities I usually run following commands to sync and generate database automatically according to my entities.
./vendor/bin/doctrine-module orm:validate-schema ./vendor/bin/doctrine-module orm:schema-tool:create
Is there a way to make this process reverse? I mean, Can I generate entities from existing database in mysql?
-38283276 0It's the server's job to turn the URL encoded email address back into its original value. So your JavaScript is working perfectly, there's nothing to do there. Your server code is what needs to be fixed.
And if the application on the server isn't even decoding parameters before it's running the query against the database, it makes me feel like you may have some security issues to fix as well. Make sure that your parameters are decoded and cleaned before they are used in SQL queries. You can read more on cleaning parameters and SQL injection here.
-1519149 0 Graphic object outside of C# app - is it doable?I have already asked here but the only answer was related to positioning. I would need to make an app which would produce an image always following the mouse, outside of the app. I know now how to hook mouse position, but I have no clue how to let the object (image) be on the top of other apps. Anyway I dont know if it is even possible in .NET. Thanks!
-2607401 0Is the button within a form? It has to be within a form to do a post...
-1709746 0use xsd.exe in the .net sdk.
use the /c switch to generate classes
-14667666 0It's not NoUniqueBeanDefinitionException
being thrown, it's:
ClassNotFoundException: org.springframework.beans.factory.NoUniqueBeanDefinitionException
Please add spring-beans-3.2.1.RELEASE.jar
into your CLASSPATH. Notice that this class was introduced in version 3.2.1 (most fresh for the time being). Make sure all your Spring JARs are in the same version.
I'm trying to process my Form submit values to a .csv file using the fputcsv
function. I'm not getting any errors and no Form values have been saved to the data.csv file. Can anyone see a problem as to what i'm doing wrong?
Form
<label for="location">How many Locations?</label> <input id="location" name="loc" /><br /> <select id="when" name="day"> <option value="Sunday">Sunday</option> <option value="Monday">Monday</option> <option value="Tuesday">Tuesday</option> <option value="Wednesday">Wednesday</option> <option value="Thursday">Thursday</option> <option value="Friday">Friday</option> <option value="Saturday">Saturday</option> </select> <input type="checkbox" id="osecom" name="osecom" value="Yes" /> <label for="osecom">Online</label> <input type="checkbox" id="item1yes" name="item1yes" value="Yes" /> Yes <input type="checkbox" id="item1no" name="item1no" value="No" /> No<br /> <label for="chkitem1">mobile</label> <input type="checkbox" id="item2yes" name="item2yes" value="Yes" /> Yes <input type="checkbox" id="item2no" name="item2no" value="No" /> No<br /> <label for="chkitem2">policy? </label> <input type="submit" title="Submit Form" value="" />
php code
if(isset($_POST['submit'])) { $data = implode(',', $_POST); if( $fp = fopen('data.csv', 'a') ){ fputcsv($fp, $data); } fclose($fp); }
-36487064 0 A tricky way to do this is use Aggregate()
extension, using a dictionary as accumulator with the key-property values as keys:
var customers = new List<Customer>(); var distincts = customers.Aggregate(new Dictionary<int, Customer>(), (d, e) => { d[e.CustomerId] = e; return d; }, d => d.Values);
And a GroupBy-style solution is using ToLookup()
:
var distincts = customers.ToLookup(c => c.CustomerId).Select(g => g.First());
-32017742 0 PHP cURL Upload file without processing I am trying to upload a file to a Rest API (Tableau Server Rest API) endpoint using PHP cURL.
The file upload procedure exists of three steps:
I was having issues with the server giving me a 500 status code on the second step. After contacting the support we figured out that the problem is most likely that the curl request seems to using the -data
flag instead of the --data-binary
flag which means some kind of encoding happens on the request body which should not be happening. This causes the server to respond with a 500 status code instead of an actual error message...
I would like to know how i can make a cURL request with the --data-binary
flag in PHP.
Relevant sections of my current code:
// more settings $curl_opts[CURLOPT_CUSTOMREQUEST] = $method; $curl_opts[CURLOPT_RETURNTRANSFER] = true; $curl_opts[CURLOPT_HTTPHEADER] = $headers; $curl_opts[CURLOPT_POSTFIELDS] = $body; //more settings curl_setopt_array( $this->ch, $curl_opts ); $responseBody = curl_exec( $this->ch );
$method
is "PUT", $headers
contains an array with Content-Type: multipart/mixed; boundary=boundary-string
and the $body
is constructed like this:
$boundary = md5(date('r', time())); $body = "--$boundary\n"; $body .= "Content-Disposition: name='request_payload'\nContent-Type: text/xml\n\n"; $body .= "\n--$boundary\n"; $body .= "Content-Disposition: name='tableau_file'; filename='$fileName'\nContent-Type: application/octet-stream\n\n"; $body .= file_get_contents( $path ); $body .= "\n--$boundary--";
Where the $boundary
is the same as the boundary-string in the content-type header. i am aware this is a kinda/very messy way to construct my body, i am planning to use Mustache as soon as i can actually upload my files :S
(i would like to mention that this is my first post here, please be gentle...)
-28893871 0Instead of making span text to have absolute position, I have given line to have absolute position, and have placed text in center using text-align : center.
div.btn{ width:100px; height:100px; float:left; border:1px solid #000000; font-family:Arial, Helvetica, sans-serif; font-size:80px; text-align:center; position: relative; } div.vertical_line{ width:0; height:100px; border:1px solid #000000; position:absolute; right:49px; z-index:100; margin:0; padding:0; top : 0; } div.btn span{ float:left; width : 100%; text-align : center; z-index:0; }
-5001769 0 EmailsList.ToString()
?
If it's your class, implement ToString()
method the way you need.
Simplest way is to use a List
1 to store your elements, and use Collections.shuffle()
on it - and then take elements iteratively.
The shuffle produces a random permutation of the list, so chosing items iteratively gives you the same probability to chose any ordering, which seems to be exactly what you are after.
Code snap:
String[] picture = { "blue", "white", "red", "yellow" }; //get a list out of your array: List<String> picturesList = Arrays.asList(picture); //shuffle the list: Collections.shuffle(picturesList); //first picture is the first element in list: String pictureOne = picturesList.get(0); System.out.println(pictureOne); //2nd picture is the 2nd element in list: String pictureTwo = picturesList.get(1); System.out.println(pictureTwo); ...
(1) Simplest way to get the list from an array is using Arrays.asList()
If your host machine has wifi feature built in, you can use the bridged network mode :
And done.
-28374282 0Take a look at
http://www.realtimerendering.com/intersections.html
Lot of help in determining intersections between various kinds of geometry
http://geomalgorithms.com/code.html also has some c++ functions one of them serves your purpose
-26566852 0No using javascript means you want to do this in pure CSS. It could be difficult to get the exact result that you want, although you can find effects close to what you need : See here.
If you are ok with using javascript, this is what you're looking for (note that jquery was included, this is a javascript library that simplifies its use. You can easily include it in an html page by putting <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
in your <head>
Hope that helps!
Sources: Simple CSS Animation Loop – Fading In & Out "Loading" Text and How to make this jQuery animation code loop forever?
-3502476 0If an object is not getting deallocated it is not because it is 'referenced' by another object, but because someone who had 'ownership' of the object did not 'release' it. This is called a 'memory leak'.
You can find out more by reading the Memory Management Programming Guide. Following the simple rules presented in the guide should help you avoid memory leaks.
For detecting memory leaks you could use Instruments.
I don't know of any app / tool that will show you which objects are referencing a particular object.
-19463999 0 Android spinner onItemSelected Listener cannot see outside valuesI have an onItemSelectedListener
for my Spinner in my main activity. I assign the listener to the spinner object in the onCreate
Method.
The activity class has a member variable int iCurrentSelection
. But no matter what I set iCurrentSelection
to anywhere in the activity, it is always null in the onItemSelected
Method. So the boolean changed
is always true
even if nothing has changed.
I do not understand why! Somebody please enlighten me :-)
Here is my listener class:
OnItemSelectedListener oisl = new OnItemSelectedListener(){ public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { boolean changed = iCurrentSelection != arg0.getSelectedItemPosition(); stopTracks(); if(changed){ iCurrentSelection = arg0.getSelectedItemPostion(); initTracks(actSpeed); } } @Override public void onNothingSelected(AdapterView<?> arg0) { } }
-40750590 0 You need to use AsyncHTTPTestCase, not just AsyncTestCase. A nice example is in Tornado's self-tests:
You need to implement get_app
to return an application with the RequestHandler you've written. Then, do something like:
class TestRESTAuthHandler(AsyncHTTPTestCase): def get_app(self): # implement this pass def test_http_fetch_login(self): data = urllib.parse.urlencode(dict(username='admin', password='123456')) response = self.fetch("http://localhost:8080//#/login", method="POST", body=data) # Test contents of response self.assertIn("Automation web console", response.body)
AsyncHTTPTestCase provides convenient features so you don't need to write coroutines with "gen.coroutine" and "yield".
Also, I notice you're fetching a url with a fragment after "#", please note that in real life web browsers do not include the fragment when they send the URL to the server. So your server would see the URL only as "//", not "//#/login".
-35035493 0 Spark Streaming - HBase Bulk LoadI'm currently using Python to bulk load CSV data into an HBase table, and I'm currently having trouble with writing the appropriate HFiles using saveAsNewAPIHadoopFile
My code currently looks as follows:
def csv_to_key_value(row): cols = row.split(",") result = ((cols[0], [cols[0], "f1", "c1", cols[1]]), (cols[0], [cols[0], "f2", "c2", cols[2]]), (cols[0], [cols[0], "f3", "c3", cols[3]])) return result def bulk_load(rdd): conf = {#Ommitted to simplify} keyConv = "org.apache.spark.examples.pythonconverters.StringToImmutableBytesWritableConverter" valueConv = "org.apache.spark.examples.pythonconverters.StringListToPutConverter" load_rdd = rdd.flatMap(lambda line: line.split("\n"))\ .flatMap(csv_to_key_value) if not load_rdd.isEmpty(): load_rdd.saveAsNewAPIHadoopFile("file:///tmp/hfiles" + startTime, "org.apache.hadoop.hbase.mapreduce.HFileOutputFormat2", conf=conf, keyConverter=keyConv, valueConverter=valueConv) else: print("Nothing to process")
When I run this code, I get the following error:
java.io.IOException: Added a key not lexically larger than previous. Current cell = 10/f1:c1/1453891407213/Minimum/vlen=1/seqid=0, lastCell = /f1:c1/1453891407212/Minimum/vlen=1/seqid=0 at org.apache.hadoop.hbase.io.hfile.AbstractHFileWriter.checkKey(AbstractHFileWriter.java:204)
Since the error indicates that the key is the problem, I grabbed the elements from my RDD and they are as follows (formatted for readability)
[(u'1', [u'1', 'f1', 'c1', u'A']), (u'1', [u'1', 'f2', 'c2', u'1A']), (u'1', [u'1', 'f3', 'c3', u'10']), (u'2', [u'2', 'f1', 'c1', u'B']), (u'2', [u'2', 'f2', 'c2', u'2B']), (u'2', [u'2', 'f3', 'c3', u'9']),
. . .
(u'9', [u'9', 'f1', 'c1', u'I']), (u'9', [u'9', 'f2', 'c2', u'3C']), (u'9', [u'9', 'f3', 'c3', u'2']), (u'10', [u'10', 'f1', 'c1', u'J']), (u'10', [u'10', 'f2', 'c2', u'1A']), (u'10', [u'10', 'f3', 'c3', u'1'])]
This is a perfect match for my CSV, in the correct order. As far as I understand, in HBase a key is defined by {row, family, timestamp}. Row and family are combination are unique and monotonically increasing for all entries in my data, and I have no control of the timestamp (which is the only problem I can imagine)
Can anybody advise me on how to avoid/prevent such problems?
-31823954 0Right click the project and click on properties, Then on the left click on web, under project URL you can change the port. click save, it will ask if you want to create the new virtual directory for the port.
-37241457 0 Dependency property inside viewmodel in PrismIs there any way to declare dependency property inside viewmodel? I want to declare a dependency property inside viewmodel and change it's value through command.
public class MyViewModel : Prism.Windows.Mvvm.ViewModelBase { public bool IsPaneVisible { get { return (bool)GetValue(IsPaneVisibleProperty); } set { SetValue(IsPaneVisibleProperty, value); } } public static readonly DependencyProperty IsPaneVisibleProperty = DependencyProperty.Register("IsPaneVisible", typeof(bool), typeof(MyViewModel), new PropertyMetadata(0)); public ICommand VisibilityChangeCommand { get; set; } public MyViewModel() { VisibilityChangeCommand = new DelegateCommand(OnVisibilityChange); } private void OnVisibilityChange() { IsPaneVisible = !IsPaneVisible; } }
Problem is, I am getting some compilation error in IsPaneVisible' getter/setter : "GetValue does not exist in the current context". Is there any alternative way to do this?
-30602566 0Figured it out. I had to change the API url to: https://api.twitter.com/1.1/statuses/update_with_media.json
-25491882 0Use i18n files at ISO 639-1 representation.
That files allow you have any languages and use each "labels" with Ti.Locale.getString().
Also, you can use a require of file at app.js and put this variable like global.
language.js (for example):
var language = (function() { var self = { currentLanguage: 'en' // by default }; var labels = { msgHello: { en: 'Hello World', es: 'Hola Mundo' } }; self.changeLanguage = function changeLanguage(newLanguage){ self.currentLanguage = newLanguage; }; self.getLabel = function getLabel(key, language){ if(typeof language !== 'undefined') { return labels[key][language]; } else return labels[key][self.currentLanguage]; }; return self; }()); module.exports = language;
app.js (for example):
var appLanguage = require('language.js'); (function() { Ti.API.info("Language: "+appLanguage.currentLanguage); Ti.API.info("MSG Hello World (English): "+appLanguage.getLabel(msgHello)); Ti.API.info("MSG Hello World (Spanish): "+appLanguage.getLabel(msgHello, es)); }());
You can use appLanguage variable directly on any file.
-32138576 0 Time effciency for test case in euler #1Often times when solving questions on hackerrank codechef my code times out for certain test cases. I know it's because my code isn't efficient enough and I need to reduce the time complexity of the code.
In this particular problem Project Euler Multiples of 3 and 5 I don't seem to understand how the test cases timed out. If I'm not wrong code runs in O(n^2), that too considering the loop for taking the test cases. How can I make my code efficient?
The description of the question is in the link.
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ int t, n; int n1,n2; int mul3, mul5, sum=0,sum3=0,sum5=0; cin>> t; while(t--){ cin>>n; sum=0; sum5=0; sum3=0; if(n%3==0) n1=n/3-1; else n1=n/3; if(n%5==0) n2=n/5-1; else n2=n/5; for(int i=0;i<=n1;i++){ if(i<=n2){ mul5= i*5; sum5+=mul5; } mul3=i*3; if((mul3%5)!=0) sum3+=mul3; sum = sum3+sum5; } cout << sum << endl; } system("PAUSE"); return 0; }
-19181204 0 Hi there this looks quite komplex but if you are willing to use GSON this could be converted to a JAVA Object with just a few lines.
-30326822 0 use wildcards with update and replaceI have a very large MySQL table with lots of data in it, one of the fields is Invoice No, and is a number starting at 1000.001 (This is a string). I have got this from someone that left the company and they imported the data through excel and some of the numbers have come across as 1000.01 instead of 1000.010.
When I run this query in php my admin, it shows there are over 11k rows, so I can see them ok.
SELECT `AnalysisID` , `InvoiceNo` FROM `STStbl000010` WHERE `InvoiceNo` LIKE '%.__' ORDER BY `STStbl000010`.`AnalysisID` ASC
So simply put I need to add a 0 (Zero) to the end of those entries.
I have tried the following, however, it just returns 0 rows effected.
Can I use wildcards like this in and Update and Replace Statement?
UPDATE `STStbl000010AT` SET `InvoiceNo` = replace(`InvoiceNo`, '%.__', '%.__0') WHERE `InvoiceNo` LIKE '%.__'
Thanks
-36542323 0 In Selenium Webdriver, how to get a text after an element?I would like to get a text that exactly comes after a specific element. Pleases look the sample code:
<div id="content-tab-submitter" class=""> <h4>Sender</h4> <p> <span class="screenHidden">Name: </span> submitter <br> <span class="screenHidden">E-mail address:</span> submitter@asd.com <br> <span class="screenHidden">Account: </span> asdas <br> </p> </div>
I would like to get the text that comes exactly after <span>
which contains "Account". By using this xpath:
//*[@id='content-tab-submitter']/p/span[contains(text(),'Account')]/following::text()
JAVA gives me an error, since the output is not a web element and it is a text. So, it is not possible to use findElement. Is there any idea how to get this text in a clean way. I mean I do not want to get all texts: (in this case) submitter\nsubmitter@asd.com\nasdas and then extract the desired text.
Many thanks in advance for your valuable comments!
-6577187 0 why dialog is not a view in AndroidI am wondering why dialog is not a view. From Android developer guide, "The visual content of the window is provided by a hierarchy of views — objects derived from the base View class", but dialog class:
public class Dialog implements DialogInterface, Window.Callback, KeyEvent.Callback, OnCreateContextMenuListener {
is there anyone knows about the reason of the design?
-29338293 0<h2><a href="<?php echo the_permalink() ?>" title="<?php echo the_title(); ?>"><?php echo the_title(); ?></a></h2>
you should use <?php echo the_title(); ?>
or <?= the_title(); ?>
Sure, no problem running without an operating system, I do that kind of thing daily...
http://sam7stuff.blogspot.com/
You programs are, at least at first, not going to resemble desktop applications, I would avoid any libraries C libraries, no printfs or strcmps or things like that until you get the feel for it and find the right tools. No floating point as well. add some numbers do some shifting blink some leds.
codesourcery lite is probably the fastest way to get started, the gnueabi one I believe is the one you want.
This winarm site has a compiler and tons of non-os projects for seems like every arm based microcontroller. http://www.siwawi.arubi.uni-kl.de/avr_projects/arm_projects/
Atmel is very very good about information, no doubt they have example programs you can try as well on the eval board.
emdebian is another cross compiler that is somewhat up to date and has binaries. building a gcc from scratch for cross compiling is not bad at all. The C library is another story though, and even the gcc library for that matter. I find it easier to do without either library.
It is possible get a C library working and run a great many kinds of programs. Depends on what you are looking to do. Ahh, just looked at the specs, that is a pretty serious eval board, plenty of power for an operating system should you choose to run one. You can certainly run programs that use the display as a user interface. read/write sd cards, usb, basically everything on the board, without an os, if you choose.
-22923333 0 calling setBackgroundColor on UILabel causes crashOkay so I have been pulling my hair out, TRYING to find the cause of this problem in my code, and I've narrowed it down to a single line. The problem is, it doesn't make any sense. I create a UIViewController and put this code in the init method
- (id)init { [super init]; [self.view setBackgroundColor:[UIColor groupTableViewBackgroundColor]]; iCodeAppDelegate*appDelegate = [[UIApplication sharedApplication] delegate]; UIWindow*window = appDelegate.window; int headerY = appDelegate.rootNavigator.navigationBar.bounds.size.height;// + [UIApplication sharedApplication].statusBarFrame.size.height; //project options table int tableOffsetY = 250; UITableView* projectOptions = [[UITableView alloc] initWithFrame:CGRectMake(0, headerY+tableOffsetY, window.bounds.size.width, window.bounds.size.height-(headerY+tableOffsetY)) style:UITableViewStyleGrouped]; projectOptions.delegate = self; projectOptions.dataSource = self; projectOptions.scrollEnabled = NO; [self.view addSubview:projectOptions]; [projectOptions release]; //xcode logo image int centerX = window.bounds.size.width/2; int logoOffsetY = 8; int logoScale = 200; UIImage* xcodeLogo = [UIImage imageNamed:@"Images/xcode_logo.png"]; UIImageView* xcodeLogoView = [[UIImageView alloc] initWithFrame:CGRectMake(centerX-(logoScale/2), headerY+logoOffsetY, logoScale, logoScale)]; [xcodeLogoView setImage:xcodeLogo]; //[xcodeLogoView setBackgroundColor:[UIColor groupTableViewBackgroundColor]]; [self.view addSubview:xcodeLogoView]; [xcodeLogo release]; [xcodeLogoView release]; //"Welcome to Minicode" text int welcomeLabelHeight = 50; UILabel*welcomeLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, headerY+logoScale+8, window.bounds.size.width, welcomeLabelHeight)]; [welcomeLabel setText:@"Welcome to miniCode"]; [welcomeLabel setTextColor:[UIColor darkGrayColor]]; [welcomeLabel setTextAlignment:UITextAlignmentCenter]; [welcomeLabel setBackgroundColor:[UIColor clearColor]]; [welcomeLabel setFont:[UIFont fontWithName: @"Trebuchet MS" size: 24.0f]]; [self.view addSubview:welcomeLabel]; [welcomeLabel release]; return self; }
The problem lies in this specific line:
[welcomeLabel setBackgroundColor:[UIColor clearColor]];
if I comment it out, the code works fine, except that the label has a big white box behind it. I've scoured the internet, and it appears only one person has had a similar problem. The solution doesn't seem to have any sort of application to my code, however.
-34625747 0 Algorithm for finding conflicting relative order among list elementsI do not know the name of this problem (if I did, I could probably look up a solution).
Problem:
Given two lists of integers A
and B
, determine whether there exists an ordering conflict between any two elements x
and y
, where both x
and y
exist in both A
and B
.
For example, consider these two lists:
A : 2 3 8 9 B : 3 1 7 2
In this case, there exists an ordering conflict { 2, 3 }
because those elements appear in the opposite order relative to one another in list A
as they do in list B
.
Trivial cases
A
and B
have no elements in common; no conflicts.
A
and B
are the same list; no conflicts.
Question
What are some algorithms for solving this problem?
-17229059 0 loading a webpage into a div-not getting loadedI'm trying to load a webpage into a div...But It's not getting loaded into the div...instead it's loading as a whole webpage....why??
<li><a href="#" onClick="AboutUs();">About Us</a></li> <div class="bdy"></div>
javascript code:
function AboutUs () { // body... //$('.bdy').load('http://www.jhsoftech.com' ); $('.bdy').html('<object style="width:100%;height:435px;" data="http://www.erail.in">'); }
-1066657 0 PageFunction ultimately derives from Page, so I'm fairly certain you can just use <Page.CommandBindings>
to define your command bindings. Certainly you can use <Page.Resources>
in a PageFunction to define its resources.
Why can't you use <PageFunction.CommandBindings>
? I don't know, but I think you're probably right when you say it has to do with the fact that PageFunction is a generic type. You'd need some way in XAML to say what the underlying type is. I think that's possible in the .NET 4.0 version of XAML but not in the current version.
"Chunks" are parts of your code that get, in a sense, required on demand from the server. So you can have one main deliverable that loads the site, but load additional resources as the user starts to browse around.
Practically, you do this by defining a split point. This tells webpack to put the code needed to run the code path within that split point (i.e. a function) in its own file. Webpack will then factor out the modules that are common to that split chunk and the main file and put it into the main file to avoid duplicating vendor code (in other words, the chunk probably won't stand alone). Now Webpack generates two files: the main file, and an additional chunk. When the chunk's code path gets hit, the main file will pull in the additional chunk off the wire. From the developer's perspective, this all happens with a require
, which makes it very easy to reason.
One of the most common uses is to chunk router code. There is a working example in the react-router
docs, but the general idea is that you load your initial routes into the main file, and all subsequent or child routes can be in their own chunks and only get downloaded when the user hits those routes, increasing performance (potentially). The example code is a great way to grok how this works because you can watch the files get pulled off the wire when you hit the routes.
Anyhow, code chunking is an awesome feature.
All that said, be very wary of premature optimization. It can kill productivity. The best advice is to get running with Webpack without any code chunking, and then add code chunking when you require the performance (for example when you note that a feature or section of your site is heavy but rarely used).
PS: If you have more specific questions, I'm happy to amend this answer. If you're curious, though, check out the react-router
link above.
You can use WTForms. See example below, pulled from Flask's documentation:
from wtforms import Form, BooleanField, TextField, PasswordField, validators class RegistrationForm(Form): username = TextField('Username', [validators.Length(min=4, max=25)]) email = TextField('Email Address', [validators.Length(min=6, max=35)]) password = PasswordField('New Password', [ validators.Required(), validators.EqualTo('confirm', message='Passwords must match') ]) confirm = PasswordField('Repeat Password') accept_tos = BooleanField('I accept the TOS', [validators.Required()])
See the link for the other snippets (view, template, etc).
-7530469 0Yes, you have log errors with console.log and show the LogCat tab in Eclipse. There, Web Console messages (including JS errors) will show up. It's a little verbose so you have to filter to show just the Web Console tags but it works well. Described here: SHOWING CONSOLE CONSOLE.LOG OUTPUT AND JAVASCRIPT ERRORS WITH PHONEGAP ON ANDROID/ECLIPSE
-35770702 0 create yesterday's date folder yyyy-mm-dd using .batI am attempting to create a prior date folder using the below script, and the problem is that it skips the month. To illustrate my point it ends up with 2016-2-
. Thus, any relevant feedback on this would be appreciated.
Ps: Current date from my machine: 3/3/2016
Best,
@echo off setlocal enabledelayedexpansion cls set vbs=%temp%\vbs.vbs > %vbs% echo WScript.Echo DateAdd("d",-1,Date) for /f "tokens=* delims=" %%a in ('cscript //nologo %vbs%') do ( set newfold=%%a ) del %vbs% for /f "tokens=1-3* delims=/ " %%1 in ("%newfold%") do ( set month=%%2&set date=%%3&set year=%%4 md !date!-!month!-!year! echo New folder created = !date!-!month!-!year! )
EDIT: VBScript
using the Weekday()
function
@echo off setlocal EnableDelayedExpansion cls set vbs=%temp%\vbs.vbs >%vbs% echo dateYesterday=DateAdd("d",-1,Date): wdayYesterday=Weekday(dateYesterday): If wdayYesterday=1 Then WScript.Echo DateAdd("d",-2,dateYesterday) Else If wdayYesterday=7 Then WScript.Echo DateAdd("d",-1,dateYesterday) Else WScript.Echo dateYesterday for /f "tokens=* delims=" %%a in ('cscript //nologo %vbs%') do ( set newfold=%%a ) echo dateYesterday = %newfold% ^(assumption: month/day/year^) del %vbs% for /f "tokens=1-3 delims=/ " %%1 in ("%newfold%") do ( set month=%%2 set day=%%1 set year=%%3 ) md %day%-%month%-%year% echo New folder created = %day%-%month%-%year% ^(day/month/year^)
-28859163 0 I think the main problem is you're not actually calling $http.get(), you're just defining it. Also, you should read more about async calls in Angular (they're a real pain, but they get pretty cool after you get a grasp of them).
This got me started: http://chariotsolutions.com/blog/post/angularjs-corner-using-promises-q-handle-asynchronous-calls/ (just make sure you stay away from their official documentation; it's a real mess that's either overcomplicated or over-simplified).
Anyways, for your problem:
Try this in your factory:
app.factory("PlantServiceLIVE", function($http) { var mData = { get_data : function(){ return $http.get('pages/getplants.php').success(function(data) { return mData.data = data; }); } }; return mData; });
Then get the data (after you've received it) in your controller, like this:
app.controller('TestController', function($scope, $http, PlantServiceLIVE) { $scope.click_me = function(){ var wait = PlantServiceLIVE.mData(); wait.then(function(data){ console.log(data); //you should have your data here. $scope.Plants = data; }); } });
Then make it touchable with
<button ng-click="click_me()">Gimme plants</button>
-23425523 0 ThreadLocal instance getting null at some cases Getting ThreadLocal instance as null. Using the following code, I had created new ThreadLocal instance.
private static final ThreadLocal<SimpleDateFormat> inputSdfLocal = new ThreadLocal<SimpleDateFormat>() { protected SimpleDateFormat initialValue() { return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); }; };
Now I am calling ThreadLocal (inputSdfLocal) instance as inputSdfLocal.get().
SimpleDateFormat inputSdf = inputSdfLocal.get();
At this point some time, I am getting ThreadLocal ->inputSdfLocal instance as null. Will anyone please explain, why ThreadLocal instance getting null.
-5311600 0This is just another version of Tom Morgan's accepted answer. It uses division instead of substring to trim the least significant digit off the BIGINT digit column:
SELECT t.Digit/10 ( -- Foreach t, get the Source character that is most abundant (statistical mode). SELECT TOP 1 Source FROM table i WHERE (i.Digit/10) = (t.Digit/10) GROUP BY i.Source ORDER BY COUNT(*) DESC ) FROM table t GROUP BY t.Digit/10 HAVING COUNT(*) = 10
I think it'll be faster, but you should test it and see.
-16137229 0config.assets.initialize_on_precompile = false
Include that in application.rb, ABOVE module APPNAME
I had originally included it inside
class Application < Rails::Application
Edit: actually, the above didn't fix it.
I had to do this
https://devcenter.heroku.com/articles/labs-user-env-compile
-16838277 0Simple addition would work.
DateTime date = DateTime.Parse(txtStartDate.text) + DateTime.ParseExact(t3, "H:mm tt", CultureInfo.InvariantCulture).TimeOfDay;
-12798239 0 simple:
@interface MONBlackStyle : NSObject // << new class, not category + (void)willPresentAlertView:(UIAlertView *)alertView1; @end @interface MONOrangeStyle : NSObject // << new class, not category + (void)willPresentAlertView:(UIAlertView *)alertView1; @end
no category required. of course, the alert parameter is redundant when you use that category on UIAlertView
and of course the definitions of the messages above could call some other category method if access is the issue. also note that in this exact example, the delegate would be set as such: alert.delegate = [MONOrangeStyle class];
that's one step in the right direction but more steps could be taken. good luck.
Searching in projects.trapexit.org for "pubsub" this is what you get: .
Maybe one of these could help you.
-36401315 0I guess it is Maven feature - when you run several goals it stops on first failure (which usually makes sense, e.g. "mvn clean install").
Just run goals separately:
mvn clean test mvn site
-4602766 0 Is there a difference between '=' and In? Is there any differences (perf) writting this request:
Select * from T where PK = 1
or this
Select * from T where PK in (1)
I believe not but i realy don't know how to dispay an execution plan that should assert my feeling.
Thx in advance
-37768605 0Change your location of cache. This will definitely work. By default NPM tries to pickup packages from cache and the default location is sometimes prohibited from reading.
npm config set cache C:\Dev\nodejs\npm-cache --global
Cheers!
-5920088 0myMapView.setStreetView(true);
-7307050 0 As you are root, you can try it su - apache -c "ssh-keygen -t rsa"
I have a little question here. Is there any way to build a server side JS without any use of external software. The reason for this is I am not able to install any software on the webspace but I wanted to experiment with realtime communication with the server and another user for a game or something like this.
If someone knows a way to establish something like this I would be quite happy to hear about it.
EDIT: Guys NOT NodeJS I AM NOT ALLOWED TO INSTALL ANY OTHER SOFTWARE!
-2802269 0 validate linqtosql mapping to a modelI have generated a LinqtoSQL mapping xml file, which I have a valid XSD schema that I check to make sure the XML is correct.
Now I want to check that the field type match the Model/Interface
for example:
checking that the nullable fields are nullable that int are int etc
anyone got any ideas if I can do this?
-9400464 0I think from a technical and programming point of view, it would be cool to pass the data image back.
You could do that with a base64 encoded version of the image, and most modern browsers will support that. You could also do it with the HTML5 canvas object. Documentation is available on the MDN.
However, from a practical point of view, the most maintainable solution is to use an ID and let it make a separate HTTP request. No HTML 5 required, supported in pretty much every browser in use, and you can reuse existing image delivery systems.
If your server is tuned, it will be OK to have that extra HTTP request for the image, and it will be much less CPU load on the server if you are doing a lot of these images.
-5253243 0 "no match for ‘operator=’" error with g++I have a class AP
template<typename T> class AP : public std::auto_ptr<T> { typedef std::auto_ptr<T> Super; public: AP() : Super() { } AP(T* t) : Super(t) { } AP(AP<T>& o) : Super(o) { } };
And a function to return it.
namespace AIR { namespace Tests { namespace { AP<A> CreateGraph() { AP<A> top(A::Create("xyz").release()); ... return top; } AP<A> top; top = CreateGraph();
When I compile the code
AP<A> top; top = CreateGraph();
I got this error message
no match for ‘operator=’ in ‘top = AIR::Tests::<unnamed>::CreateGraph()()’
I added this operator to the AP class, but it doesn't work.
AP<T>& operator=(AP<T>& o) { (*(Super*)this) = o; return *this; }
What's wrong with the class?
top.reset(CreateGraph().release())
solved this issue.
Or in a more fashionable way:
string duration = String.Format($"{(int)seconds.TotalHours}:{seconds.Minutes}:{seconds.Seconds}");
*Edit: And also more readable
-25252744 0This code segment
int* ptr_int; *ptr_int = 10;
is already wrong. Pointer ptr_int was not initialized. So the program has undefined behaviour.
To test your code you could write for example
int main() { int* ptr_int = new int( 10 ); test_session ( &ptr_int ); std::cout << "Hello, world!\n"; delete ptr_int; }
-13923097 0 Android Front-Facing Camera Preview Size I have an app that I am working on that makes use of the front-facing camera on the device. I am trying to set the preview size by getting the list of supported preview sizes and looping through them looking for one that is pretty close. The method that I wrote to do so is basically the same as the one from the OS's own camera app. The method works fine, exactly how I would like it to, that's not why I am here.
I was having problems with the camera preview looking obviously skewed on some devices; either squishing or stretching the preview of the image. I couldn't figure out why it was doing this so I stepped through it and looked at all of the supported preview sizes available to my front-facing camera and found that there were only 2 and neither of them were the correct aspect to be usable. My "surfaceChanged" method in my SurfaceHolder.Callback class is reporting a width and height of 762x480 for the front-facing camera, but of the two supported preview sizes (acquired with cam.getParameters().getSupportedPreviewSizes()) both were in the opposite aspect: 480x800, 320x640.
With these as the only options, it seems impossible to have a preview for my front-facing camera that is not skewed. I know that in versions 2.3 or less, arbitrary values can be used for width and height without regard to supported sizes, but I am trying to make my app work for newer versions of the OS as well. How can I make the preview look correct?
-35046433 1 How do I apply a value from a dataframe based on the value of a multi-index of another dataframe?I have the following:
Dataframe 1 (Multi-index dataframe):
| Assay_A | --------------------------------------------------- Index_A | Index_B | Index_C | mean | std | count | --------------------------------------------------- 128 12345 AAA 123 2 4
Dataframe 2:
Index | Col_A | Col_B | Col_C | mean ------------------------------------- 1 128 12345 AAA 456
where Col_X = Index_X for a,b,c.
I have been spending all morning trying to do the following:
How do I pick the correct mean in dataframe 2 (which has to match up on Col ABC) so I can do mathematical operations on it. For example, I want to take the mean of dataframe 1 and divide it by the correctly chosen mean of dataframe 2.
Ideally, I want to store the results of the operation in a new column. So the final output should look like this:
| Assay_A | ------------------------------------------------------------ Index_A | Index_B | Index_C | mean | std | count | result | ------------------------------------------------------------ 128 12345 AAA 123 2 4 0.26
Perhaps there is an easier way to do this I would be open to any such suggestions as well.
-29197466 0You have to set the source object of the binding, which is the UserControl itself here.
<Image Source="{Binding Source, RelativeSource={RelativeSource AncestorType=UserControl}}"/>
Do not set the DataContext
of the UserControl to itself, because that complicates using your UserControl in common binding scenarios, where it inherits the DataContext from its parent control:
<local:DeletableObjectPresenter Source"{Binding SomeImage}"/>
Here, SomeImage
is a property in the inherited DataContext of the UserControl, which would not be so easily accessible if you had explicitly set the DataContext before.
Please note also that it is not necessary to the set an UriKind
on a Pack URI:
new BitmapImage(new Uri( "pack://application:,,,/DeletableObjectPresenter;component/Resources/StandartView.png"));
-37934048 0 There are two straightforward options for doing this within Git (without using any of the p4 tools). One, probably the better one in general, is (as PetSerAl answered in a comment):
git checkout --theirs "path"; git add "path"
The first part, git checkout --theirs
, extracts the other branch version (the one you are calling "remote" here; that's one of several names various tools use to try to tell which file is which) into the work-tree. The second part, git add
, marks the file as "resolved".
Another (not quite as good in some ways) method is:
git checkout MERGE_HEAD "path"
This looks—and is!—simpler: it tells Git to extract the MERGE_HEAD
version (the --theirs
or "remote" version) of the given path, and as a side effect, marks the file resolved.
In most cases (including yours, here) these two do exactly the same thing.
The one case where they do something different occurs when Git decides that a file was renamed. Consider the following example:
$ mkdir mergetest; cd mergetest; git init Initialized empty Git repository in [...]/mergetest/.git/ $ echo repo for merge example > README $ git add README; git commit -m initial [master (root-commit) 74ad4af] initial 1 file changed, 1 insertion(+) create mode 100644 README
We now have a repository with no files yet (except for a README). Let's make a file with some fairly significant content that Git can detect easily enough even if we modify and rename it:
$ cp /etc/termcap termcap; chmod 644 termcap $ git add termcap; git commit -m 'add termcap' [master de3d189] add termcap 1 file changed, 4666 insertions(+) create mode 100644 termcap
Now let's set up to have two branches, and make changes to the termcap copy in each branch, so that we can get a merge conflict.
$ git branch A; git checkout -b B Switched to a new branch 'B'
In our B branch, let's change the last few lines a bit:
$ tail -3 termcap # # END OF TERMCAP # ------------------------ $ ed termcap 208311 $-1s/TERMCAP/LINE/p # END OF LINE w 208308 q $ git add termcap; git commit -m 'Tron MCP says END OF LINE!' [B 9f40f2d] Tron MCP says END OF LINE! 1 file changed, 1 insertion(+), 1 deletion(-)
Now we'll change the file in an incompatible way in branch A:
$ git checkout A Switched to branch 'A' $ ed termcap 208311 $-1s/TERMCAP/FILE/p # END OF FILE w 208308 q $ git add termcap; git commit -m 'incompatible change' [A 9aae164] incompatible change 1 file changed, 1 insertion(+), 1 deletion(-)
We're almost ready to merge, but that will be somewhat boring, so let's make one more change now: we'll rename termcap
.
$ git mv termcap stocking-cap $ git commit -m rename [A 713eddd] rename 1 file changed, 0 insertions(+), 0 deletions(-) rename termcap => stocking-cap (100%)
Now we can try to merge from B:
$ git merge B Auto-merging stocking-cap CONFLICT (content): Merge conflict in stocking-cap Automatic merge failed; fix conflicts and then commit the result. $ git status On branch A You have unmerged paths. (fix conflicts and run "git commit") Unmerged paths: (use "git add <file>..." to mark resolution) both modified: stocking-cap no changes added to commit (use "git add" and/or "git commit -a")
Note that Git now refers to the file, not as termcap
, but as stocking-cap
. The conflict is between our Tron-ish END OF LINE phrase, which we applied to a file named termcap
, and our END OF FILE
phrase, which we applied to termcap
as well but then we renamed to stocking-cap
.
If we attempt to check out termcap
from MERGE_HEAD
, we get an error instead:
$ git checkout MERGE_HEAD stocking-cap error: pathspec 'stocking-cap' did not match any file(s) known to git.
The file is known, in the tip of branch B
(aka MERGE_HEAD
), as termcap
, not as stocking-cap
. But if we git checkout --theirs
it works:
$ git checkout --theirs stocking-cap $ tail -3 stocking-cap # # END OF LINE # ------------------------
There we go: the file is still renamed, but we got "their" version, which in MERGE_HEAD is known as termcap
. The file is still in unmerged state though, as git status
will show (try it), or as seen in git ls-files --stage
:
$ git ls-files --stage 100644 666e31eff490e17863f3261a0c16df0cdf8ca69f 0 README 100644 30e251d0e75b4905449a052b5f04e316b15ffd46 1 stocking-cap 100644 941c1fa9c08e7dc0c5b8fd8e033708e6a66e4166 2 stocking-cap 100644 f6282a43f57b2acf2561ccbc58b817e21ae13b07 3 stocking-cap
We must git add stocking-cap
to resolve it:
$ git add stocking-cap $ git status -s M stocking-cap
and now we can commit:
$ git commit -m 'completed the merge' [A c0a3dad] completed the merge
and view diffs:
$ git diff A B diff --git a/stocking-cap b/termcap similarity index 100% rename from stocking-cap rename to termcap
and logs:
$ git log --decorate --oneline --graph --all * c0a3dad (HEAD -> A) completed the merge |\ | * 9f40f2d (B) Tron MCP says END OF LINE! * | 713eddd rename * | 9aae164 incompatible change |/ * de3d189 (master) add termcap * 74ad4af initial
and so on.
You may use git checkout MERGE_HEAD
, which extracts the file from the other commit (B
in our example here) and lets you skip the git add
step, but requires the file name to be unchanged. Or, you may use git checkout --theirs
, which extracts the file from the other commit, and handles renames, but forces you to git add
the result.
I'm developing an application using android studio, I'm completely new to android and this is my second application, I've searched everywhere to find a way to open an url and to read the Json content from it, these are the codes i have found, but the problem is where it arrives to "con.connect();" it says Unfortunately your application has stopped working i can't read even the string from that url, i really don't know what the problem is, so i hope you can help me solving this problem.
public String webrequest(String url1){ try { URL url = new URL(url1); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); con.connect(); if (con != null) { try { BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(),"UTF-8")); String input; while ((input = br.readLine()) != null) { System.out.println(input); } br.close(); return input.toString(); } catch (IOException e) { e.printStackTrace(); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } //return input; return ""; }
And by the way, i have got the internet permission in android manifest. Thank you for your help.
-15191234 0
- The building is a graph, rooms are vertices, hallways are edges connecting them. Therefore this is an undirected connected graph.
- You can solve this by getting the weight of graph's minimal spanning tree, then doing complete weight minus the weight of MST - the result is sum of weights of hallways that can be removed.
Yes, both of these are correct (modulo the nitpick that the building is not a graph with rooms as vertices and hallways as edges, but can be viewed as such). And if you view it thus, the difference between the total weight of the original graph and the total weight of a minimum spanning tree is the maximal possible reduction of weight without making some rooms unreachable from others (i.e. making the graph disconnected).
So I see two possibilities,
Without any further information, I would consider 1 more likely.
Is there any other way to solve this problem? I would happily try anything with the grading server.
Since you need to find the weight of an MST, I don't see how you could do it without finding an MST. So the other ways are different algorithms to find an MST. Kruskal's algorithm comes to mind.
-29641642 0Does it help when you force the time filter to kick in only after the client filter has run?
FI like in this example:
;WITH ClientData AS ( SELECT [E2].[CompanyId] ,[E2].[Time] ,[E1].[Id] ,[E1].[Status] FROM [dbo].[SplittedSms] AS [E1] INNER JOIN [dbo].[Sms] AS [E2] ON [E1].[SmsId] = [E2].[Id] WHERE [E2].[CompanyId] = 4563 AND ([E1].[NotifiedToClient] IS NULL) ) SELECT TOP 10 [CompanyId] ,[Id] ,[Status] FROM ClientData WHERE [Time] > '2015-04-10'
-34568156 0 strtok return value taking bad value after calling malloc I'm making a code that retrieve each every 3 lines of a .csv file and put the values of those lines in a double array (i use a double array), but in the middle of the loop (k=5) i have an issue with the value of "token" which become empty just after i do a malloc on plaintexts[k].
I understand that the problem comes from the call of malloc but i don't know how to fix it.
int main(){ unsigned char **plaintexts=malloc(sizeof(unsigned char)*30); int i,j,k; FILE *fp; unsigned char *token; unsigned char *str=malloc(sizeof(char)*600); const char s[2] = ","; fp = fopen("aes_traces.csv","r"); double temp; i=0; k=0; while(fgets(str,600,fp)!=NULL){ if(i==0 || i%3==0){ plaintexts[k]=malloc(sizeof(unsigned char)*60); puts(str); token = strtok(str,s); j=0; do{ temp = strtod(token,NULL); plaintexts[k][j] = (unsigned char) (temp); printf("plaintexts[%d][%d] = %d\n",k,j,plaintexts[k][j]); token=strtok(NULL,s); j++; }while(token != NULL); k++; } i++; return 0; }
-7974368 0 Qt - unable to terminate console app after loading library I have a problem with QT console application. At the beginning of my code in main, i load a dll using QLibrary. When i exit the app by returning 0 if the mode i checked from my dll is incorrect, the app will crash; stating "QObject:: shared object was deleted directly. The program is malformed and may crash.". Can anyone help me in this?
Here's my code
int mode = -1; QLibrary myLib("checkmode.dll", 0); myLib.load(); if (myLib.isLoaded()) { typedef int (*GetModeStatusFunction)(char *, int, char *); GetModeStatusFunction GetModeStatus = (GetModeStatusFunction) myLib.resolve("GetModeStatus"); if (GetModeStatus) { mode = GetModeStatus("localhost", 10, NULL); } } if (mode!= 0) { return 0; // crash when return }
-16939651 0 Waiting for multiple asynchronous JSON queries to finish before running code I am looking to run multiple different JSON request simultaneously, and then only perform a function once they have either completed or returned an error message (404 etc.). Here's what I have so far, but the function finished
doesn't remember the variables from either request. Any ideas?
function socialPosting(a_date,a_title,a_source,a_thumbnail,a_url) { socialPosts[socialPosts.length] = {date: a_date, title: a_title, source: a_source, thumbnail: a_thumbnail, url: a_url}; //console.log(socialPosts[amount]); //console.log(amount); } function finished(source) { if (source == "Twitter") { var Twitter = "True"; } if (source == "YouTube") { var YouTube = "True"; } console.log(source); //diagnostics console.log(Twitter); //diagnostics console.log(YouTube); //diagnostics if (Twitter == "True" && YouTube == "True") { console.log(socialPosts[0]); //Should return after both requests are complete } } $.getJSON('https://gdata.youtube.com/feeds/api/videos?author=google&max-results=5&v=2&alt=jsonc&orderby=published', function(data) { for(var i=0; i<data.data.items.length; i++) { //for each YouTube video in the request socialPosting(Date.parse(data.data.items[i].uploaded),data.data.items[i].title,"YouTube",data.data.items[i].thumbnail.hqDefault,'http://www.youtube.com/watch?v=' + data.data.items[i].id); //Add values of YouTube video to array } finished("YouTube"); }); $.getJSON("https://api.twitter.com/1/statuses/user_timeline/twitter.json?count=5&include_rts=1&callback=?", function(data) { var amount = socialPosts.length; for(var i=0; i<data.length; i++) { socialPosting(Date.parse(data[i].created_at),data[i].text,"Twitter"); //Add values of YouTube video to array } finished("Twitter"); });
-16561639 0 Horizontal dashed line stretched to container width I have a layout contained within a ScrollViewer
in which I need to draw a horizontal dashed line that stretches to the full width of the container. The closest I've managed is the following
<ScrollViewer HorizontalScrollBarVisibility="Auto"> <StackPanel> <Button Width="400" Height="50" VerticalAlignment="Top" Margin="10" /> <Line HorizontalAlignment="Stretch" VerticalAlignment="Bottom" Stroke="Black" X2="{Binding ActualWidth, RelativeSource={RelativeSource Self}}" StrokeDashArray="2 2" StrokeThickness="1" /> </StackPanel> </ScrollViewer>
This nearly works, however once the container (in my case a window) has been enlarged, the line doesn't shrink back down to the appropriate size when the container is sized back down. The below is the screenshot of the same window after I have horizontally sized the window up and down.
Note that the fact that the line is dashed is important as it means that solutions that involve stretching the line don't work (the dashes appear stretched).
I know that this is because of the X2="{Binding ActualWidth, RelativeSource={RelativeSource Self}}"
binding (by design the line is always the widest thing in the scrollable region, so when I size the window down the scrollable region the line defines the width of the scrollable region), however I can't think of a solution.
How can I fix this problem?
Screenshot of why using ViewportWidth
doesn't work
If the reader is reporting true
from Read()
, then your stored procedure is definitely returning a row (or rows).
If you call the SP directly (SSMS etc), that will quickly tell you whether a row is returned. A row with a null in every column is still a row. Two options:
For example. If the first column must be non-null for a "real" row, then simply:
if(!reader.IsDBNull(0)) Count++;
Which ignores the row if the first cell is null.
-12675403 0Because you haven't provided any definite HTML markup, only a generic description of your problem, I provide you a link to http://css-tricks.com/centering-in-the-unknown/ Here you can find various CSS techniques to center content both vertically and horizontally.
jQuery is not necessary to center content, I believe you will manage it with proper HTML markup coupled with some CSS.
Fiddle ( http://jsfiddle.net ) will be helpful, though.
-13434450 0 How to make text bigger in label?I am wanting to use NSMutableAttributedString to change part of the original string and make part of the text bigger then the original. However, it is not working because of something very minor that I can't figure out. Here is my code:
NSString *combineString = [NSString stringWithFormat:@"%@", ...]; NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:combineString]; NSRange selectedRange = NSMakeRange(5, 4); // 4 characters, starting at index 22 [string beginEditing]; [string addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:50] range:selectedRange]; [string endEditing]; mainCell.label.text = combineString;
-12922834 0 Reflection API allows one to manipulate/access data that is not accessable otherwise - or some data on the class that is unknown at compile time.
In here, it is really not needed. All you need is to put()
the element into the map, it will "remove" the old value from the key you just inserted (if it is already there) and associate it (the key) with the newly added value.
So, basically - all you need to do is myMap.put(key,newValue)
, and the implementation of the Map
(assuming it is a correct one, of course) will take care of the rest.
If you want to store the data between runs of the program - you will have to save it (the map) on disk. In order to do so, you can use serialization, or if you can use Properties
in some cases.
Make sure that you load the map from disk once the program starts, or you will not see the values you stored.
I have a list with 12 elements , within those elements I have a div
What I want to achieve its that every div will have diffrent size
So I use nth-child on the li
elemnt to set diffrent size to every div
element
But the 12 one dosen't work, the rest nth-child workt perfectly
My list:
<ul class="size"> <li data-radius="1"><div class="circleSize"></div> <br /> 2px </li> <li data-radius="2"><div class="circleSize"></div> <br /> 4px </li> <li data-radius="1"><div class="circleSize"></div> <br /> 2px </li> <li data-radius="3"><div class="circleSize"></div> <br /> 6px </li> <li data-radius="4"><div class="circleSize"></div> <br /> 8px </li> <li data-radius="5"><div class="circleSize"></div> <br /> 10px </li> <li data-radius="6"><div class="circleSize"></div> <br /> 12px </li> <li data-radius="7"><div class="circleSize"></div> <br /> 14px </li> <li data-radius="8"><div class="circleSize"></div> <br /> 16px </li> <li data-radius="9"><div class="circleSize"></div> <br /> 18px </li> <li data-radius="10"><div class="circleSize"></div> <br /> 20px </li> <li data-radius="11"><div class="circleSize"></div> <br /> 22px </li> <li data-radius="12"><div class="circleSize"></div> <br /> 24px </li> </ul>
My css:
.circleSize { background-color:black; display:inline-block; vertical-align: middle; border-radius: 50%; } .size li:nth-child(1) .circleSize { width:2px; height:2px; } .size li:nth-child(2) .circleSize { width:4px; height:4px; } .size li:nth-child(3) .circleSize { width:6px; height:6px; } .size li:nth-child(4) .circleSize { width:8px; height:8px; } .size li:nth-child(5) .circleSize { width:10px; height:10px; } .size li:nth-child(6) .circleSize { width:12px; height:12px; } .size li:nth-child(7) .circleSize { width:14px; height:14px; } .size li:nth-child(8) .circleSize { width:16px; height:16px; } .size li:nth-child(9) .circleSize { width:18px; height:18px; } .size li:nth-child(10) .circleSize { width:20px; height:20px; } .size li:nth-child(11) .circleSize { width:22px; height:22px; } .size li:nth-child(12) .circleSize { width:24px; height:24px; }
My jsfiddle: https://jsfiddle.net/4nvug6og/
-40150481 0This is why it is a bad idea to declare most binary operators as member functions - they are asymmetric. You need
class Kinetics; Kinetics operator *(const Kinetics& k, double c); Kinetics operator *(double c, const Kinetics&k) { return k*c; } class Kinetics{ double x; double y; double z; public: Kinetics(); Kinetics(double x_, double y_, double z_); Kinetics(const Kinetics & obj); ~Kinetics(); double get_x(); void set_x(double x_); Kinetics operator + (const Kinetics & obj); friend Kinetics operator * (const Kinetics& k, double c); void operator = (const Kinetics & obj); };
-19973785 0 Ok, lets try to make sure that the image is visible in QWebView at all and you indeed have a problem with PDF conversion. So you need to run this and see if it works:
import sys from PyQt4 import QtGui, QtCore, QtWebKit class MyWin(QtGui.QWidget): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.setLayout(QtGui.QVBoxLayout()) self.view = QtWebKit.QWebView(self) self.layout().addWidget(self.view) self.view.setHtml(''' ... <img src="star.jpg" /> ... ''', QtCore.QUrl.fromLocalFile("/var/www/icons/") ) if __name__ == '__main__': app = QtGui.QApplication(sys.argv) win = MyWin() win.show() sys.exit(app.exec_())
-40136996 0 Does my string full of various delimiters have a specific delimiter in use, but not in the data contained in the string? If we have the new delimiter in place, I know not to use the old one. If my string uses the "," for a delimiter I will continue to use it (and not allow it in data) but if it doesn't I want to use the new delimiter "!".
We have a string like “Web Distribution:Walnut Creek & State Specialty - At Home::1757:1-1-3~1:1-1-3~2:1-1-2~0-0~=~1~Yes, complete today while at store~0.b Willing:::”
We are doing a test to see if it used ‘!’ as a delimiter string.Contains(“!”)
If it does then we are cool
If it doesn’t
We are testing to see if ‘,’ is used as a delimiter We are doing a simple test of string.Contains(“,”)
This is where we have a problem. “Yes, complete today while at store”
So how can I say, great it has a “,” but if it’s between two ~ don’t worry about it. Use the ! as the delimiter moving forward and let the “,” live in the question and alert plugin.
If the text looks like “Web Distribution:Walnut Creek & State Specialty - At Home::1757:1-1-3~1:1-1-3~2:1-1-2~0-0~=~1~Yes, complete today while at store~0.b Willing^1-1-2~0-0~=~2~Yes, complete later via email~0.b Willing::1-1-2~0-0~=~0~~0.b - Willing!1-1-3~0-0~=~0~~0.c - Email:”
It has a “!” and we are cool
my current code
Friend Const mcItemDelimiterOld As String = "," Friend Const mcItemDelimiterNew As String = "!" Public Shared mcItemDelimiter As String = "!" If sDelimitedText.Contains(mcItemDelimiterNew) Then mcItemDelimiter = mcItemDelimiterNew Else If sDelimitedText.Contains(mcItemDelimiterOld) Then mcItemDelimiter = mcItemDelimiterOld Else mcItemDelimiter = mcItemDelimiterNew End If End If
-7795852 0 Don't know if it is steel relevant but here is the solution:
TextBox _textBox; protected override void SetupEditControls() { base.SetupEditControls(); _textBox = (TextBox)EditControl; var value = CustomerTypeBox.Value ?? string.Empty; if (String.IsNullOrEmpty(value.ToString())) { _textBox.Text = "Default text"; } else { _textBox.Text = value.ToString(); } if (_textBox != null) EditControl.Parent.Controls.Add(_textBox); } public override void ApplyEditChanges() { var customerTypeBoxValue = _textBox.Text; if (customerTypeBoxValue != null) { SetValue(customerTypeBoxValue); } }
Default value for property is also possible to set in admin mode.
-40807215 0 What is the role of the curly brace in this case in Perl?The following print statements are valid in accessing the 1st element of the array reference
my $aref = [6, 7, 8]; print $aref->[0]; print $$aref[0]; print ${$aref}[0];
What is the reason for allowing/using the curly brace in the 3rd print? Does it work by design or by chance?
-7770242 0If you are happy with SNI SSL support, no further configuration should be necessary. Use this gist to determine whether a request is made with an SSL-encrypted connection.
-31769123 0 What is difference of "Array" & "Object" in JSWhat is difference of "Array" & "Object" in JS. I know only that:
var variable=[1, 2, 3, "Array"] var varibale1={Fist:1, Second:"Some String", Third:"Object"}
-397641 0 FindBugs for .NET In Java is this nice tool called FindBugs. Is there something similar in .Net?
-14655079 0 Git push "permission denied"I am attempting to push my code to my github account, however whenever I try, i get this
Pushing to git@github.com:AlphaModder/Space-Dimension-Mod.git Permission denied (publickey). fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists.
Question: how can I avoid that "Permission Denied"? Is the GitHub remote address a valid one?
-847842 0Option #2 is fairly standardized. Always put OK before Cancel.
Microsoft recommends 75pix by 23pix for both buttons.
-39896984 0Check the URL in Facebook Debug Tool, https://developers.facebook.com/tools/debug/. Scrape your URL again and again and check. It will display the error that you are missing.
The minimum image size is 200 x 200 pixels. If you try to use an image smaller than this you will see an error in the Sharing Debugger.
Refer the link,
https://developers.facebook.com/docs/sharing/best-practices#images
-1162850 0I've had some success in solving this problem of mine. Here are the details, with some explanations, in case anyone having a similar problem finds this page. But if you don't care for details, here's the short answer:
Use PTY.spawn in the following manner (with your own command of course):
require 'pty' cmd = "blender -b mball.blend -o //renders/ -F JPEG -x 1 -f 1" begin PTY.spawn( cmd ) do |stdout, stdin, pid| begin # Do stuff with the output here. Just printing to show it works stdout.each { |line| print line } rescue Errno::EIO puts "Errno:EIO error, but this probably just means " + "that the process has finished giving output" end end rescue PTY::ChildExited puts "The child process exited!" end
And here's the long answer, with way too many details:
The real issue seems to be that if a process doesn't explicitly flush its stdout, then anything written to stdout is buffered rather than actually sent, until the process is done, so as to minimize IO (this is apparently an implementation detail of many C libraries, made so that throughput is maximized through less frequent IO). If you can easily modify the process so that it flushes stdout regularly, then that would be your solution. In my case, it was blender, so a bit intimidating for a complete noob such as myself to modify the source.
But when you run these processes from the shell, they display stdout to the shell in real-time, and the stdout doesn't seem to be buffered. It's only buffered when called from another process I believe, but if a shell is being dealt with, the stdout is seen in real time, unbuffered.
This behavior can even be observed with a ruby process as the child process whose output must be collected in real time. Just create a script, random.rb, with the following line:
5.times { |i| sleep( 3*rand ); puts "#{i}" }
Then a ruby script to call it and return its output:
IO.popen( "ruby random.rb") do |random| random.each { |line| puts line } end end
You'll see that you don't get the result in real-time as you might expect, but all at once afterwards. STDOUT is being buffered, even though if you run random.rb yourself, it isn't buffered. This can be solved by adding a STDOUT.flush
statement inside the block in random.rb. But if you can't change the source, you have to work around this. You can't flush it from outside the process.
If the subprocess can print to shell in real-time, then there must be a way to capture this with Ruby in real-time as well. And there is. You have to use the PTY module, included in ruby core I believe (1.8.6 anyways). Sad thing is that it's not documented. But I found some examples of use fortunately.
First, to explain what PTY is, it stands for pseudo terminal. Basically, it allows the ruby script to present itself to the subprocess as if it's a real user who has just typed the command into a shell. So any altered behavior that occurs only when a user has started the process through a shell (such as the STDOUT not being buffered, in this case) will occur. Concealing the fact that another process has started this process allows you to collect the STDOUT in real-time, as it isn't being buffered.
To make this work with the random.rb script as the child, try the following code:
require 'pty' begin PTY.spawn( "ruby random.rb" ) do |stdout, stdin, pid| begin stdout.each { |line| print line } rescue Errno::EIO end end rescue PTY::ChildExited puts "The child process exited!" end
-6835075 0 milliseconds until next 5th second So I want to do some monitoring and I want it to be on every fifth minute, so for example if the application starts at 1:47 monitor everything until 1:50 and then reset. I currently have this working for hour but I need to cut it down to every fifth minute and I'm having a little trouble coming up with the math.
I get all of the current time information
Calendar currentCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT")); long currentTimeInMillis = currentCalendar.getTimeInMillis(); int hr = currentCalendar.get(Calendar.HOUR_OF_DAY); int min = currentCalendar.get(Calendar.MINUTE); int sec = currentCalendar.get(Calendar.SECOND); int millis = currentCalendar.get(Calendar.MILLISECOND);
Now I need to find the next fifth minute, for hour I have this which works.
millisUntilNextHour = currentTimeInMillis + ((60L - min) * SECONDS_IN_MINUTE * 1000L) + ((60 - sec) * 1000L) + (1000L - millis);
Can anybody think of a way similar to above to get the milliseconds to the closest fifth minute?
-16816504 0 How to change text of wxComboBox based on it's selected itemHow to change the value of a wxComboBox
when user selects an item from its own drop down list? I have added EVT_COMBOBOX(ID_WXCOMBODATETIME, CNFrm::WxComboDateTimeSelected)
to my EVENT_TABLE
.
void CNFrm::WxComboDateTimeSelected(wxCommandEvent& event ) { WxComboDateTime->SetValue ( "ljlk" ); }
trying SetValue
in the function just empties the control, it doesn't set it.
Any help is appreciated.
-27015918 0How about:
lines = out.lines do_something_1(lines.first) lines[1..-2].each do |line| do_something_2(line) end do_something_3(lines.last)
This code will do some action on the first line, some other action on all lines except the first and the last, and a third action on the last line.
-28691601 0 How to change the variable to find in a FOR/DO statement | BatchHow would I change the variable that I look for in a For/Do Statement.
@ECHO off set Riddle=The Bird In The The Bush SET /a count=0 FOR (The) IN (%Riddle%) DO SET /a count=%count%+1 ECHO %count%
In this case "The" is the variable that I desire to look for,
But I don't think that's the correct formatting
Output:
3
-23544916 0 Gitlab API Access Connection timed out I just installed Gitlab and I have an error during the gitlab-shell self check.
The command returns :
root@git:/home/git/gitlab# sudo -u git -H bundle exec rake gitlab:check RAILS_ENV=production Checking Environment ... Git configured for git user? ... yes Checking Environment ... Finished Checking GitLab Shell ... GitLab Shell version >= 1.9.3 ? ... OK (1.9.3) Repo base directory exists? ... yes Repo base directory is a symlink? ... no Repo base owned by git:git? ... yes Repo base access is drwxrws---? ... yes Satellites access is drwxr-x---? ... yes update hook up-to-date? ... yes update hooks in repos are links: ... Thibaud / thibaud-dauce ... repository is empty Running /home/git/gitlab-shell/bin/check Check GitLab API access: /usr/local/lib/ruby/2.0.0/net/http.rb:878:in `initialize': Connection timed out - connect(2) (Errno::ETIMEDOUT) from /usr/local/lib/ruby/2.0.0/net/http.rb:878:in `open' from /usr/local/lib/ruby/2.0.0/net/http.rb:878:in `block in connect' from /usr/local/lib/ruby/2.0.0/timeout.rb:52:in `timeout' from /usr/local/lib/ruby/2.0.0/net/http.rb:877:in `connect' from /usr/local/lib/ruby/2.0.0/net/http.rb:862:in `do_start' from /usr/local/lib/ruby/2.0.0/net/http.rb:851:in `start' from /home/git/gitlab-shell/lib/gitlab_net.rb:76:in `get' from /home/git/gitlab-shell/lib/gitlab_net.rb:43:in `check' from /home/git/gitlab-shell/bin/check:11:in `<main>' gitlab-shell self-check failed Try fixing it: Make sure GitLab is running; Check the gitlab-shell configuration file: sudo -u git -H editor /home/git/gitlab-shell/config.yml Please fix the error above and rerun the checks. Checking GitLab Shell ... Finished Checking Sidekiq ... Running? ... yes Number of Sidekiq processes ... 1 Checking Sidekiq ... Finished Checking LDAP ... LDAP is disabled in config/gitlab.yml Checking LDAP ... Finished Checking GitLab ... Database config exists? ... yes Database is SQLite ... no All migrations up? ... yes Database contains orphaned UsersGroups? ... no GitLab config exists? ... yes GitLab config outdated? ... no Log directory writable? ... yes Tmp directory writable? ... yes Init script exists? ... yes Init script up-to-date? ... yes projects have namespace: ... Thibaud / thibaud-dauce ... yes Projects have satellites? ... Thibaud / thibaud-dauce ... can't create, repository is empty Redis version >= 2.0.0? ... yes Your git bin path is "/usr/bin/git" Git version >= 1.7.10 ? ... yes (1.7.10) Checking GitLab ... Finished
Of course, Gitlab is running :
root@git:/home/git/gitlab# service gitlab status The GitLab Unicorn web server with pid 1543 is running. The GitLab Sidekiq job dispatcher with pid 1736 is running. GitLab and all its components are up and running.
And my config file :
root@git:/home/git/gitlab# sudo -u git -H cat /home/git/gitlab-shell/config.yml # GitLab user. git by default user: git # Url to gitlab instance. Used for api calls. Should end with a slash. gitlab_url: "http://git.thibaud-dauce.fr/" http_settings: # user: someone # password: somepass # ca_file: /etc/ssl/cert.pem # ca_path: /etc/pki/tls/certs self_signed_cert: false # Repositories path # Give the canonicalized absolute pathname, # REPOS_PATH MUST NOT CONTAIN ANY SYMLINK!!! # Check twice that none of the components is a symlink, including "/home". repos_path: "/home/git/repositories" # File used as authorized_keys for gitlab user auth_file: "/home/git/.ssh/authorized_keys" # Redis settings used for pushing commit notices to gitlab redis: bin: /usr/bin/redis-cli host: 89.234.146.59 port: 6379 # socket: /tmp/redis.socket # Only define this if you want to use sockets namespace: resque:gitlab # Log file. # Default is gitlab-shell.log in the root directory. # log_file: "/home/git/gitlab-shell/gitlab-shell.log" # Log level. INFO by default log_level: INFO # Audit usernames. # Set to true to see real usernames in the logs instead of key ids, which is easier to follow, but # incurs an extra API call on every gitlab-shell command. audit_usernames: false
I already try to replace in Redis conf host: 127.0.0.1
to host: 89.234.146.59
I also try to add 89.234.146.59 git.thibaud-dauce.fr
in /etc/hosts
I have a server running Debian 7 32bits with a container LXC for Gitlab, Ruby is version 2.0.0. I have the same error when I try to push a repo (but I can create one online with the web app)
Do you have any idea ? I really look everywhere and found no solution...
-7312993 0try require_once($_SERVER['DOCUMENT_ROOT'] . '/sms/test.php');
I solved my issue by using DIFFBOT Article API and the link of API is https://www.diffbot.com.
-14813778 0 MySQLSyntaxErrorException - Invalid Parameters in Prepared StatementI Have a code Like Below. I have Tried the Other Solutions in stack but nothing seems to be Working. The Java code which generates the Error is as Shown Below.
public Connection getConnection() { try { conn = DriverManager.getConnection(CONNSTR, USER, PASS); return conn; } catch (SQLException e) { e.printStackTrace(); return null; } } public boolean AuthenticateUser() { String UserName = "User"; String Password = "Password"; try { PreparedStatement pstmt = null; ResultSet rs = null; conn = getConnection(); String strSQL = "SELECT UserName " + " FROM Users " + " WHERE UserId = ? AND " + " Password = ?"; pstmt = (PreparedStatement) conn.prepareStatement(strSQL); pstmt.setString(1, UserName); pstmt.setString(2, Password); System.out.println(strSQL); rs = pstmt.executeQuery(strSQL); System.out.println(rs.getRow()); rs.last(); int TotalRows = rs.getRow(); System.out.println(TotalRows); if(TotalRows > 0) return true; else return false; } catch (SQLException e) { e.printStackTrace(); return false; } }
The Table Structure of the Database is as Given Below
CREATE TABLE Users(Id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, UserName VARCHAR(255), UserId VARCHAR(255), Password VARCHAR(255))
The error is As given Below in Image
The Exception are as Below
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? AND Password = ?' at line 1 at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) at java.lang.reflect.Constructor.newInstance(Unknown Source) at com.mysql.jdbc.Util.handleNewInstance(Util.java:411) at com.mysql.jdbc.Util.getInstance(Util.java:386) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1052) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3609) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3541) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2002) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2163) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2618) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2568) at com.mysql.jdbc.StatementImpl.executeQuery(StatementImpl.java:1557) at com.apryll.db.util.dbUtil.AuthenticateUser(dbUtil.java:55) at com.apryll.db.Login.doPost(Login.java:42) at javax.servlet.http.HttpServlet.service(HttpServlet.java:641) at javax.servlet.http.HttpServlet.service(HttpServlet.java:722) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:395) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:250) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source)
-34786253 0 if value null in radio button list does not show radio button mvc4 I have in model having the questions and answer list. In some of the questions having 4 options and some of the questions having the 2 options. I am getting the options from the back end and i'm binding from model class into the razor view. Now if the answer value null means radio button is showing but i don't want to radio button if the radio button option value nulls.
@for (int j = 0; j < Model.Count; j++) { i++; <div class="panel-heading online-test" role="tab" id=""> <h5 class="panel-title"> @Html.HiddenFor(m => m[j].ID) @Html.HiddenFor(m => m[j].SkillId) @i) @Html.DisplayFor(m => m[j].QuestionText) </h5> </div> foreach (var k in Model[j].Options) { <div class="panel-collapse"> <div class="panel-body online-test-options"> <div class="input-group"> <div class="col-lg-12" id="radiolist"> @Html.RadioButtonFor(m => m[j].SelectedAnswer, "A") <label for="@k.AnswerId">@k.Option1</label> </div> <div class="col-lg-12"> @Html.RadioButtonFor(m => m[j].SelectedAnswer, "B") <label for="@k.AnswerId">@k.Option2</label> </div> <div class="col-lg-12"> @Html.RadioButtonFor(m => m[j].SelectedAnswer, "C") <label for="@k.AnswerId">@k.Option3</label> </div> <div class="col-lg-12"> @Html.RadioButtonFor(m => m[j].SelectedAnswer, "D") <label for="@k.AnswerId">@k.Option4</label> </div> </div> </div> </div> } } public class QuestionsModel { public decimal ID { set; get; } public decimal SkillId { get; set; } public string QuestionText { set; get; } public List<Answer> Options { set; get; } public string SelectedAnswer { set; get; } public QuestionsModel() { Options = new List<Answer>(); } } public class Answer { public int AnswerId { get; set; } public string Option1 { set; get; } public string Option2 { set; get; } public string Option3 { set; get; } public string Option4 { set; get; } } public class Evaluation { public List<QuestionsModel> Questions { set; get; } public Evaluation() { Questions = new List<QuestionsModel>(); } }
Please help to solve.. Thanks in Advance.
-33196610 0driver.cs(19.25):error 1061: 'calculator' does not contain a definition for 'addition' and no extension method 'addition' accepting a first argument of type 'calculator' could be found
As Matti Virkkunen has pointed already this is because method is private
.
Normally if method is private
and it is in the same project as console app, you'll get compile time error : "method is inaccesible due to its protection level".
Because it's in another project it's not inaccessible but completely invisible for console app.
P.S. You can still access your private method using reflection :
static void Main(string[] args) { calculator calc = new calculator(); var addition = calc.GetType().GetMethod("addition", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); var result = addition.Invoke(calc, new object[] { 5, 10 }); Console.WriteLine(result); }
Output : 15
I'm parallelizing some back-end code and trying not to break interfaces. We have several methods that return Dictionary and internally, I'm using ConcurrentDictionary to perform Parallel operations on.
What's the best way to return Dictionary from these?
This feels almost too simple:
return myConcurrentDictionary.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
I feel like I'm missing something.
-31823366 0b & 1
tests if b is odd. If it is, result
is set to tmp * power
.
b >>= 1
divides b by 2. If the result is non-zero, tmp
is set to power
, and power
is set to tmp * tmp
.
Eventually, b
is divided by 2 so much that it reaches zero, which ends the while
loop.
The algorithm is a generalization of so-called "Russian Peasant multiplication" called "Exponentiation by squaring". The same basic process can be used for exponentiation instead of multiplication, by squaring the intermediate result (which we see in the second if
test) rather than doubling.
Time complexity proportional to the highest set bit in b
; if the highest set bit in b
is bit K then the loop will iterate K times. That is, time complexity is proportional to the base 2 logarithm of b.
For a single-server LAMP site (which is usually under quite high load), what is best way to use memcache?
Does it make sense to run the memcache daemon on the same server as the application, or is that just going to take valuable memory away from MySQL, giving a net performance loss. Does it even make sense to use memcache in this scenario- or is the best solution to always have dedicated servers for memcache?
I appreciate that profiling the site before and after would be required to really answer this question, but I would rather not do that at this stage on the live site. Especially as someone out there certainly knows the answer off the top of their head.
-24032406 0Some like that:
(function ($) { "use strict"; $(document).ready(function () { if ($.fn.plot) { var dataPie = [{ label: "Samsung", data: <?php echo $data1 ?> }]; } }); });
-30781849 0 Switched to PDO and it's working now. Thank you!
-21104959 0I've never had success getting nested routes to work by simply passing the object in question as the url parameter of link_to
... Plus (and maybe it's just me) I like my templates to be a bit more "explicit" than that.
A couple things you could do:
<%= link_to project.name, url_for([@client, project]) %>
or
<%= link_to project.name, client_project_path(@client, project) %>
I bet you are looking for templates.
D has a great language reference that is free online.
-30524517 0How I solved it:
I created a file version.properties in the root of my android project and added the versioncode in it.
Then I created method called getCurrentVersionCode() in my build.gradle file that reads the current versioncode.
Code:
def getCurrentVersionCode() { def versionPropsFile = file('version.properties') def Properties versionProps = new Properties() versionProps.load(new FileInputStream(versionPropsFile)) return versionProps['version_code'].toInteger() }
I also created a method to generate a new code:
Code:
// http://stackoverflow.com/questions/30523393/auto-increment-versioncode-only-on-releases // def setUpdatedVersionCode() { def versionPropsFile = file('version.properties') def Properties versionProps = new Properties() def code = getCurrentVersionCode() + 1 versionProps['version_code'] = code.toString() versionProps['version_name'] = generateVersionName() versionProps.store(versionPropsFile.newWriter(), null) }
and then I created a task that triggers on a QA build.
Code:
task('increaseVersionCode') << { setUpdatedVersionCode() } tasks.whenTaskAdded { task -> if (task.name == 'assembleQaRelease') { task.dependsOn 'increaseVersionCode' } }
That way it saves the versioncode in a separate file so I don't need to edit my build.gradle.
-2383717 0RCW's should be (from what I know) of the special type System.__ComObject, however probably what you want to do is call Marshal.IsComObject which will tell you if the object is a runtime wrapper or not. In a quick test a COM created object via that route ends up as a direct managed object and loses the COM wrapper.
-34544306 0I was having the same problem today, highlighting the selected tags ranging over multiple tags. The solution:
Refer the code below , for further clarification.
function getRangeObject(selectionObject){ try{ if(selectionObject.getRangeAt) return selectionObject.getRangeAt(0); } catch(ex){ console.log(ex); } } document.onmousedown = function(e){ var text; if (window.getSelection) { /* get the Selection object */ userSelection = window.getSelection() /* get the innerText (without the tags) */ text = userSelection.toString(); /* Creating Range object based on the userSelection object */ var rangeObject = getRangeObject(userSelection); /* This extracts the contents from the DOM literally, inclusive of the tags. The content extracted also disappears from the DOM */ contents = rangeObject.extractContents(); var span = document.createElement("span"); span.className = "highlight"; span.appendChild(contents); /* Insert your new span element in the same position from where the selected text was extracted */ rangeObject.insertNode(span); } else if (document.selection && document.selection.type != "Control") { text = document.selection.createRange().text; } };
-11371468 0 Bug using UISplitViewController in a UITabController in iPad interface I am a new IOS developer working on my first app. I'm quite a way in to it, and have managed to get pretty much everything working how I want, but I'm chasing an odd bug.
Here's the basic app design (yes, I understand it may not confirm to Apple UI guidelines) as best I can describe it:
It's a universal app written in the latest X Code fully using storyboarding. I have a working iPhone and iPad interface, but it's in the iPad interface where my issue exists. The root controller is a UITabView. On one of the tabs, I have a split view controller which implements the typical master detail pattern. In portrait mode, the master table is hidden and content renders. A navigation bar button brings forth the master table view. You select an item and the master table view vanishes and the right side updates the content via a segue. So far so good. You rotate the device, everything keeps working. The split view master table stays on the left, and the content renders on the right. This all works great even within the tab controller.
Here are the two use cases that demonstrate the bug not happening and happening, in that order
1- Bug does not happen a) Launch app in Portrait. b) Select Nav button to bring up master table c) Select item from table (item renders, master table vanishes) d) Rotate device to lanscape (master/detail rotates properly) e) Pick a different view from tab controller f) Pick original view containing split view g) Everything is great
2- Bug happens in this use case a) Launch app in Portrait b) Select Nav button to bring up master table c) Select item from table (item renders, master table vanishes) d) Pick a different view from the tab controller e) Rotate device to landscape whilst in the other tab view f) Pick original view with the split controller from the tab bar g) View comes back, detail is rendered, master/view is completely missing.
So, it seems to be that if the master/detail rendered in landscape before the other tab view was selected, everything is fine. But if the master/detail view doesn't render in landscape at least once before you pick another view in the tab, it doesn't work right.
In my viewWillAppear method for the master/table controller, I check self.masterPopoverController.isPopoverVisible and sure enough it returns false.
I'm wondering if this is a bug, or maybe one of the reasons Apple doesn't recommend putting a split view in another controller?
-10608228 0Matt Galloway's answer on this thread explains the why:
Consider the following:
id anotherObject1 = [someObject performSelector:@selector(copy)]; id anotherObject2 = [someObject performSelector:@selector(giveMeAnotherNonRetainedObject)];
Now, how can ARC know that the first returns an object with a retain count of 1 but the second returns an object which is autoreleased?
It seems that it is generally safe to suppress the warning if you are ignoring the return value. I'm not sure what the best practice is if you really need to get a retained object from performSelector -- other than "don't do that".
-14214077 0 c# LINQ DataTable substractioni have two DataTables which has different columns but one column is same.
i want to get new DataTable which contains row from dt1 which are not exist in dt2.
how can i do it using LINQ?
that's is my current code, but it work only for Datatables with same columns:
private void Delete_HPM_Deleted_Points(int YellowCard_Request_ID) { DataTable dt_hpm_points_DB = DataAccessLayer.Get_YellowCard_Request_HPM_Points(YellowCard_Request_ID); //dt_hpm_points_DB.Columns.Remove("HPM_Tool_ID"); //dt_hpm_points_DB.Columns.Remove("HPM_Point_Message"); //dt_hpm_points_DB.Columns.Remove("HPM_Point_isDisabled"); //dt_hpm_points_DB.Columns.Remove("HPM_Point_Comments"); DataTable dt_hpm_points_Local = UserSession.Get_User_YC_HPM_Added_Points_DATATABLE(); //dt_hpm_points_Local.Columns.Remove("HPM_Tool_ID"); //dt_hpm_points_Local.Columns.Remove("HPM_Point_Message"); //var rowsInFirstNotInSecond = dt_hpm_points_DB.Rows.Where(r1 => !dt_hpm_points_Local.Rows.Any(r2 => r1.ID == r2.ID)); DataTable dt_points_to_remove = dt_hpm_points_DB.AsEnumerable().Except(dt_hpm_points_Local.AsEnumerable(), DataRowComparer.Default).CopyToDataTable(); foreach (DataRow dr in dt_points_to_remove.Rows) { DataAccessLayer.Delete_YellowCard_Request_HPM_Point(YellowCard_Request_ID, dr["HPM_Point_ID"].ToString()); } }
-31206619 0 How to check Availability of Region Monitoring status in objective c In my app, when it loads the current position of the user, it works correctly.
But when the user goes outside of the boundaries of a city (or any specific place), I want to do something.
For that, I am reading the reference of the Apple documentation Region Monitoring and iBeacon
But I do not understand lots of things. Like how to determine the availability of Region Monitoring? From where i can get UUID string..?
- (void)registerRegionWithCircularOverlay:(MKCircle*)overlay andIdentifier: (NSString*)identifier { // If the overlay's radius is too large, registration fails automatically, // so clamp the radius to the max value. CLLocationDistance radius = overlay.radius; if (radius > self.locManager.maximumRegionMonitoringDistance) { radius = self.locManager.maximumRegionMonitoringDistance; } // Create the geographic region to be monitored. CLCircularRegion *geoRegion = [[CLCircularRegion alloc] initWithCenter:overlay.coordinate radius:radius identifier:identifier]; [self.locManager startMonitoringForRegion:geoRegion]; }
-16204802 0 Portrait Orientation Slider (JQuery) I have tried Nivo Slider for this but I find it hard to convert it into a portrait orientation. Is there an easy way for this? I mean, I'm a newbie of this field and I have been working on this for a couple of days. Thanks! I don't have the code, I just want a portrait orientation and the images will actually resize depending on the sliders width and height. Thanks!
P.S I was following this tutorial but I can't make it work. LINK: http://net.tutsplus.com/tutorials/design-tutorials/code-your-own-juicy-tabbed-slider-using-the-nivo-slider/
-35523743 0The Erwin API can be used to programatically access the model.
you can write a program to step through the model, extract and format the information you want to export.
One of the model properties is the date the model was last updated. If your export program saves the date that it was last run, you could compare the 2.
-22274891 0After some intense googling I got my code working.
First thing I did was added an extra class to store the token.
class TokenResponseModel { [JsonProperty("access_token")] public string AccessToken { get; set; } [JsonProperty("token_type")] public string TokenType { get; set; } [JsonProperty("expires_in")] public int ExpiresIn { get; set; } [JsonProperty("userName")] public string Username { get; set; } [JsonProperty(".issued")] public string IssuedAt { get; set; } [JsonProperty(".expires")] public string ExpiresAt { get; set; } }
After that I changed my code to the following code.
static internal async Task<TokenResponseModel> GetBearerToken(string siteUrl, string Username, string Password) { HttpClient client = new HttpClient(); client.BaseAddress = new Uri(siteUrl); client.DefaultRequestHeaders.Accept.Clear(); HttpContent requestContent = new StringContent("grant_type=password&username=" + Username + "&password=" + Password, Encoding.UTF8, "application/x-www-form-urlencoded"); HttpResponseMessage responseMessage = await client.PostAsync("Token", requestContent); if (responseMessage.IsSuccessStatusCode) { string jsonMessage; using (Stream responseStream = await responseMessage.Content.ReadAsStreamAsync()) { jsonMessage = new StreamReader(responseStream).ReadToEnd(); } TokenResponseModel tokenResponse = (TokenResponseModel)JsonConvert.DeserializeObject(jsonMessage, typeof(TokenResponseModel)); return tokenResponse; } else { return null; } }
I can now get the bearer token from a WebAPI 2 site in my client so I can add it to future request. I hope it is helpful to someone else.
-28640500 0Problem solved.
It turned out that additional permission is needed for the report on the report server. After the DBA granted the account access to the report folder, the problem is solved.
-26396550 0You're almost there, push the whole array when its not yet set on the new container, if already set, then just add them:
$newArr = []; foreach($array as $value) { if(!isset($newArr[$value['NAME']])) { // if this name is not yet inside, push it $newArr[$value['NAME']] = $value; } else { // if already inside then add $newArr[$value['NAME']]['USED_LICENSES'] += $value['USED_LICENSES']; $newArr[$value['NAME']]['TOTAL_LICENSES'] += $value['TOTAL_LICENSES']; $newArr[$value['NAME']]['DENIED_LICENSES'] += $value['DENIED_LICENSES']; } } // $newArr = array_values($newArr); // optional array reindex
-17971600 0 Complex map by objects property in ruby I'm trying to create different kind of structure from the array I currently have in my code.
I've got an array of objects (active directory objects) so lets say i got a from db :
a = [o1,o2,o3,o4,o5]
My object has property source_id
and name
which are the relevant properties.
I want to create structure like this (I want hash) from the data I have in my array :
objects = Hash.new { |hash, key| hash[key] = [] }
And this would be one example of how to put the data inside new structure:
a.each do |ob| objects[ob.source_id] << { :new => '', :name => {:unformated => ob.name, :formatted => ob.format(:name)} } end
I'm trying to replicate the same structure and it's not working out in my case :
a.group_by(&:source_id).map do |k,v| { k=> { { :new => '', :name => {:unformated => v.name, :formatted => ob.format(:name)} } } } end.reduce(:merge)
This is the error I get :
! #<NoMethodError: undefined method `name' for #<Array:0xae542b4>>
-32247075 0 You can use String.Replace Method:-
filename = filename.Replace(" ","").Replace("(","").Replace(")","").Replace(".","");
You can wrap this inside an extension method like this:-
public static class StringExtention { public static string RemoveUnwantedCharacters(this string s) { StringBuilder sb = new StringBuilder(s); sb.Replace("(", ""); sb.Replace(")", ""); sb.Replace(" ", ""); sb.Replace(".", ""); return sb.ToString(); } }
You can use this as: filename = filename.RemoveUnwantedCharacters();
But, since there is a possiblity of whitespaces too and not just space, I guess Regex is the best answer here as answered by @JonSkeet :)
-38841495 0If you want to focus purely on front end development work there is little need to know a great deal about back end stuff. If you are proficient in angular, javascript, html and css then you are on course. I would suggest taking a couple of interviews and seeing what they ask you that you feel weak on, and taking it from there.
There comes a point when you have to just "go for it". The best learning is done in the dev projects.
-34494437 0 automatic switch textview size by displayPlease I have problem with size in textView
I have .xml code, where I use linear/horizontal/frame layout and I have in layout some object (textview) and have same text in textviews.
I need switch text size according to Phone display. but if I put 130dp is not good for small display.
little of my code
<LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent" android:baselineAligned="false"> <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="2"> <TextView android:layout_width="wrap_content" android:layout_height="fill_parent" android:textAppearance="?android:attr/textAppearanceLarge" android:text="88" android:id="@+id/hlc" android:textSize="130dp" android:textIsSelectable="false" android:gravity="end" android:textStyle="bold" /> <LinearLayout android:orientation="vertical" android:layout_width="0dp" android:layout_height="wrap_content" android:paddingTop="0dp" android:layout_weight="10"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:text="°" android:id="@+id/textView15" android:textSize="@android:dimen/notification_large_icon_width" android:textIsSelectable="false" android:textStyle="bold" android:layout_weight="9" android:textAlignment="viewStart" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:text="8" android:id="@+id/hld" android:textSize= "@android:dimen/notification_large_icon_width" android:textStyle="bold" android:textAlignment="viewStart" android:layout_weight="1" /> </LinearLayout> </LinearLayout>
if i use @android:dimen/thumbnail_width it's too big for my formated display
I need to fill in framelayput with text in textview.
I can't put image here :(
... and how are used values-small, values-large, etc ? example please. example declarate and example use in xml.
Thanks.
-33004857 0Try this out, it seems to not complain about it, but don't have the full setup to test it out.
void ShowTableInDataGrid(System.Data.Entity.Core.Metadata.Edm.EntityType myEntityType) { var tableName = myEntityType.GetType(); var result = _context.Database. SqlQuery<myEntityType.GetType()> ("SELECT * FROM dbo." + tableName).ToList(); DataGridMain.ItemsSource = result; }
-35755933 0 Importing *.pdf_tex file error I have made a graphic with inkscape. Now I'm trying to build it in Latex. I' m working with TEXMaker. Therefore I have exported my graphic as *.pdf_tex
and *.pdf
. In macros i have added the following
\usepackage{color} \usepackage{transparent} \graphicspath{{fileWithPictures/}}
my picture is build in like this:
\begin{figure} \centering \def\svgwidth{175pt} \input{fileWithPictures/pic.pdf_tex} %\includegraphics[width=2in]{fileWithPictures/pic.pdf_tex} \end{figure}
Here I'm getting the following error. "!Package pdftex.def Error: File'pic.pdf" not found. See the pdftex.def package.."
I have tryed also to work with includegraphics which not succed. Because there he it doesn't recognize pdf_tex
format.
Interesting is that the compiler says that there is not a file called "pic.pdf
" and not "pic.pdf_tex
". Althought both files are clearly in the file. To be sure i put the pic.svg
file in the file. Now i have no more ideas and would be happy to get some help
Thanks
-12691986 0The first question has already been answered so I won't answer it again.
2) it redirects to upload_file.php and displays a message. Is there a way to actually go back the main page and display text that it was successful?
It is normally better to show the success message on the redirected page but you can solve this two ways:
header("Location: old_page.php");
Also this is not the best way to get a file extension:
$extension = end(explode(".", $_FILES["file"]["name"]));
Try using pathinfo instead: http://php.net/manual/en/function.pathinfo.php
$extension = pathinfo( $_FILES["file"]["name"], PATHINFO_EXTENSION);
And your if
statement:
if ($extension!=".doc" || $extension!=".doc" && ($_FILES["file"]["size"] < 200000) && in_array($extension, $allowedExts)) {
Even though this is a tiny usage of in_array
I still would recommend taking that out and using a more practical method of searching arrays: http://php.net/manual/en/function.array-search.php
So your if
would become something like:
if (($_FILES["file"]["size"] < 200000) && array_search($extension, $allowedExts)!==false) {
-19889206 0 Found this while looking for same answer, it seems to be a windows + Doctrine issue
Doctrine Ticket with more detailed info
TLDR: Basically the proxy is trying to rename a file thats still being used, works in linux but not always on windows.
-6530736 0Yes. To move <div id="div1" />
inside <div id="div2" />
, you can do this:
$('#div1').appendTo($('#div2'));
Any of the appendTo
, insertAfter
, append
, etc. methods will "move" a tag to another location. You can find a list of available jQuery functions here.
Use primeface 4.0. Versions below this version do not support the placeholder attribute.
use name space xmlns:pt="http://java.sun.com/jsf/passthrough"
.
p:inputTextarea id="textAreaValue" pt:placeholder="your text"
don't insert a new line in inputTextArea
.
go sp_configure 'show advanced options',1 reconfigure with override go sp_configure 'Ad Hoc Distributed Queries',1 reconfigure with override go SELECT * into temptable FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 'Excel 8.0;Database=C:\Documents and Settings\abhisharma\Desktop\exl\ImportExcel2SQLServer\ImportExcel2SQLServer\example.xls;IMEX=1', 'SELECT * FROM [Sheet1$]') select * from temptable
-40611378 0 pagination for appended div I want to append content of div_2 in show_form div every time when i click on add more button.after appending appending div will slide by next and previous button by pagination.please help me out.
<html> <head> </head> <body> <div id="div_2" class="div_2"> this is div 2 <form class="this_form"> <input type="name"> <textarea placeholder="message"> <input type="button" value="buttons" /> </form> </div> <div id="show_form" class="show_form"> </div> <button class="btnn" type="button" id="btnn">add more</button> </body> </html>
here is my javascript code
<script> $(document).ready(function(){ $("body").on("click",".btns",function(){ $(".show_form").append($(".div_2").html()); $('.div_2').animate( { 'margin-left':'1000px' },function(){ $(".div_2").remove() $('#show_form').attr("id","div_2"); $('#div_2').addClass('div_2'); $('#div_2').removeClass('show_form'); $( "#div_2" ).after(function() { return "<div id='show_form' class='show_form'></div>" }); $('#show_form').addClass('show_form') }) $('.show_form').show("slow"); } ); }); </script>
-1685199 0 What would be the best way to send NSData through PHP into MySQL? Ok I believe this must be a pretty common scenario. I need to send a NSData variable over a HTTP request through a PHP page which then subsequently stores it in MySQL. This will be retrieved later by some other HTTP call which then downloads it into a NSData again. What is the best way to do this?
Should I convert the NSData into some sort of string representation (base64 etc)? Should I store the data in MySQL as VARCHAR or Blob? The data length will not exceed the MySQL/HTTP limit.
-17963088 0I'm surprised you are not using the TYPO3's documentation...
First hit with full description and samples: http://wiki.typo3.org/XCLASS
-16815615 0XCLASS'ing is a mechanism in TYPO3 CMS to extend or overwrite classes or methods of other extensions or of core code with own code...
You can also write getters for your different formats:
public function getGeoAsString() { // Create the string from your DB value. For example: return implode(',', json_decode($this->geom)); }
Then you can use the geoAsString
like a regular (read-only) attribute. You can also add a setter method, if you want to make it writeable.
The error is in your configuration. This line:
[remote "heroku"] url = git@heroku.com:yourhttp://still-lake-3136.herokuapp.com/.git
Is complete nonsense. I don't know how that line ended up there. You must have copy-pasted something from somewhere the wrong way. My guess is it should look like this:
[remote "heroku"] url = git@heroku.com:still-lake-3136.git
If that does not work you should really follow the instruction here to initiate a remote repository:
https://devcenter.heroku.com/articles/git
In that case you can delete the whole [remote "heroku"]
section (actually the 5 last lines) from your config
file before proceeding with those instructions.
One of those two (editing the line, or reinitializing the repository) should fix your problem.
-9828492 0try setting internet permission outside the application tag
-27528632 0Jayes is a Java library for Bayesian networks and the inference in such networks. At the moment, there is no learning component included. (We can, however, recommend the Apache Mahout library.)
-10278906 0Zoom is not included in the CSS specification, but it is supported in IE, Safari 4, Chrome (and you can get a somewhat similar effect in Firefox with -moz-transform: scale(x)
since 3.5). See here.
So, all browsers
zoom: 2; zoom: 200%;
will zoom your object in by 2, so it's like doubling the size. Which means if you have
a:hover { zoom: 2; }
On hover, the <a>
tag will zoom by 200%.
Like I say, in FireFox 3.5+ use -moz-transform: scale(x)
, it does much the same thing.
Edit: In response to the comment from thirtydot
, I will say that scale()
is not a complete replacement. It does not expand in line like zoom
does, rather it will expand out of the box and over content, not forcing other content out of the way. See this in action here. Furthermore, it seems that zoom
is not supported in Opera.
This post gives a useful insight into ways to work around incompatibilities with scale
and workarounds for it using jQuery.
I need to design a form for a account
resource. In that form, i need to collect some set of ids as an array in the params
hash in attribute called relationships
. So the final params[account]
hash from the POST request should be like
{:name => 'somename', :relationships => ["123", "23", "23445"]}
How shall I design the form_for fields. I tried this, but didn't work.
<%= form_for @account do |f| %> <%= f.text_field :name %> <% @eligible_parents.each do |p| %> <%= f.check_box "relationships", nil, :value => p.id %> <b><%= p.name %></b><br/> </span> <% end %> <%= f.submit "Submit" %> <% end %>
Number of elements in @eligible_parents
varies every time. relationships
is neither an association nor an attribute in account
model. I have to use virtual attributes but I need to fill in an array from a form. Please help. How can I do this?
Flex provide a JPEG encoder. You can use that to compress the bitmap images and send them to the server, where you can that stitch them together using ffmpeg.
-39344119 0record.x_sum_stored_taxes_exclude_withholding =\ sum(line.amount for line in record.x_sum_stored_taxes_exclude_withholding)
You should use `tax_line_ids ?
record.x_sum_stored_taxes_exclude_withholding =\ sum([line.amount for line in record.tax_line_ids])
And ofcourse you need only positive values:
record.x_sum_stored_taxes_exclude_withholding =\ sum([line.amount for line in record.tax_line_ids if line.amount >= 0.0])
-35324331 0 Okay, let's break it down. replace(/[\W_]/g, "")
means replace every non-word character and underscore with an empty string. So in the string $1.00, it would come out as 100 ($ and . are non-word characters).
Then .replace(",","")
removes commas.
And .replace(".","")
removes periods.
I have created a loop to call posts so I can display posts easily on my website, however... I'm using animate.css to add animations, and a problem I'm now facing is all of these elements have the same data-id so they scroll in at the same time...
I'm very new to PHP and so I don't know if there's a way that I can give each of the divs a different data-id so they scroll in one by one?
Here's my code thus far;
<div class="animatedParent animateOnce" data-appear-top-offset='-525' data-sequence='500' style="margin: 40px 0; text-align: center;"> <h2 class="animated bounceInUp" data-id='14' style="text-transform: uppercase;">Recent Events at Pontins!</h2> <div class="past-events"> <?php query_posts('cat=#&posts_per_page=4'); ?> <?php while (have_posts()) : the_post(); ?> <div class="one-fourth animated bounceInLeft" data-id='15'> <a href="<?php echo get_permalink(); ?>"> <?php the_post_thumbnail('large_wide'); ?> </a> <h4><a href="<?php echo get_permalink(); ?>"><?php the_title(); ?></a></h4> <?php the_excerpt(); ?> </div> <?php endwhile; ?> <?php wp_reset_query(); ?> </div> <div style="clear:both;"></div> </div>
http://www.stuartgreen.me.uk/pontins-events/wp-content/themes/genesis-sample/js/css3-animations.js here's a link to the JS (I'm using 'Jack McCourt - Animate It')
-30572447 0break; does NOT work for if statements, only loops, switch and such.
You can do this to avoid nesting:
if(mainCondition) { if(condition1) goto LabelContinue; bool condition2 = logic...; if(condition2) goto LabelContinue; //Code } LabelContinue: //Other code.
-4719132 0 You're looking for the FileVersionInfo
class:
FileVersionInfo.GetVersionInfo(typeof(string).Assembly.Location)
-35252136 0 You are attempting to present another viewController while first ViewController has yet not loaded.
Solution:
You'll want to use the FlashWindowEx function. Basically, get a handle to the window, create a FLASHWINFO structure with the handle and how you want the window to flash (continuously, until it's opened, etc), and pass it into FlashWindowEx.
edit: Here's an example of how to do it in C#.
-25844644 0 geom_segment combined with geom_pointI am plotting a geom_point in ggplot and I want to combine it with a segment from the x-asis to the point. How do I specify that the segment should go from the x-axis?
head(pValues_Both.m) value 1 5.502 2 0.823 3 0.374 4 3.886 5 0.724 6 0.706 ggplot(pValues_Both.m, aes(x=seq_along(value),y=value)) + geom_segment(aes(yend=value), xend=0, colour="grey50") + geom_point(size=3.5,colour="#2E64FE")
-9679009 0 Concatenate the .po files into a single .po file i have to concatenate following two .PO files
firstfile.po
msgid "Select game" msgstr "Choisissez le jeu" msgid "Without answers1" msgstr "Guide d'achat1"
secondfile.po
msgid "Select game" msgstr "Choose category" msgid "any one answer" msgstr "Guide d'achat
Here while i concating using msgcat
without using --use-first
the output po obtained is given below.
output.po
msgid "Select game" msgstr "Choisissez le jeu" msgid "Without answers1" msgstr "Guide d'achat1 msgid "any one answer" msgstr "Guide d'achat
Thev above output file doesnot contain all the msgstrs found for the repeated msgid.
expected output is
output.po
msgid "Select game" msgstr "Choisissez le jeu" msgid "Without answers1" msgstr "Guide d'achat1" msgid "Select game" msgstr "Choose category" msgid "any one answer" msgstr "Guide d'achat
Is there any way to repeat the same msgid
in the output PO file
I have a ASP.NET MVC 4 app.
I want to copy a text(from PDF) CTRL+C and paste it as parameter in a method from a controller.
My webgrid has column with an ActionLink
grid.Column(" ", " ", format: @<a href="@Url.Action("Clipboard", "People", new { cbdata = window.clipboardData.getData('Text') })">Clipboard</a>),
...
[HttpPost] public ActionResult Clipboard(string cbdata) // is string ok ? { //I'm doing something with my clipboard data .. return View(); }
This part is not working : window.clipboardData.getData('Text') Do I have to modify my MapRoute in Global.asax.cs ?
Q : How can I get the data from my clipboard in a method from my controller ?
-8284291 0Generally speaking there are two or three steps to federated sign out - locally you need to remove the forms auth cookie if one was used as well as the FIM cookie, this will sign out from the local application.
You then need to issue wasignoutcleanup10 request to the STS used, which would sign you out from the STS itself and, in theory, shoud issue a wasignoutcleanup1.0 request (or equivalent) to all the other IPs that were involved in the process (the STS should keep track of which IPs were contacted for each request)
I built such scenario once using Windows Identity Foundation which has the components needed, but it did require some development to keep track of the all the IPs and issue the calls.
I suspect that the ACS currently does not support this behaviour meaning that a user will have to close the browser to fully sign-out from all the applications.
-33931108 0You have a number of issues you need to overcome...
The first could be done in a number of ways, assuming we can change the data. You could make the first token meaningful (human
, pet
); you could use JSON or XML instead. But lets assume for the moment, you can't change the format.
The key difference between the two types of data is the number of tokens they contain, 7 for people, 5 for pets.
while (input.hasNext()) { String text = input.nextLine(); String[] parts = text.split(","); if (parts.length == 7) { // Parse owner } else if (parts.length == 5) { // Parse pet } // else invalid data
For the second problem you could use arrays, but you would need to know in advance the number of elements you will need, the number of people and for each person, the number of pets
Oddly enough, I just noticed that the last element is an int
and seems to represent the number of pets!!
Morely,Robert,123 Anywhere Street,15396,4,234.56,2 ------------^
But that doesn't help us for the owners.
For the owners, you could use a List
of some kind and when ever you create a new Human
, you would simply add them to the List
, for example...
List<Human> humans = new ArrayList<>(25); //... if (parts.length == 7) { // Parse the properties human = new Human(...); humans.add(human); } else if (parts.length == 5) {
Thirdly, for the pets, each Pet
should associated directly with the owner, for example:
Human human = null; while (input.hasNext()) { String text = input.nextLine(); String[] parts = text.split(","); if (parts.length == 7) { //... } else if (parts.length == 5) { if (human != null) { // Parse pet properties Pet pet = new Pet(name, type, age, date1, date2); human.add(pet); } else { throw new NullPointerException("Found pet without human"); } }
Okay, so all this does, is each time we create a Human
, we keep a reference to the "current" or "last" owner created. For each "pet" line we parse, we add it to the owner.
Now, the Human
class could use either a array or List
to manage the pets, either will work, as we know the expected number of pets. You would then provide getters in the Human
class to get a reference to the pets.
Because out-of-context code can be hard to read, this is an example of what you might be able to do...
Scanner input = new Scanner(new File("data.txt")); List<Human> humans = new ArrayList<>(25); Human human = null; while (input.hasNext()) { String text = input.nextLine(); String[] parts = text.split(","); if (parts.length == 7) { String firstName = parts[0]; String lastName = parts[1]; String address = parts[2]; int cid = Integer.parseInt(parts[3]); int vists = Integer.parseInt(parts[4]); double balance = Double.parseDouble(parts[5]); int other = Integer.parseInt(parts[6]); human = new Human(firstName, lastName, address, cid, vists, balance, other); humans.add(human); } else if (parts.length == 5) { if (human != null) { String name = parts[0]; String type = parts[1]; int age = Integer.parseInt(parts[2]); String date1 = parts[3]; String date2 = parts[4]; Pet pet = new Pet(name, type, age, date1, date2); human.add(pet); } else { throw new NullPointerException("Found pet without human"); } } }
-1422406 0 Read the bottom part of Wikipedia Ruby.
Windows
If you install the native Windows version of Ruby using the Ruby One-Click Installer, then the installer has setup Windows to automatically recognize your Ruby scripts as executables. Just type the name of the script to run it.
$ hello-world.rb Hello world
If this does not work, or if you installed Ruby in some other way, follow these steps.
1. Log in as an administrator.
2. Run the standard Windows "Command Prompt", cmd.
3. At the command prompt (i.e. shell prompt), run the following Windows commands. When you run ftype, change the command-line arguments to correctly point to where you installed the ruby.exe executable on your computer.
$ assoc .rb=RubyScript .rb=RubyScript $ ftype RubyScript="c:\ruby\bin\ruby.exe" "%1" %* RubyScript="c:\ruby\bin\ruby.exe" "%1" %*
For more help with these commands, run "help assoc" and "help ftype".
-28165140 0 Can I be able to use the latest features of latest Android API if I set the minimum SDK version as 2.3.3?Can I be able to use the latest features of latest Android API if I set the minimum SDK version as 2.3.3?
I am thinking that if I set the minimum SDK version as 2.3(API level as 9) then Can I use the features which are there in the recent API though my target API is Recent(21).
What should be a standard values for: “Minimum Required SDK” , “Target SDK” & “Compile with”
As I am starter to Android development.
-22968411 0 Updating data in databaseI have a problem trying to update this data but giving error messages all the time...
private void btnEnterReturn_Click(object sender, EventArgs e) { OleDbConnection connect = new OleDbConnection(); connect.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=MovieLibrary.accdb"; connect.Open(); addnew = "UPDATE tblLoan set MovieID='" + this.txtMovieID + "', DateIssued='" + this.txtDateIssued.Text + "', DateReturned='" + this.txtDateReturned.Text + "' WHERE MemberID='" + this.txtMemberID.Text + "';"; com = new OleDbCommand(addnew, connect); com.ExecuteNonQuery(); connect.Close(); MessageBox.Show("Successfully returned.."); //clear screen txtMemberID.Text = " "; txtMovieID.Text = " "; txtDateIssued.Text = " "; txtDateReturned.Text = " "; }
-26759750 0 Your update is a separate statement from the select
. If you want to do this in an update, try:
WITH CTE AS ( SELECT rownum = ROW_NUMBER() OVER (ORDER BY p.BusinessEntityID), p.FirstName FROM Person.Person p ) UPDATE p SET FirstName = prev.FirstName FROM CTE p JOIN CTE prev ON prev.rownum = CTE.rownum - 1 WHERE CTE.FirstName IS NULL;
The left join
isn't important here, because you are only changing rows where FirstName IS NULL
. The left join
would set the NULL
value to itself.
So... I'm trying to eliminate some memory leaks from my GTK+ 3 program. I though it would be a good idea to look back at some simple examples to see if there is some cleanup stuff I'm forgetting, but the hello_world program provided in the documentation has leaks too. (Valgrind output below).
Are these leaks acceptable? If so, is there some other application I should be using to debug GTK programs?
==13717== Memcheck, a memory error detector ==13717== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al. ==13717== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info ==13717== Command: ./a ==13717== Hello World ==13717== ==13717== HEAP SUMMARY: ==13717== in use at exit: 1,578,162 bytes in 11,614 blocks ==13717== total heap usage: 45,699 allocs, 34,085 frees, 6,461,970 bytes allocated ==13717== ==13717== LEAK SUMMARY: ==13717== definitely lost: 2,560 bytes in 5 blocks ==13717== indirectly lost: 6,656 bytes in 207 blocks ==13717== possibly lost: 363,228 bytes in 1,937 blocks ==13717== still reachable: 1,205,718 bytes in 9,465 blocks ==13717== suppressed: 0 bytes in 0 blocks ==13717== Rerun with --leak-check=full to see details of leaked memory ==13717== ==13717== For counts of detected and suppressed errors, rerun with: -v ==13717== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)
Code:
#include <gtk/gtk.h> /* This is a callback function. The data arguments are ignored * in this example. More on callbacks below. */ static void print_hello (GtkWidget *widget, gpointer data) { g_print ("Hello World\n"); } static gboolean on_delete_event (GtkWidget *widget, GdkEvent *event, gpointer data) { /* If you return FALSE in the "delete_event" signal handler, * GTK will emit the "destroy" signal. Returning TRUE means * you don't want the window to be destroyed. * * This is useful for popping up 'are you sure you want to quit?' * type dialogs. */ g_print ("delete event occurred\n"); return TRUE; } int main (int argc, char *argv[]) { /* GtkWidget is the storage type for widgets */ GtkWidget *window; GtkWidget *button; /* This is called in all GTK applications. Arguments are parsed * from the command line and are returned to the application. */ gtk_init (&argc, &argv); /* create a new window, and set its title */ window = gtk_window_new (GTK_WINDOW_TOPLEVEL); gtk_window_set_title (GTK_WINDOW (window), "Hello"); /* When the window emits the "delete-event" signal (which is emitted * by GTK+ in response to an event coming from the window manager, * usually as a result of clicking the "close" window control), we * ask it to call the on_delete_event() function as defined above. * * The data passed to the callback function is NULL and is ignored * in the callback function. */ g_signal_connect (window, "delete-event", G_CALLBACK (on_delete_event), NULL); /* Here we connect the "destroy" event to the gtk_main_quit() function. * * This signal is emitted when we call gtk_widget_destroy() on the window, * or if we return FALSE in the "delete_event" callback. */ g_signal_connect (window, "destroy", G_CALLBACK (gtk_main_quit), NULL); /* Sets the border width of the window. */ gtk_container_set_border_width (GTK_CONTAINER (window), 10); /* Creates a new button with the label "Hello World". */ button = gtk_button_new_with_label ("Hello World"); /* When the button receives the "clicked" signal, it will call the * function print_hello() passing it NULL as its argument. * * The print_hello() function is defined above. */ g_signal_connect (button, "clicked", G_CALLBACK (print_hello), NULL); /* The g_signal_connect_swapped() function will connect the "clicked" signal * of the button to the gtk_widget_destroy() function; instead of calling it * using the button as its argument, it will swap it with the user data * argument. This will cause the window to be destroyed by calling * gtk_widget_destroy() on the window. */ g_signal_connect_swapped (button, "clicked", G_CALLBACK (gtk_widget_destroy), window); /* This packs the button into the window. A GtkWindow inherits from GtkBin, * which is a special container that can only have one child */ gtk_container_add (GTK_CONTAINER (window), button); /* The final step is to display this newly created widget... */ gtk_widget_show (button); /* ... and the window */ gtk_widget_show (window); /* All GTK applications must have a gtk_main(). Control ends here * and waits for an event to occur (like a key press or a mouse event), * until gtk_main_quit() is called. */ gtk_main (); return 0; }
-9019088 0 CQRS/Event sourcing project structure I have my first CQRS project which uses event sourcing and I was wondering if this type of project should be structured in a different way in Visual studio compared to other projects that involve multiple tiers?
For example, in the pastt projects created had layers such as Remoting, App services, domain etc and it was clear each layer/assembly touched the one below it. These assemblies seemed to do a lot and using a tool like NDepend did say much about the structure of the project.
However, with a CQRS project would it be better just to have smaller assemblies that show their intent i.e. assembly for commands, another for events, another for event handlers etc.
Now with NDepend it would give me a better representation how the assemblies are used.
TIA
JD
-37306161 0Thats because of stopwords Set PositionIncrements to False and luceneMatchVersion to 4.3
Replace your StopFilterFactory with this.
<filter class="solr.StopFilterFactory" luceneMatchVersion="4.3" ignoreCase="true" words="stopwords.txt" enablePositionIncrements="false"/>
-37746464 0 _load_frames is a member function of the struct DataSet.
I would presume that given the leading underscore it is a private method.
struct DataSet { private: //function declaration std::vector<Frame> _load_frames(const std::string& basepath); };
I would recommend reading a book or taking some classes on c++ as this is a fairly fundamental concept.
http://www.tutorialspoint.com/cplusplus/cpp_class_member_functions.htm https://www.amazon.co.uk/Jumping-into-C-Alex-Allain-ebook/dp/B00F9311YC https://www.amazon.co.uk/C-Programming-Language-Bjarne-Stroustrup-ebook/dp/B00DUW4BMS
-26572291 0Afaik the field tables in classic delphi and FPC only work for published fields. Published fields must be class fields (value types like integer must go via properties). Newer Delphi's also allow RTTI for non published fields, but that works differently (different untis), and FPC doesn't support that yet.
I hacked together a small demonstration example since the help for typinfo seems to be light on examples. Note the tpersistent derivation.
{$mode delphi} uses typinfo,classes; type TAClass=class(Tpersistent) a: tstringlist; b: tlist; end; var ovmt: PVmt; FieldTable: PVMTFieldTable; PVMTFieldEntry; i: longint; begin ovmt := PVmt(TAClass); while ovmt <> nil do begin FieldTable := PVMTFieldTable(ovmt^.vFieldTable); if FieldTable <> nil then begin FieldInfo := @FieldTable^.Fields[0]; for i := 0 to FieldTable^.Count - 1 do begin writeln(fieldinfo^.name); FieldInfo := PvmtFieldEntry(PByte(@FieldInfo^.Name) + 1 + Length(FieldInfo^.Name)); end; end; { Try again with the parent class type } ovmt:=ovmt^.vParent; end;
end.
-38386746 0 C# - ComboBox control of ASP.NET AJAX control is not editable in ChromeWe dynamically create a web page with an editable dropdown list. But it can't be edited in Chrome, it did work in IE. Following are the dynamically creating code and result on page.
AjaxControlToolkit.ComboBox comboBox = GetComboBox(i); sControlID = comboBox.ID; comboBox.TabIndex = (short)(i + 100); if (ca.List != null) { string[] sList = ca.List; Array.Sort(sList); for (int j = 0; j < sList.Length; j++) comboBox.Items.Add(sList[j]); } ListItem li = comboBox.Items.FindByText(sVal); if (li != null) li.Selected = true; else { li = new ListItem(sVal); comboBox.Items.Add(li); li.Selected = true; } tc.Controls.Add(comboBox); }
I found following snippet at the bottom oft the page within script
tag,
Sys.Application.add_init(function() { $create(Sys.Extended.UI.ComboBox, {"autoCompleteMode":3,"autoPostBack":true,"buttonControl":$get("comboBox2_comboBox2_Button"),"comboTableControl":$get("comboBox2_comboBox2_Table"),"dropDownStyle":1,"hiddenFieldControl":$get("comboBox2_comboBox2_HiddenField"),"optionListControl":$get("comboBox2_comboBox2_OptionList"),"selectedIndex":4,"textBoxControl":$get("comboBox2_comboBox2_TextBox")}, null, null, $get("comboBox2")); });
As you can see, the textBoxControl
in the snippet is the text filed for this editable dropdown list. If I remove it("textBoxControl":$get("comboBox2_comboBox2_TextBox")
) from the snippet, it can be edited but the button behind is not working, it means the dropdown list doesn't work.
Any ideas what's going on here? Thanks in advance.
UPDATE:
I figured that it's the Ajax Control Toolkit, I think that the snippet I posted is the key for this issue. When the page loads, it changes and overrides the original element. I checked the document about this control and found that the dropDownStyle is for controlling the permission to allow user to edit or not. But as the document says, there are three values which are 'DropDownList', 'DropDown' and 'Simple'. But it didn't work when I changed this value.
-5084150 0I'm using it for research, so "semi-production". It's a wonderful framework, and the way things are architected certainly make sense once you fully grok it. But I've hit far too many problems to consider it production ready. I'm using jzmq, so some of this might be specific to that.
BUT, and this is a big but, I can't count how many man-hours it has saved me. This post has a good summary of just a few of the ways it makes life more pleasant.
-22249363 0Append this in your code. this might help.
$("object param[name=flashvars]").attr("value", $("object").attr("data"));
-6730429 0 Should environment variables that contain a executable-path with spaces also contain the necessary quotes? When defining an environment variable (on Windows for me, maybe there is a more general guideline)
set MY_TOOL=C:\DevTools\bin\mytool.exe
if the tool is located on a path with spaces
set MY_TOOL=C:\Program Files (x86)\Foobar\bin\mytool.exe
should the environment variable already contain the necessary spaces?
That is, should it read:
set MY_TOOL="C:\Program Files (x86)\Foobar\bin\mytool.exe"
instead of the above version without spaces?
Note: In light of Joeys answer, I really should narrow this question to the examples I gave. That is, environment variables that contain one single (executable / batch) tool to be invoked by a user or by another batch script.
Maybe the spaces should be escaped differently?
-25743069 0 asp.net Custom ErrorI am rly confused about this. I tried following all kind of tutorials but cant seem to get it working right I dont know what I am doing wrong sinse its the exact same as those vids I Have seen.
I tried this
web.config
<customErrors mode="On" defaultRedirect="Error.aspx"/>
changing the application_error under Global.aspx.cs
where it ends out with a respons redirect also tried server transfer but none of them leads me to my Error.aspx
does someone know a good simple tutorial on how to set one up? or someone who can tell me step by step what to do?
I tried following the first part of this guide sinse that is what I wanted.
protected void Application_Error(object sender, EventArgs e) { Exception ex = Server.GetLastError(); Server.ClearError(); Response.Redirect(@"~Error.aspx"); }
but it tells me it goes into an infinite loop.
I want to send the user to a page called Error.aspx where they can see a custom error screen.
-16404142 0If your level class has non primitive members they should also implement serializable.
-26535859 0 How to display quiz using Magnific-popup with ajaxI am attempting to implement the ability to download a quiz, and display it in a lightbox, with a single mouse click. I got all the ajax stuff working, and I think am using Magnific-popup correctly, but the "lightbox" is missing. Instead all I see is the text, left justified, on the dark background.
I reduced the jQuery code to be the minimum necessary to duplicate the issue:
$('.els-ajax-popup').magnificPopup({ type:'ajax', callbacks: { parseAjax: function (ajaxResponse) { ajaxResponse.data = "<div class='wrapper'><p>this is a test</p></div>"; } } });
And my html looks like this
<a class = "els-ajax-popup" href="http://sandbox.somewhere.net/wp-admin/admin-ajax.php?action=els_quiz_ajax&quiz_id=3" >Quiz</a>
Current behavior: After clicking the link, the screen turns dark and the words "Loading ..." appear, centered on the screen for a second and vanish. Then the html appears, directly on the dark background, left-justified and centered vertically. In addition the the missing white background, there is no way to exit. Only a screen refresh will return it to normal.
I carefully read all of the stack overflow questions tagged with "Magnific-popup". Not sure what else I can do at this point.
Magnific is working great for me in "inline" mode.
$('a.open-quiz-popup').magnificPopup({ type:'inline', midClick: true, // allow opening popup on middle mouse click. });
In this case, the HTML and jscript are already in the page. You can see how the inline version works here.
-38986788 0There are three main problems with your code:
Change __int__
to __init__
. Your instance isn't getting initialized, which is why you get the no attribute 'speed'
error.
Your subclass (the class that's inheriting, which in this case is Player
) should have an __init__
method that takes all the arguments you want associated with it. You can pass the ones used by the superclass (Persion
) to the superclass's __init__
. That means probably changing the __init__
method to:
class Player(Persion): def __init__(self, name, gender, speed): super(Player, self).__init__(name, gender) self.speed = speed self.posX = 0 self.posY = 0
Now, when creating the instances, you need only create an instance of the subclass. It will inherit the methods from the superclass:
hero = Player('Ben', 'm', 30)
With these changes, these lines:
print("you are now at ", hero.posX, "," , hero.posY) print("your speed is ", hero.speed) print("your gender is ", hero.gender) hero.talk()
Now produce this output:
you are now at 20 , 20 your speed is 30 your gender is m hi my name is Ben and I am a m.
Additional small notes:
Person
instead of Persion
.@abstractmethod
method should not be needed.I have a set of Java files in the same package, each having main methods. I now want the main methods of each of the classes to be invoked from another class step by step. One such class file is Splitter.java. Here is its code.
public static void main(String[] args) throws IOException { InputStream modelIn = new FileInputStream("C:\\Program Files\\Java\\jre7\\bin\\en-sent.bin"); FileInputStream fin = new FileInputStream("C:\\Users\\dell\\Desktop\\input.txt"); DataInputStream in = new DataInputStream(fin); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine = br.readLine(); System.out.println(strLine); try { SentenceModel model = new SentenceModel(modelIn); SentenceDetectorME sentenceDetector = new SentenceDetectorME(model); String sentences[] = sentenceDetector.sentDetect(strLine); System.out.println(sentences.length); for (int i = 0; i < sentences.length; i++) { System.out.println(sentences[i]); } } catch (IOException e) { e.printStackTrace(); } finally { if (modelIn != null) { try { modelIn.close(); } catch (IOException e) { } } fin.close(); } }
I now want this to be invoked in AllMethods.java
inside a main method. So how can I do this? There are several other class files having main methods with IOException
which have to be invoked in AllMethods.java
file.
Update -
I have main methods having IOException
as well as main methods not having IOEXception
that has to be invoked in AllMethods.java
.
Overview:
Our application extends a UIApplication and has a SMS Listener class that is registered on boot. When a message is received that fits our criteria we process the message and then we want to save it to a local SQLite database as well as upload it to a Web Server. It is important that this happens as soon as possible after the SMS is received, even if the UI Application is not open at that stage.
Problem:
When the SMSListener Instance is running in the background, with no UIApplication instance active, and wants to access the SQLite database or tries to create a HTTP Connection a “No Application Instance” exception is thrown.
Desired outcome:
We want to process, save and upload all the messages from the SMSListener background thread even if the UIApplication is not active. Currently the SMSListener background thread would store the messages in the RuntimeStore; when the UI Application is started it reads the messages from the RuntimeStore and saves it to the database. This is not an optimal solution though, because the synchronisation with the Web Server would also then only happen when the UI Application is next opened. It is important that it rather syncs when the message is received.
Application Pseudo Code:
Main Class, checks for startup and creates a SMSListener instance or gets the instance from the RuntimeStore.
public class OurAppUi extends UiApplication { public static void main(String[] args) { if (args != null && args.length > 0 && args[0].endsWith("gui")) { // Create a new instance of the application and make the currently // running thread the application's event dispatch thread. OurAppUi theApp = new OurAppUi(); theApp.enterEventDispatcher(); } else { // Entered through the alternate application entry point SmsListener.waitForSingleton(); } } }
The SMSListener Class listens for any incoming messages, makes use of the RuntimeStore Singleton Model. This is working as expected.
public class SmsListener implements javax.wireless.messaging.MessageListener { public static SmsListener waitForSingleton() { //Ensure this is a singleton instance. //Open RuntimeStore and obtain the reference of BackgroundListener RuntimeStore store = RuntimeStore.getRuntimeStore(); Object obj = store.get(ID_BACKGROUND_LISTENER); //If obj is null, there is no current reference to BackgroundListener //Start a new instance of BackgroundLIstener if one is not running if(obj == null) { store.put(ID_BACKGROUND_LISTENER, new SmsListener()); return (SmsListener)store.get(ID_BACKGROUND_LISTENER); } else { return(SmsListener)obj; } } public void notifyIncomingMessage(MessageConnection conn) { new Thread() { MessageConnection connection; Thread set (MessageConnection con) { this.connection = con; return (this); } public void run() { try { Message m = connection.receive(); String msg = null; if (m instanceof TextMessage) { TextMessage tm = (TextMessage)m; msg = tm.getPayloadText(); } // Process the SMS SMSObject sms = processSMS(msg); // Save to DataBase { Exception is Thrown Here } SQLManager.getInstance().save(sms); // Upload to Web Server { Exception is Thrown Here } WebServer.upload(sms); } catch(Exception error) { } } }.set(conn).start(); } }
When the SmsListener Instance wants to access the SQLite database or tries to create a HTTP Connection a “No Application Instance” exception is thrown.
public final class SQLManager { private SQLManager() { try { db = OpenOrCreateDatabase(); } catch (MalformedURIException e) { Debug.log(TAG, "Get connection: URI: " + e.getMessage()); } catch (ControlledAccessException e) { Debug.log(TAG, "Get connection: Controlled Access: " + e.getMessage()); } catch (DatabasePathException e) { Debug.log(TAG, "Get connection: Database Path: " + e.getMessage()); } catch (DatabaseIOException e) { Debug.log(TAG, "Get connection: Database IO: " + e.getMessage()); } catch (Exception e) { Debug.log(TAG, e); } } public static synchronized SQLManager getInstance() { if (instance == null) { instance = new SQLManager(); } return instance; } }
We’ve tried store the SQLite instances in the RuntimeStore, using the same Singleton Model as the SMSListener but received errors when the UI Application tried to access the stored DB Instance.
-29184067 0You can use Application.Caller to determine which button was clicked, then just name your buttons 1,2,3,4,5 ect.. with the name of the button being the row that it is on. Then set a variable = to Application.Caller to get the row number and then you can tell excel to copy whatever rows you want based on that
rownum = Application.Caller Range("A" & rownum + 5).Copy
This will say tot copy 5 rows down from whichever row was clicked assuming you name your buttons with just row numbers.
When you filter rows the entire rows get hidden, including any buttons that are on them.
-7865583 0 Core Location and Core Motion device headingI've noticed one problem with Coree Motion. When I'm using the
[_mMotionManager startDeviceMotionUpdatesUsingReferenceFrame: CMAttitudeReferenceFrameXTrueNorthZVertical toQueue: [[[NSOperationQueue alloc] init] autorelease] withHandler: ^(CMDeviceMotion* motion, NSError* error) { //my code here }];
to get device motion it gives me wrong device heading. I mean if I start processing motion updates holding device towards the north the heading is OK. But if I start not towards the north the bias is very big.
Is there any way to get correct values of heading?
-29501744 0 Why don't pointer to VLA function parameters deduce their size automatically and is there currently any good usage of them?As I understand it every VLA have an hidden variable of it's size which value can be 'acquired' by sizeof
operator. What I don't get here is pointer to VLA's used in function parameters - why isn't their size automatically deduced and stored in this hidden variable - why we should explicitly provide it. And in this case why should we even use it given that we have already the type 'pointer to array of unknown size'?
What I mean is this:
void func(size_t, int (*)[*]); //function accepting pointer to VLA void func_1(size_t, int (*)[]); //function accepting pointer to array of unknown bound void func(size_t sz, int (*parr)[sz]) //implementation of 'func' { printf("%lu", sizeof(*parr) / sizeof(int)); printf("%lu", sz); } void func_1(size_t sz, int(*parr)[]) //implementation of 'func_1' { //printf("%lu", sizeof(*parr) / sizeof(int)); //error: invalid application of 'sizeof' to an incomplete type 'int []' printf("%lu", sz); }
As I can see it the only benefit of using 'func' instead of 'func_1' is that 'sizeof' operator will return a copy of the initial value of 'sz'.
Example usages of the above functions:
int main() { size_t sz = 3; int arr[sz]; func(sizeof(arr) / sizeof(int), &arr); func_1(sizeof(arr) / sizeof(int), &arr); return 0; }
Why can't the size of pointer to VLA parameter be assigned implicitly? This would at least make some good use of the syntax:
void func(int (*parr)[*]) // size copied from function argument { printf("%lu", sizeof(*parr) / sizeof(int)); printf("%lu", sz); }
And then calling the function like this:
int main() { size_t sz = 3; int arr[sz]; func(&arr); return 0; }
Will cause array hidden size variable with value of '3' to be passed as hidden argument to 'func' creating code similar to instancing previous 'func' with current syntax and using 'sizeof' operator to passed array.
If you're curios enough compiling the proposed syntax into whatever Clang compiler - you'll get an easter egg (;.
-31798092 01: What is the best LAyoutout thing for this approach? I thought of a Listview where I add Textviews dynamically
That sounds good to me, you can go with either ListView
or RecyclerView
. You are basically not adding TextView
s dynamically, you create an adapter that will do handle creating and recycling of views for you.
2: How can I achieve this in Code?
Create a DialogFragment
, it's the best candidate for such dialogs with logic. Its lifecycle is handled via FragmentManager
, so you won't have issues on screen rotations and so on. It allows you setting whatever layout you need just like any other Fragment
. It will be placed in the center for you, so you don't have to handle that manually. Just set the size of the dialog you want and it will look perfect.
It should loose the Focus when the User taps outside of the view so my surfaceView gets the Focusagain and set the LAyout to Gone.
I don't really get this one. When user touches outside, do you need to lose the focus but the dialog should not be closed? If yes, then this is already answered here:
Allow outside touch for DialogFragment
If the dialog should be closed, you don't have to implement anything, it works like that by default.
-26263200 0I was having the exactly the same issue. I was first storing the image data on a local HDD before using the function imagecreatefromjpeg() to post-process the image further.
At certain times the locally stored image was corrupted during the store process and when called by imagecreatefromjpeg($imagePath); the PHP Warning: imagecreatefromjpeg(): gd-jpeg, libjpeg: recoverable error: Premature end of JPEG file occured. showed up.
So to resolve the PHP warnings and to make up for the corrupted image I used a clearly defined solution in the PHP manual (http://php.net/manual/en/function.imagecreatefromjpeg.php) see the function LoadJpeg($imgname)
To prevent the further failures I have focused on the reason why the data supplied to imagecreatefromjpeg() function was not integrious in the first place. In my case it was the network flood issue which was causing some images to arrive corrupted.
Long story short, you may want to check what exactly is being supplied into imagecreatefromjpeg() function before trying to extend the base library etc..
-36740114 0I think he's resolving your empty bind as url(undefined)
.. So He'll try to resolve the URL http://<domain>/path/to/your/page/undefined
.
Do you initialize scope.image_url
on page load?
To prevent this, I suggest to bind the entire style attribute, and not only the url()
... If there is no "empty" url()
, I think it won't load a random request... Or if the background is only static, use CSS classes instead of style
attribute...
i have created an object as follows
var lassie = { name: 'Lassie', breed: 'Collie', speak: function () { return 'Woof! Woof!'; } };
I create another object by using Object.create method of javascript as
var obj = Object.create(lassie);
now when i console obj it gives me a blank object. But when i console obj.speak() it gives me 'Woof! Woof!' .
can someone please explain why?
-15359464 0 Concurrent interrupt handling in LinuxWhat are the things that can be done or needs to be done in the top-half of an ISR handler. I see that the interrupts are disabled first, but when this is done don't we miss the interrupts (on the same IRQ line) while handling the current interrupt?
Or is any one there who keeps track of the missing interrupts, so that they can be handled after interrupts are enabled at the end of the ISR?
-24301363 0In fact, there are two commands to use :
hdfs namenode
hdfs datanode
You probably have the self-signed key still in your keystore - so the server doesn't know which one to choose: The self-signed or the CA-issued.
Remove the self signed (excess) one.
-31157713 0 how to create row in angular js?I am trying to make a row which is displayed in image .Actually my circle is not on right side and my “P” is not getting background color.Here is my code http://plnkr.co/edit/qIz2rFgW8n3J92evCRTd?p=preview
can we give row height in percentage ? actually I need my row should look like as shown in image
![<html> <head> <meta charset="utf-8"> <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width"> <title>Ionic Swipe Down</title> <link href="//code.ionicframework.com/nightly/css/ionic.css" rel="stylesheet"> <script src="//code.ionicframework.com/nightly/js/ionic.bundle.js"></script> <script src="http://code.ionicframework.com/contrib/ionic-contrib-swipecards/ionic.swipecards.js?v=5"></script> </head> <style> .brd { border: 1px solid red; } </style> <body ng-app=""> <div class="list card"> <div class="item item-avatar"> <div style="border: 1px solid red;float: left;background: gray;">P </div> <h2>16000389</h2> <p>RutherFord & Alfanso Company Lmt</p> <div style="border: 1px solid black;float: left;background: green;border-radius: 100%;width: 50px;height: 50px">650</div> </div> </div> </body> </html>
-30856194 0 How can I use Guice to inject fields into Jersey @BeanParam parameters? This a bit of a weird setup. We've got a web service built on Dropwizard and using Guice for dependency injection. What I want to accomplish is injection of a Guice configured database access object (DAO) into a Jersey REST endpoint @BeanParam
.
The code (which I drew upon this answer, this question and the Jersey HK2 examples looks like this:
Authorization annotation interface, Authenticaiton.java
@Retention(RetentionPolicy.RUNTIME) @Target({ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD}) public @interface Authentication { }
Resolver with nested binder: AuthenticationResolver.java
@Singleton public class AuthenticatorResolver implements InjectionResolver<Authentication> { protected Authenticator injectableAuthenticator; @Override public Object resolve(Injectee injectee, ServiceHandle<?> root) { return injectableAuthenticator; } @Override public boolean isConstructorParameterIndicator() { return true; } @Override public boolean isMethodParameterIndicator() { return true; } public final class Binder extends AbstractBinder { public Binder(Authenticator authenticator) { injectableAuthenticator = authenticator; } @Override protected void configure() { // @P13NAuthentication bind(AuthenticatorResolver.class).to(new TypeLiteral<InjectionResolver<P13NAuthentication>>() {}).in(Singleton.class); } } }
All examples I've found of implementing a Binder
for an InjectionResolver
show the Binder
as a separate class or as a static
inner class. I've changed it to a non-static nested class to attempt to simply provide an instance to return via the Binder to the Resolver.
The Dropwizard Application class (which is a little deviant from a normal Jersey application because it's essentially a extension wrapper): Service.java
AuthenticatorResolver resolver = new AuthenticatorResolver(); AuthenticatorResolver.Binder binder = resolver.new Binder(injector.getInstance(Authenticator.class)); environment.jersey().getResourceConfig().register(binder);
At this point, the injector
is an instantiated com.google.inject.Injector
object with the needed instance of the Authenticator
on it. I can see it get added to the instance of the Binder
.
The class used as the @BeanParam
looks like this:
public class UserIdentifierContainer implements Serializable { @Authentication Authenticator authenticator; // Bunches of other parameter fields, parsing and validation // Trying to add some magic to verify some fields against the database
And I try to add it to an endpoint like so:
@PUT @Path("/like/{postId}") public Response putCategoryLike( @BeanParam UserIdentifierContainer userIdentifierContainer, @PathParam("postId") @ApiParam(required=true, value=CATEGORY_ID_DESC) Integer postId, ) throws Exception {
Inside of this method I would like the bean to have already validated all the parameters' format and checked the user against the database. However, inside the UserIdentifierContainer
object, the Authenticator
is null. No error is found trying to resolve an instance of it.
I think what's happening is the way the Binder instance gets treated in the application Register()
method doesn't preserve the actual instance, or a new AuthenticationResolver has to be constructed somewhere along the way that doesn't get the Authenticator
instance needed to return. In other words, my nested class dirty hack didn't work.
Is there some other way to get an instantiated object into a resolver for a dead-simple resolve implementation?
If not, it seems like I need to make the ServiceHandle
object that gets passed into the AuthenticationResolver
.resolve()
method somehow aware of of Authenticator
instance that's been configured by Guice. How can I do this?
Or is the best solution to somehow convert the Juice injector to play nicely with the HK2 Service Location paradigm?
-26718510 0Found out a way to get around this.
Pretty much have the codes as below:
// POST: api/XXXX [ResponseType(typeof(MyFileDTO))] public IHttpActionResult PostMyFile(MyFile myFile) { if (!ModelState.IsValid) { return BadRequest(ModelState); } db.MyFile.Add(myFile); db.SaveChanges(); // Get the highest myFile value. long maxMyFileId = db.MyFile.Max(p => p.MyFileId) var dto = new MyFileDTO() { FileId = maxMyFileId }; return Ok(Dto); }
Not sure if this is the proper way, but for now, it seems to resolve my issue of being able to obtain the column value.
Would appreciate any other answer if available.
-29064310 0TOP is the equivalent of LIMIT in sql server: http://www.w3schools.com/sql/sql_top.asp
As has been pointed out below, TOP is not the equivalent realy. In fact you need to use OFFSET and FETCH to exactly match the LIMIT behaviour: https://msdn.microsoft.com/en-us/library/ms188385.aspx
-9828028 0 Ruby Cucumber says path can't find route when Rake Routes show it is thereI have Ruby on Rails with Cucumber. The db has been migrated for the test environment and I can see it using sqliteman. The problem is that while rake routes shows the routes I want, cucumber returns an error saysing the routes don't exist.
Routes are:
movies GET /movies(.:format) {:action=>"index", :controller=>"movies"} POST /movies(.:format) {:action=>"create", :controller=>"movies"} new_movie GET /movies/new(.:format) {:action=>"new", :controller=>"movies"} edit_movie GET /movies/:id/edit(.:format) {:action=>"edit", :controller=>"movies"} movie GET /movies/:id(.:format) {:action=>"show", :controller=>"movies"} PUT /movies/:id(.:format) {:action=>"update", :controller=>"movies"} DELETE /movies/:id(.:format) {:action=>"destroy", :controller=>"movies"}
Then, in the same prompt box, I run "bundle exec cucumber" and get this error in two different scenarios in the same feature file:
No route matches {:action=>"show", :controller=>"movies"} (ActionController::RoutingError) No route matches {:action=>"edit", :controller=>"movies"} (ActionController::RoutingError)
The features/support/paths.rb file fails on the two lines where *movie_path* and *edit_movie_path* are called
when /^the details page for (.*)/ mov= Movie.find_by_title($1) movie_path(mov) when /^the edit page for (.*)/ mov= Movie.find_by_title($1) edit_movie_path(mov)
Was I supposed to rake routes into the test environment somehow? I'm not sure what I'm missing as it "looks" like all the pieces are there.
-22201349 0$result2[$value] = array( $options_key => $_POST[$options_key][$value] ); // problem !
Change to:
if( !isset($result2[$value])) $result2[$value] = array(); $result2[$value][$options_key] = $_POST[$options_key][$value];
-26388189 0 May be late still wanted to add to this..
exactly had the same problem. Just increment open files using ulimit -n to say 10000 and connect clients from multiple process solved the issue. I split 2500 connections to every process and could create 10k connections.
Hope this helps.
-11608693 0create your custom ImageView, define regions (rects or coordinates) and listen for onTouch events and iterate trough your list when touch event occurs and react if user has touched a defined region
-8433046 0 Mongodb query with fields in the same documentsI have next json.
{ "a1": {"a": "b"}, "a2": {"a": "c"} }
I want request all documents where a1 not equal a2 in the same document.
How I can do it?
-298826 0You can set the document.domain but if I remember correctly a few browsers (Opera) will not even allow this. I am afraid your answer is to create some sort of proxy on the subdomain that you can talk through
-8234695 0 "Leaking this" from a Design StandpointWarning: Leaking "this" in constructor
I keep running into this, and I have a nagging feeling that it's because my design is wrong or not optimal.
I understand that this warning is bringing to my attention the fact that I am allowing access to an object that is potentially not fully initialized.
Let's say that I need a Frame that HAS and requires a List (Frame(List list)). In List, I might want to do something such as add(). In order to make sure Frame knows as little about List as possible (only that it has one), I would want to access the containing Frame from the List (List HAS a Frame?). This seems a little silly, but I have 2+ implementations of List that will use Frame in different ways..
To ensure that my code is used properly, I would require a Frame in the constructor of List. I would also require a List in the constructor of Frame, as it MUST have one:
public abstract class Frame { private final List list; public Frame(List list) { this.list = list; list.setFrame(this); } } public abstract class List { private Frame frame; protected final void setFrame(Frame frame) { this.frame = frame; } }
So, is this bad design, or should I really create some intermediate scaffolding that does this, or even leave the scaffolding to the user?
Thanks!
-35458449 0Here's a small example with 2x2 bars which will be growing and changing color randomly, one at a time when update_bars()
is called:
import matplotlib.pyplot as plt import mpl_toolkits.mplot3d.axes3d as p3 import matplotlib.animation as animation import random def update_bars(num, bars): i = random.randint(0, 3) dz[i] += 0.1 bars[i] = ax.bar3d(xpos[i], ypos[i], zpos[i], dx[i], dy[i], dz[i], color=random.choice(['r', 'g', 'b'])) return bars fig = plt.figure() ax = p3.Axes3D(fig) xpos = [1, 1, 3, 3] ypos = [1, 3, 1, 3] zpos = [0, 0, 0, 0] dx = [1, 1, 1, 1] dy = [1, 1, 1, 1] dz = [3, 2, 6, 5] # add bars bars = [] for i in range(4): bars.append(ax.bar3d(xpos[i], ypos[i], zpos[i], dx[i], dy[i], dz[i], color=random.choice(['r', 'g', 'b']))) ax.set_title('3D bars') line_ani = animation.FuncAnimation(fig, update_bars, 20, fargs=[bars], interval=100, blit=False) plt.show()
Output (not animated here):
-29366504 0using a little set time out magic though i found the solution :
$('#myTab').on('click' , 'li a' , function(){ $this = $(this); var str_href = $this.attr('href'); str_image = str_href + ' ' + 'img'; str_contentdiv = str_href + ' ' + '.add-animation'; setTimeout(function(){ $(str_image).addClass('animated bounceInLeft'); $(str_contentdiv).addClass('animated bounceInRight'); setTimeout( function(){ $(str_image).removeClass('animated bounceInLeft'); $(str_contentdiv).removeClass('animated bounceInRight'); }, 2000); }, 100); });
note : to the col-md-5 that i add the animated bounceInRight class i also add the class add-animation
as a hook , could have used a css selector , but never mind .
Drawback of this method : if the user turns out to be click maniac , the animations will not show .. because well thats the way setTimeout works :D
have a nice day guys . YOLO .
any suggestions ? are very very welcome.
-9738700 0 Why is it that _localtime32 and _gmtime32 return the same time value for a non-GMT time zone?My time zone is set to CDT
in the control panel Date/Time applet.
The following code places exactly the same date and time into pCurGmtTime
and pCurTime
:
int main(int argc, char *argv[]) { __time32_t t=_time32(NULL); tm *pCurGmtTime=_gmtime32(&t); tm *pCurTime=_localtime32(&t); // The values in the *pCurGmtTime structure are equal to the values in *pCurTime return 0; }
I don't have the TZ
environment variable set, but my time zone is properly configured for the system via the Control Panel Date and Time applet. This behavior seems to go against the MSDN documentation for these functions, which says that TZ
overrides the control panel settings, but if it is absent the control panel settings will be used.
Thanks
-10954019 0 Multiple dropdowns on mvc viewHow can I create multiple dropdowns in my view with values coming from my database? I can get one dropdown, but how do I add another one?
public class MyModel { public Category Category { get; set; } public IEnumerable<SelectListItem> List { get; set; } } public ActionResult Page() { var query = model.MyModel.Select(c => new SelectListItem { Value = c.ModelDescription, Text = c.ModelDescription }); var model = new MyModel { List = query.AsEnumerable() }; return View(model); }
-33278957 0 If you implement one of these two CASES provided below you will definitely get viewWillAppear
and be sure you wrote it correct with it's super
-(void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; // Your code goes here }
CASE 1 - Using Navigation Controller
If you want to Pop from one ViewController to another you need to have all of them in the same navigation stack. It means every time you want to open new View Controller you need to do something like this:
[self.navigationController pushViewController:nextVC animated:YES];
instead of doing this
[self presentViewController:nextVC animated:YES completion:nil];
And after that if you already have all VCs in that same Navigation Controller, you can use this code to go one step back (e.g. from B to A, from C to B)
[self.navigationController popViewControllerAnimated:YES];
And you can use this code to jump to the beginning (e.g. from C to A)
[self.navigationController popToRootViewControllerAnimated:YES];
CASE 2 - Usual Cycle (Looks like what you need)
This is en easy case but you need to be more careful with your code. You can just get parent of the parent to Leave current View Controller
[[[self presentingViewController] presentingViewController] dismissViewControllerAnimated:NO completion:nil];
Note: You can't use navigation controller functions with modal presentation functions. Push is with Pop, Present is with Dismiss
UPDATE 1
Modal segues is creating a nested connection(one line of a tree). If you close child(current) VC parent VC appears normally. If you want to jump to the parent of the parent just dismiss the parent and it will dismiss all it's child VCs. I don't know why popViewControllerAnimated works fine from B to A but you are not allowed to do like that. Just use dismiss if if you are using modal segues. Never use Pop. Pop is for Push. Do this and everything should work fine.
For going back from B to A change your code to:
[self dismissViewControllerAnimated:YES completion:nil];
For going back from C to A use this code:
[[self parentViewController] dismissViewControllerAnimated:YES completion:nil];
OR
[[self presentingViewController] dismissViewControllerAnimated:YES completion:nil];
UPDATE 2
I discovered that for STORYBOARD segues we NEED to use this code to go back
[[[self presentingViewController] presentingViewController] dismissViewControllerAnimated:NO completion:nil];
This code totally fine jumps from C to A and viewWillAppear
is being called BUT viewWillAppear
is being called both in A and B
You have 3 tracks to choose (Actually you have more, like using delegates and notifications but this is too bad)
I think the question pretty explains what I want to achieve. I've got this code:
<input type="date" data-role="datebox" data-options='{"mode": "datebox","noButton": true,"useDialogForceTrue": true, "useDialogForceFalse": false}' name="mydate" id="mydate" />
And I want to set some default date when user opens up the datebox window in the input data-options so it won't take another line of code.
Thanks.
-13002020 0fixed by adding
require 'rexml/document'
-18877618 1 why should I use django forms I am starting a new project again in django and so far i have never used django forms. Now i am wondering why i should use it and what it would save me. I still feel, by using django forms, i am not free in terms of html styling with frontend frameworks like bootstrap.
why should I use django forms?
can you guys please guide me a bit?
-21436301 0You can edit /etc/issue
file as root and append to it the message you want to be displayed without the user needing to login
Related article:
-36948052 0Don't use $rootScope, for application configuration is recommended use a specific module with the configuration info and register each configuration block as `constant'.
In your case the server side configuration made a bit more complex. See Asynchronously Bootstrapping AngularJS Applications with Server-Side Data
(function() { var appConfig=angular.module("app.config"); var initInjector = angular.injector(["ng"]); var $http = initInjector.get("$http"); $http.get('config/config.json').success(function(configResponse) { appConfig.constant("config", configResponse); }); $http.get('preferences/preferences.json').success(function(prefsResponse { appConfig.constant("preferences", preferencesResponse); }); })());
At your app module include the app.config
and then you can inject the config,preferences or foo
to your angular controllers, services,...
angular.module("app",["app.config"])
-39812345 0 Try this:
$('[data-popup-complete]').on('click', function(e) { var targeted_popup_class = jQuery(this).attr('data-popup-complete'); $('[data-popup="' + targeted_popup_class + '"]').fadeOut(350); $('[data-popup="' + targeted_popup_class + '"]').css('display', 'block'); e.preventDefault();
});
-839417 0Classic closure problem. When you get the callback, the closure actually refers already to the HTTP object.
You can do the following as someone suggests:
var that = this; this.req.onreadystatechange = function() { this.handleReceive.apply(that, []); };
OR just do the following:
var that = this; this.req.onreadystatechange = function() { that.handleReceive(); };
-14957636 0 Share Picture on twitter with shareKit. A shorten URL is visible instead of actual attached image in tweet I am using shareKit to share something on twitter. I successfully send tweet (only) text by using
SHKItem *item = [SHKItem text:@"sample tweet"]; [SHKTwitter shareItem:item];
I try to attach UIImage with tweet using
SHKItem *item = [SHKItem image:[UIImage imageNamed:@"testImage.png"] title:@"posting test image"]; [SHKTwitter shareItem:item];
Although it posts successfully on twitter but instead of actual image shown within tweet it attaches a shorten URL. i.e. posting test image http://img.ly/sMx0
Please tell what i am doing wrong. Is there any other way to attach image within tweet. I want to give iOS compatibility 4.0 to 6.1
-15607240 0I have never used treegrid, from the sample provided by Oleg it seems to be that in grid data there is an item isLeaf
. I think you have to check for rd.isLeaf
See the demo here the data used there is (first row)
{id: "1", name: "Cash", num: "100", debit: "400.00", credit: "250.00", balance: "150.00", enbl: "1", level: "0", parent: "null", isLeaf: false, expanded: true, loaded: true, icon: "ui-icon-carat-1-e,ui-icon-carat-1-s"},
-31768854 0 Listview overlaps with ToolBar I am using android design support library.
ListView
first row overlaps with Toolbar
widget.
In my MainActivity
i added coordination layout and in first TAB fragment added ListView
layout.
But first row of the ListView
cut because if Toolbar
tabs.
How to fix this problem?
Main.xml
<?xml version="1.0" encoding="utf-8"?> <android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent"> <RelativeLayout android:id="@+id/coordi" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.design.widget.CoordinatorLayout android:id="@+id/coordinatorLayout" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.design.widget.AppBarLayout android:id="@+id/appBarLayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:layout_scrollFlags="scroll|enterAlways" app:popupTheme="@style/ThemeOverlay.AppCompat.Light" /> <android.support.design.widget.TabLayout android:id="@+id/tabLayout" android:layout_width="match_parent" android:layout_height="wrap_content" app:tabIndicatorColor="#FFEB3B" app:tabIndicatorHeight="6dp" app:tabSelectedTextColor="@android:color/white" app:tabTextColor="@android:color/white" /> </android.support.design.widget.AppBarLayout> <android.support.v4.view.ViewPager android:id="@+id/viewPager" android:layout_width="match_parent" android:layout_height="match_parent" /> <android.support.design.widget.FloatingActionButton android:id="@+id/fab" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="end|bottom" android:layout_margin="16dp" android:src="@drawable/plus" /> </android.support.design.widget.CoordinatorLayout> </RelativeLayout> <android.support.design.widget.NavigationView android:id="@+id/navigation_view" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="start" app:headerLayout="@layout/layout_drawer_header" /> </android.support.v4.widget.DrawerLayout> list_view.xml: ------------- <?xml version="1.0" encoding="utf-8"?> <ListView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/listView1" android:layout_width="match_parent" android:layout_height="match_parent"></ListView>
-24904790 0 use the following code ====================== function allowDrop(ev) { ev.preventDefault(); } function drag(ev) { ev.dataTransfer.setData("Text", ev.target.id); } function drop(ev) { ev.preventDefault(); var data = ev.dataTransfer.getData("Text"); ev.target.appendChild(document.getElementById(data)); } <input type="text" ondrop="drop(event)" ondragover="allowDrop(event)"> and use this url for viewing : http://jsfiddle.net/zLYGF/25/
-39460798 0 while(last != 0){ for(int i = 0; i<last;i++){ elements[i]= elements[i-1]; } last--; }
Remove the while loop. If you're trying to make sure it's not dequeueing an empty queue have an if condition check to ensure that the size is > 0.
public int Dequeue(){ if (getSize() == 0) { // throw an error or something } int output = elements[first]; System.out.print(output + " "); for(int i = 0; i<last;i++){ elements[i]= elements[i-1]; } last--; return output ; }
Additionally you need to print the output in your tester class, and I assume you want to dequeue while the queue is NOT empty:
while (!q.empty()){ System.out.println(q.Dequeue());
-26724073 0 Please change the looping condition in your for 1st loop !
i <= len
to
i < len
It goes from 0 ... n-1
Also you need to change initialization condition in 2nd loop
int j = len
to
int j = len-1
It goes from n-1 ... 0
-11576284 0If you want any kind of accuracy, the simple algorithm is terribly bad. For an accurace range reduction algorithm, see e.g. Ng et al., ARGUMENT REDUCTION FOR HUGE ARGUMENTS: Good to the Last Bit .
-14443092 0 How to specify template argument for a function in a child?So I try:
class data_ppp { public: template <class T> virtual boost::shared_ptr<T> getData() { return boost::shared_ptr<T>(new T()); } }; class data_child : public data_ppp { public: template<> getData<std::vector<int>>(); };
but cant get desired effect - I want to have in class data_child getData function that would only return boost::shared_ptr<std::vector<int>>
. How to do such thing?
Try to modify :
CASE WHEN ID = 'test' THEN ROLENAME END
into :
CASE WHEN ID = 'test' THEN ROLENAME END AS ROLENAME
The reason is because when you use CASE clause, it will have no name, unless you define it
-30393907 0If the POST
structure always looks like this you can try:
// match the whole user-post-post path MATCH (u:USER {name: "Lamoni"})-[:CREATED]-(p_direct:POST)-[:RESHARED]-(p_shared:Post) WITH u, p_direct, p_shared OPTIONAL MATCH (p_direct)<-[:LIKES]-(u2:USER) OPTIONAL MATCH (p_shared)<-[:LIKES]-(u3:USER) RETURN u.name, p_direct.xyz, collect(u2.name), p_shared.xyz, collect(u3.name)
If you just want all USERS
that like a POST
by a given USER
(independent of the type of POST
, created or shared) you can also collect all POST
:
MATCH (u:USER {name: "Lamoni"})-[:CREATED|RESHARED*1..2]-(p:Post) WITH u, p OPTIONAL MATCH (p)<-[:LIKES]-(u2:USER) WITH u.name, p, u2 ORDER BY u2.created_at RETURN u.name, p, collect(u2.name)
-18141263 0 In most cases you should not think of a class as a set of attributes that you operate on externally, but as an entity that provides certain services to the application. Most attributes of the class will end up being private and not having get or set methods.
There are exceptions though: for example in some settings you will find classes that only hold values and have little or no logic themselves. The usual rule for these kinds of classes is to make fields private and provide get and set methods because once you make something public and some other class depends on it you can't change it. For example you may want to ensure that the value of a particular field is never null or do some other validation; if you used a set method you could add the check there, but if the field is public there's nothing you can do. Another example: you may want to change the field type to do some optimization, but if the field is public, there's nothing you can do.
All rules are meant to be broken though. If you know that you will never need get and set methods there's not much point in adding them. Some people may complain about "lack of encapsulation" but if every attribute of the class can be read and written from the outside anyway where's the encapsulation?
-1842524 0What Vinegar says - just install it and play ;). But if it's really all that new to you it might be a good idea to install linux in VirtualBox or vmware. This way you won't break anything on your computer if you'll make mistake during installation and you can always save 'clean' installed system as snapshot and easily come back to that 'clean' state by reverting to snapshot.
For reading... i just recommend man pages. You can access them from console or online, for example here. When you aren't sure how to use some command - read its man page.
-29857919 0 BULK COLLECT INSERT and after checking duplicatesIn plsql i want to insert around 1 million rows from a staging table to actual table and currently I am using cursor for loop for that. But I understand that there is a way to speed up this using bulk insert for all command but i am struggling in the section of eliminating duplicates. Can u please help to convert the below code to use bulk collect
DECLARE CURSOR c1 is select ps_item_code, item_code, cons_date, shop_code, dept_code, class_code, sub_class_code, supl_code, plu_price, sal_qty, sal_val_in_lc, disc_val_in_lc, tax_val_in_lc, odept, oclass, osubclass from sales_stage; BEGIN FOR i in c1 loop BEGIN my_cnt := 0; select count(1) into my_cnt from hps_ps_terr_sales_1415 where item_code=i.item_code and cons_date=i.cons_date and shop_code=i.shop_code and sal_qty=i.sal_qty and supl_code=i.supl_code; IF my_cnt = 0 THEN BEGIN insert into sales_actual ( ps_item_code, item_code, cons_date, shop_code, dept_code, class_code, sub_class_code, supl_code, plu_price, sal_qty, sal_val_in_lc, disc_val_in_lc, tax_val_in_lc, odept, oclass, osubclass, dept, class, subclass ) values ( i.terr_code, i.ps_item_code, i.item_code, i.cons_date, i.shop_code, i.dept_code, i.class_code, i.sub_class_code, i.supl_code, i.plu_price, i.sal_qty, i.sal_val_in_lc, i.disc_val_in_lc, i.tax_val_in_lc, i.odept, i.oclass, i.osubclass, i.dept_code, i.class_code, i.sub_class_code ); END; END IF; END; END LOOP; COMMIT; END;
The server should return always the index.html page. When you start the router in your Backbone than, the router handle the navigation and call the function you defined for the actual route.
-35830284 1 Python - How can I store data from a text file without storing all data simultaneously in the primary memory?I have a text file which has an unknown number of lines. Each line is either "0" or "1".
I need to analyse the text file, for example I need to find how many 1s and 0s are in the file.
So would it be incorrect to do this?
fo = open("data.txt", "r") numbers = fo.read().splitlines() fo.close()
-29833409 0 So I did the following:
def to_representation(self, instance): rep = super(MySerializer, self).to_representation(instance) duration = rep.pop('duration', '') return { # the rest 'duration of cycle': duration, }
-5618002 0 Just don't bother with user clip planes. They are emulated in weird ways across drivers. Why do you really need them? If it is to optimize something you are going to get a small gain on some HW and pay a horrible price on other. If you need it for some algorithm do it yourself using a texkill and it will be reliable everywhere. Probably not the answer you wanted, but in general, just don't use it and rethink your approach.
-22898198 0The PowerShell remote session were probably not closed correctly. Either make sure they are closed correctly (Remove-PSSession or Exit-PSSession) or try to remove them with something like below (PowerShell v3 and higher, see here).
Get-PSSession -ComputerName MyServerName | Remove-PSSession
-13854211 0 $("#myButton").click( function() { var class = $(this).attr("class"); });
Note that this can potentially contain multiple classes though.
If you need to check if a specific class exists in the CSS class list:
$("#myButton").click( function() { var isHighlighted = $(this).hasClass("highlight"); });
There's also addClass() and removeClass(). Generally there should be very little reason to ever retrieve the full class attribute as a string - it's much easier to manipulate or compare the attribute by using the jQuery methods instead.
-36700020 0Time complexity for that algorithm is O(NlogN)
.
The for
loop is executed N
times (from 0
to N
).
The while
loop is executed logN
times since your are dividing the number to half each time.
Since your are executing the while
inside the for
, your are executing a logN
operation N
times, from there it is the O(NlogN)
.
All remaining operations (assign, multiplication, division, sum) you can assume that takes O(1)
As everything is working locally, the problem is located in the device linking your laptop to the internet : your internet box.
By default, when it receives request from outside, your box will reject them, because this is a security risk (it could allow anyone to access your private network server, and if there is a security breach in a member, this could be a real problem). Moreover, your box has most of the times more than on device connected, so how can it know which device the request it gets is for?
Luckily, there is a way to tell your box "Hey! If you receive a request on this port, forward it to my laptop!". It is called port forwarding. This is quite difficult to explain as every ISP has a different implementation of this. But to set this, you have to connect to your box's administration interface and look for the section related to port forwarding.
Once you're there, you will have to set the port (if you run an HTTP application, it is 80 for example), a protocol (use both in doubt), and finally the destination IP. This is the IP of your computer on the local network. You can get it using ipconfig
on Windows.
Once you have set your forward rule, you should be able to acces your app from the internet using either a Dynamic DNS service, or your Internet address, which you can get from websites such as http://www.whatismyip.org
-9946747 0You can use the MAPISendMail api from MAPI. I used this in the past in some projects.
You can pass the function the MAPI_DIALOG flag to tell it to open a dialog for the user.
See for example: http://sundararajana.blogspot.de/2007/09/mapisendmail-in-c-application.html http://www.codeproject.com/Articles/2048/Simple-MAPI-NET
An alternative might be the Office Interop APIs, but I think they will be more complicated to work with. Also MAPI should work with other email clients thatn outlook as well (in theory at least).
Hope that helps!
-26378991 0 I create an UIImage view in interface builder, how to change its frame (position&size) in code?I have made the following changes in code for the image view, but it doesn't take effect at all. I think the key things is I created the image view in IB instead of in code.
userInfoBackground.frame = CGRectMake(0, 0, 200, 100); userInfoBackground.contentMode = UIViewContentModeScaleToFill;
What shall I do next? Thanks.
-20479370 0 Passing reference in c?I was just wondering if someone could answer this review question I have for an upcoming exam. Unfortunately I do not have an answer key to double check and I wanted to be sure my answer was correct. Here is the question:
Which of the following correctly passes the reference to the variable int max
to the function f
?
a) f(max); b) f(*max); c) f(&max); d) f(ref_max); e) None of the above
My best guess would be c. Unless I'm completely wrong, I'm sure a, d, e are not right and it's not asking me to dereference anything like choice b. I'm sorry if I broke any posting rules with this website and I know its probably an easy question for most of you.
-21517999 0 How can I create a function out my php select?How can I create a function out of my php select? Here is the code:
<? $sql = "SELECT value FROM configuration WHERE name = 'website_name'"; $result = mysql_query($sql); $row = mysql_fetch_assoc($result); ?> <?=$row['value'];?>
Basically I want to turn it into a function and call it as a variable so something like this. Here is the code:
<? function ItsaFunction() { //code goes here } ?>
I want to output the code as a variable. Here is the code:
<?=$ItsaFunction?>
How can I convert my select to a function and call it as a variable?
-23001804 0You don't specify the platform you're on...
If stdio.h
is not found, it usually mean you don't have the necessary header files on your system (usually in /usr/include/
).
Your compiler might be working fine, but it looks like the C-Library headers are not installed.
Depending on your platform, you'll have to install them.
It's a bit weird that you have a working compiler without C library headers.
You may want to reinstall your compiler, or search for a package which contains the headers for the C library.
If you're on OS X, (re)install Xcode as well as the command line tools.
If you're on Linux, use your package manager to install the development package for C (e.g. libc6-dev
on Debian).
See Why aren't variables locally scoped by default? in the Lua uFAQ.
-31282535 0You could do this using underscore, since you essentially have a list of elements once you've got c
.
var sortedC = _.sortBy(c, function (elem) { return elem.propertyToSort; });
you can use awk as well
$ echo 'Some - String- 12345-' | awk -F" *- *" '{$1=$1}1' OFS="-" Some-String-12345-
if its just "- " in your example
$ s="Some- String- 12345-" $ echo ${s//- /-} Some-String-12345-
-23604092 0 Take yout listview in one outer layout and fix the height of that layout like :
<LinearLayout android:layout_height="100dp"> <ListView android:layout_height="fill_parent"> </ListView> </LinearLayout>
-38657640 0 How to setup endless UIRouter state hierarchy? In my angularjs app, there is a concept of 'project'. Each project can contain 0 or more folders, and each of those folders can contain 0 or more subfolders. Each of the subfolders, in turn, can contain 0 or more sub-subfolders and so on. There is no actual limit on the amount of folder levels in the hierarchy.
I want to map each of the folder levels to a UIRouter state level.
E.g.,
URL State name http://localhost:8079/projects/1122024 -> _.projects.view http://localhost:8079/projects/1122024/folders/123890 -> _.projects.view.folder http://localhost:8079/projects/1122024/folders/123890/547938 -> _.projects.view.folder.folder http://localhost:8079/projects/1122024/folders/123890/547938/124890 -> _.projects.view.folder.folder.folder
etc.
Is it possible to declare such an endless hierarchy in UIRouter? If yes, then how? The only idea I have now is to use string.split, like following code - but I really don't feel like it's the correct way to do it. Any ideas?
.state('_.projects.view', { url: '/{projectId:int}' }) .state('_.projects.view.folders', { url: '/folders/{folderIds}', resolve: { folderIdTree: function($stateParams) { $stateParams.folderIds.split('/'); } } }
-37512178 0 Your problem has nothing to do with SFML, you are just reading your file incorrectly.
C++ uses wide strings (std::wstring
) to represent UNICODE. This is not UTF-8. To read a std::wstring
from an UTF-8 encoded file, please read Read Unicode UTF-8 file into wstring and use the second answer.
In case the order changes over time, that would be the one that tells you to use this function:
#include <sstream> #include <fstream> #include <codecvt> std::wstring readFile(const char* filename) { std::wifstream wif(filename); wif.imbue(std::locale(std::locale::empty(), new std::codecvt_utf8<wchar_t>)); std::wstringstream wss; wss << wif.rdbuf(); return wss.str(); }
Once you have obtained a valid std::wstring
from your file, you should be able to use it with SFML without problems.
I am trying to deserialize some JSON into a list using JSON.NET; however, there is a number in the way:
Here is the JSON:
"payment_info": { "fb_id": "", "order_items": { "0": { "product_id": "4534", "type": "product", "shipping_cost_per_item": "1.00", "quantity": "3", "price_each": "10.00", "price_total": "30.00" } },
Here is my class:
public class OrderItem { public string product_id { get; set; } public string type { get; set; } public string shipping_cost_per_item { get; set; } public string quantity { get; set; } public string price_each { get; set; } public string price_total { get; set; } } public class OrderItems { public List<OrderItem> Items { get; set; } }
How do I tell the converter to ignore the 0? There will be a 1,2,3 for each order item.
-33221042 0 How to responsive, vertically align image with CSSI am trying to responsively & vertically center an image on a page. I found several solutions online, but none are working for me. The image is stuck in the upper left hand corner. Any leads would be awesome. I'm banging my head :)
here is an image of the desired finished page
html { font-family: sans-serif; /* 1 */ -ms-text-size-adjust: 100%; /* 2 */ -webkit-text-size-adjust: 100%; /* 2 */ background: url("http://mccanney.net/mbhb/images/bg-giraffe.jpg") no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; } img.product1:empty { top: 50%; left: 50%; -webkit-transform: translate(-50%, -50%); -moz-transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); -o-transform: translate(-50%, -50%); transform: translate(-50%, -50%); }
<div> <img src="http://mccanney.net/mbhb/images/product-lg-hippo.jpg" class="product1" /> </div>
I guess the problem (besides the async peculiarities) with var transactions = {};
is that you are just creating a plain javascript object, which has no Ember support whatsoever, by Ember support I mean that you can bind to etc.
Try to declare you transaction variable like this:
var transaction = Ember.ArrayProxy.create({content: []});
And then inside your success function where you iterate over the results (code not testet):
... var obj = Ember.Object.create({id:null, vendor:null, date:null, spent:null}); obj.setProperties({ id: $(this).attr('id'), vendor: $(this).find('vendor').text(), date: $(this).find('date').text(), spent: $(this).find('spent').text() }); transaction.pushObject(obj); ...
Hope it helps
-15855010 0Well, conversion from seconds to microseconds shouldn't be too difficult;
echo time() * 1000;
If you need the time stamp to be acurate in milliseconds, look at microtime()
however, this function does not return an integer so you'll have to do some conversions
Don't know how to convert that to a readable time in Android
-33067596 0 Need guidance on Introduction to Spring JMS Active MQI am following "I coding blog" which is very good for someone like me who wants to get into Spring, JMS and ActiveMQ.
When I run TestJMSListener as a java application, I am getting following error:
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'connectionFactory' defined in class path resource [com/jms/helloworld/config/JMSConfig.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'brokerurl' of bean class [org.apache.activemq.ActiveMQConnectionFactory]: Bean property 'brokerurl' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
I do not know how to fix it, below is my JMSConfig.xml file:
your xml file here.
-29539222 0 Do you know why mysql fails creating this table? maybe my question is silly... but i couln't found the problem, when i do:
CREATE TABLE prefixes ( id INT(11) NOT NULL AUTO_INCREMENT, PRIMARY KEY(id), INDEX id (id)) ENGINE = InnoDB AUTO_INCREMENT = 1 DEFAULT CHARACTER SET = utf8;
Mysql says:
ERROR 1005 (HY000): Can't create table 'sms.prefixes' (errno: 150)
i though that an old foreign key or something is pointing/using this table, but i did an export (complete) and searched in the export for the key "prefixes" and i found nothing, so no foreign key problem or something, if i create the same table BUT naming it "prefixes2" or some else IT WORKS!!! Please if someone have any clue maybe it can be helpful.
Thanks!
-14986263 0Your event:
package { import flash.events.Event; public class ProgramEvent extends Event { public static const FINISH:String = "Finished" ; public function ProgramEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=false) { super(type, bubbles, cancelable); } public override function clone():Event { return new ProgramEvent(type, bubbles, cancelable); } public override function toString():String { return formatToString("ProgramEvent", "type", "bubbles", "cancelable", "eventPhase"); } } }
RunMain:
package { import flash.display.Sprite; import flash.events.Event; public class RunMain extends Sprite { public function RunMain():void { addEventListener(Event.ENTER_FRAME, loop); } private function loop(event:Event){ removeEventListener(Event.ENTER_FRAME, loop); dispatchEvent(new ProgramEvent(ProgramEvent.FINISH)); } } }
And Main:
public function Main() { startProgram() ; init(); otherMethods(); } public function onProgramFinish(event:ProgramEvent) { runMain.removeEventListener(ProgramEvent.FINISH, onProgramFinish) ; removeChild(runMain); runMain = null; startProgram() ; } public function startProgram(){ runMain = new RunMain() ; runMain.addEventListener(ProgramEvent.FINISH, onProgramFinish); addChild(runMain); }
-34390270 0 You need to refresh the collection after removing element. Try to change your code like below and see if it works:
Code:
var newList = invo; foreach (IGrouping<string, InvoiceCount> invoice in invo) { for (var line = 1; line < invoice.Count(); line++) { if (YOUR CONDITION HERE) { newList.Remove(invoice ); invo= newList; } } }
Note: How to modify a collection during iteration
-3611545 0Clicking the ShowAllFiles button at the top of Solution Explorer should do it.
-37987115 0 how can make it load URL in side the dynamic tab using jshow it possible to add or make it load URL link content in to dynamic tabs like this http://somup.com/cD1biN4SL
Im trying to modify this http://www.jankoatwarpspeed.com/wp-content/uploads/examples/dynamic_tabs/#
-33772466 0 TypeError: Attempted to assign to readonly property. ring.js: Line 333I have two Mac systems with different Safari versions. I'm facing this problem in Safari version 9.0.1, while it works fine in version 8.0.
THIS support blog mentions a similar issue. While I don't find this error in other browsers like Chrome or Firefox in both the Macs, but the Safari versions seems to create problem.
I came across a unaccepted solution HERE, that suggests to remove "use strict"
and that solves my problem (I have removed it from Line 28 of ring.js). But, I'm not sure about what side effects this may have. While I read the advantages of Why Strict Mode? HERE, I wonder why a modern browser(Safari 9.0.1) doesn't support it.
Can anyone throw some light to this?
-2934044 0My guess is that if you simply change your url configuration to reference "project.app.urls" instead of "app.urls", your problem will be fixed.
It seems that you've listed "project.app" in INSTALLED_APPS in your project's settings.py file, but you've referenced "app.urls" in your urls.py. You need to standardize and either always reference "app", and change your PythonPath to include the project directory, or always reference "project.app".
-21027184 0Create a class for all your mysql functions.
Something like this: Mysql.php file
<?php class Mysql { //class variables protected $_connection, $_result, $_numRows; function __construct($server, $dbuser, $dbpass, $dbselect) { $this->_connection = mysql_connect($server, $dbuser, $dbpass); mysql_select_db($dbselect, $this->_connection); mysql_set_charset('utf8',$this->_connection); } /* * @desc Close MySQL connection */ public function dbclose() { mysql_close($this->_connection); } /* * @desc Write custom queries * * @param string $sql sql query */ public function query($sql) { $this->_result = mysql_query($sql, $this->_connection); $this->_numRows = mysql_num_rows($this->_result); } /* * @desc get result af query * * @returns string $result */ public function getresult() { return $this->_result; } /* * @desc get connection af query * * @returns string $sql sql query */ public function getconnection() { return $this->_connection; } /* * @desc Count rows * @returns int $_numRows */ public function numRows() { return $this->_numRows; } /* * @desc Count rows and fetch assoc array * @return string $rows array */ public function rows() { $rows =array(); for ($x=0; $x < $this->numRows(); $x++) { $rows[] = mysql_fetch_assoc($this->_result); } return $rows; } public function retrieveInfo($companyPassword) { $result=$this->query("SELECT * FROM company WHERE password='$companyPassword'"); if ($this->numRows() == 0) { //if there is no result echo "Nothing to retrieve"; } else { //sort your data here or make the SELECT statement more specific, for now we return everything. return $result; } } ?>
Now use the class to retrieve your data in your original file:
<?php include 'Mysql.php'; $mysql = new Mysql('localhost', 'root', '', 'careers'); $result = $mysql->retrieveInfo($companypassword); //display the results print_r($results); ?>
You can now add functions to the Mysql.php class and use them the same way or directly use the
$mysql->query("Your MYSQL QUERY HERE");
function to do your calls.
You can also use the other methods I already put in Mysql.php for you.
-18160294 0This control might help you achieve the effect you're seeking:
https://www.cocoacontrols.com/controls/mpnotificationview
-21590218 1 Writing to txt in pythonI'm writing lines of numbers to a text file from another text file. The numbers that print while this is running look good, but when I open the output file nothing has been written to it. Can't figure out why.
min1=open(output1,"w") oh_reader = open(filename, 'r') countmin = 0 while countmin <=300000: for line in oh_reader: #min1 if countmin <=60000: hrvalue= int(line) ibihr = line print(line) print(countmin) min1.write(ibihr) min1.write("\n") countmin = countmin + hrvalue min1.close()
-13387075 0 Outlook footer + HTML + CSS - how to do it so it would work? I have a big problem with creating a HTML footer for my dad's firm. They are using OE and Outlook 10. I've working on the code for very long, but still I have some problems. Can I use external font? How should I make it working? How about positioning it with width: X% ?
I would like it to look like this:
But it doesn't...
Here's the code:
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>www.k#$#$#$#$#$#$#$.com</title> <style> @font-face { font-family: times_Sans_Serif; src: url('http://a#$#$#$#$#$#$#$.pl/tem/TIMESS_.ttf'); } p, a, span { font-family: times_Sans_Serif; } a { text-decoration:none; } .header { width:100%; height:5px; display:block; background-color:#6d5759; } .section li{ float: left; display: inline; list-style-type: none; margin:0% 3%; padding:0; position:relative; } .section p{ display:block; text-align: left; color:#6d5759; } .section a{ color: #6d5759; } #logo { text-decoration:none; text-align: right; } .footer { clear:both; font-size:11px; width:100%; height:auto; display:block; background-color:#6d5759; color:#FFF; text-align:center; padding: 5px; } .footer a{ color:#FFF; } </style> </head> <body> <div class="main"> <div class="header"></div> <ul class="section"> <li id="osoba"> <p> <a href="http://k#$#$#$#$#$#$#$.com/o-nas" target="_blank">Marcjusz K#$#$#$#$#$#$#$</a><br> +48 500 000 000<br> marcjusz@k#$#$#$#$#$#$#$.com </p> </li> <li id="logo"> <a href="http://k#$#$#$#$#$#$#$.com/" target="_blank"><img src="http://#$#$#$#$#$#$#$.pl/tem/image001.png"></a> </li> </ul> <div class="footer"> <span> K#$#$#$#$#$#$#$ Ubezpieczenia Sp.J. | 31-475 Kraków ul. STREET1 | 32-700 Bochnia ul. STREET2 | 32-800 Brzesko ul. STREET 3 | <a href="http://k#$#$#$#$#$#$#$.com/" target="_blank">www.kr#$#$#$#$#$#$#$.com</a></span> </div> </div> </body> </html>
Can you help me with that? I would be very helpful!
-18064779 0The first option, <meta charset='utf-8'>
, is preferred, primarily because it's shortest.
Note that the charset declaration should be the first child of the <head>
, before any user-controlled content. (in particular, before the <title>
)
Don't Use unnecessary div and css. check this as reference http://css-tricks.com/snippets/css/sticky-footer/
-33923985 0 parameter is not of type 'Blob'I have written the code below to display the text from a local file using the file API but when I click the button, nothing happens and I get the following error when I inspect the element in the browser, what am I dong wrong?
Uncaught TypeError: Failed to execute 'readAsText' on 'FileReader': parameter 1 is not of type 'Blob'.
<!DOCTYPE html> <html> <body> <p>This example uses the addEventListener() method to attach a click event to a button.</p> <button id="myBtn">Try it</button> <pre id="file"></pre> <script> document.getElementById("myBtn").addEventListener("click", function(){ var file = "test.txt" var reader = new FileReader(); document.getElementById('file').innerText = reader.result; reader.readAsText(file); }); </script> </body> </html>
I'm going to separate over 1000 virus signatures and the virus names. I have them all in a text file, and would like to do this with python.
Here is the format:
virus=signature
I need to be able to take 'virus' and write it to one file, then take 'signature' and write it to another.
This is what I've tied so far:
h = open("FILEWITHSIGS") j = h.read() k = h.split('=')
And that is basically where I got stuck. No matter what I tried, it printed (or writed) both to the same place.
-36022707 0 Disabling Datagrid Sort for excel export VB.netBeen stuck on this issue for a while now finally narrowed it down to the fact that AllowSorting
is True
. When I try to run the excel export With sorting, excel opens up into a blank document without any gridlines. Turned it off and the data appears as expected. I thought that if i turned off the sorting in the excel export button click event, then turn it back on afterwards, this would fix the issue, however this has not seemed to be the case.
I have also tried shifting where I turn off page sorting just to make sure I didn't place it in the wrong spot but still does not seem to change the result of the blank page.
Below is the coding I am using. I did read some talk about using a BindingSource
but that also did not seem to work for me.
Am I missing a step or doing something wrong?
Dim tw As New StringWriter() Dim hw As New HtmlTextWriter(tw) Dim frm As HtmlForm = New HtmlForm() Response.ContentType = "application/vnd.ms-excel" Response.AddHeader("content-disposition", "attachment;filename=" & "Facility Detail Report" & ".xls") Response.Charset = "" EnableViewState = False dgCustomers.AllowPaging = False dgCustomers.AllowSorting = False 'Dim BindingSource As New BindingSource 'BindingSource.DataSource = dgCustomers.DataSource() 'dgCustomers.DataSource = BindingSource.DataSource dgCustomers.DataBind() Controls.Add(frm) frm.Controls.Add(dgCustomers) frm.RenderControl(hw) Response.Write(tw.ToString()) Response.End() dgCustomers.AllowPaging = True dgCustomers.AllowSorting = True dgCustomers.DataBind()
-13433122 0 You can draw the image onto a new image adjusting its transparency as follows
public Raster transform(Image img, float alpha) { BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB); bi.getGraphics().drawImage(img, 0, 0, null); RasterOp rop = new RescaleOp(new float[] { 1.0f, 1.0f, 1.0f, alpha }, new float[] { 0.0f, 0.0f, 0.0f, 0.0f }, null); Raster result = rop.filter(bi.getData(), null); return result; }
-29338382 0 I tried remove all the *.err but still getting the same error. I got one of the error in error log.
[ERROR] InnoDB: Attempted to open a previously opened tablespace. Previous tablespace erp/brand uses space ID : 7 at filepath: ./erp/brand.ibd. Cannot open tablespace webdb1/system_user which uses space ID: 7 at filepath: ./webdb1/system_ user.ibd
so I delete all the ib* files and it works.
rm -f *.err ib*
-26341982 0 Connecting hover rules for two separate anchors? The fiddle below displays an image link and a text link for each corresponding page. Each image when hovered over shows the coloured version by using css. The text links simply have a border on the bottom when hovered.
I need to make the image coloured when the corresponding text link is hovered, and also the text link to have its border shown when the corresponding image is hovered? How can I link these functions together?
see this fiddle http://jsfiddle.net/rabelais/sLq28jb4/
#chorus { background: url('../images/work-icons/icon-chorus to size BW.jpg'); height: 85px; left: 30px; position: fixed; top: 78px; width: 113px; display: block; } #chorus:hover { background: url('../images/work-icons/chorus-icon to size.jpg'); border-bottom: none; } #chorus-text-link { left: 180px; position: fixed; top: 111px; }
-36688175 0 Better to cache $('html, 'body') before scrolling and use event delegation.
var $htmlBody = $('html, body'); $htmlBody.on('click', '.services-nav li a', function() { var target = $(this).attr('href') var offsetTop = $(target).offset().top || 0; $htmlBody.animate({scrollTop: offsetTop}, 1500); return false; });
-9642891 0 AFAIK, you have no good way of getting at the home button, and so you cannot use it as an anchor for a PopupMenu
. Consider instead using NAVIGATION_MODE_LIST
with the ActionBar
, which puts a Spinner
to the right of the home button and caption, where you supply the SpinnerAdapter
.
Marquee and Blink are not standard, and are no longer supported in newer browsers. Sorry.
-13177767 0I think even with --ignore-unmatch
you still need the --
disambiguator. Like:
git rm --cached --ignore-unmatch -- Rakefile ^^-this two dashes here
-33291245 0 RxJava delay for each item of list emitted I'm struggling to implement something I assumed would be fairly simple in Rx.
I have a list of items, and I want to have each item emitted with a delay.
It seems the Rx delay() operator just shifts the emission of all items by the specified delay, not each individual item.
Here's some testing code. It groups items in a list. Each group should then have a delay applied before being emitted.
Observable.range(1, 5) .groupBy(n -> n % 5) .flatMap(g -> g.toList()) .delay(50, TimeUnit.MILLISECONDS) .doOnNext(item -> { System.out.println(System.currentTimeMillis() - timeNow); System.out.println(item); System.out.println(" "); }).toList().toBlocking().first();
The result is:
154ms [5] 155ms [2] 155ms [1] 155ms [3] 155ms [4]
But what I would expect to see is something like this:
174ms [5] 230ms [2] 285ms [1] 345ms [3] 399ms [4]
What am I doing wrong?
-33166173 0 App crashes(unfortunately app has stopped) when click homebutton on phone?Using fragment app crashed when am click phone home button..i have 7 fragments in navigation.Apart from 2 fragment other not crashed when am clicked homebutton.i can not find issue. what the issue ? how can i solve it?
Source code
package com.system.soft.proj; import android.net.ParseException; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; public class Followupshistory extends android.support.v4.app.Fragment { ArrayList<Actors> actorsList; TextView tv9; Followuphistoryadapter adapter; ListView listview; String msg = "default"; String crmadminid=""; String adminname=""; String admintype=""; String userprivilege=""; String crmcmpid=""; String username=""; String corporate=""; String password=""; String id = "",fid="",distitle="",city=""; SessionManager session; private ProgressBar bar; Button b5; String message = "", ccompany = "", cassign = "", ccategtory = ""; ArrayList<Actors> temarr; String position = ""; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View rootView = inflater.inflate(R.layout.fragment_followupshistory, null); MainActivity.mTitle = " Followup "; ((MainActivity) getActivity()).restoreActionBar(); bar = (ProgressBar) rootView.findViewById(R.id.progressBar); tv9 = (TextView) rootView.findViewById(R.id.textView9); session = new SessionManager(getActivity()); b5 = (Button) rootView.findViewById(R.id.button5); HashMap<String, String> user = session.getUserDetails(); username = user.get(SessionManager.USERNAME); password = user.get(SessionManager.PASSWORD); corporate = user.get(SessionManager.CORPORATE); crmadminid = user.get(SessionManager.CRMADMINID); crmcmpid = user.get(SessionManager.CRMCMPID); adminname = user.get(SessionManager.ADMINNAME); admintype = user.get(SessionManager.ADMINTYPE); userprivilege = user.get(SessionManager.USERPRIVILEGE); Bundle bundle = this.getArguments(); id = bundle.getString("cid"); fid = bundle.getString("fid"); distitle = bundle.getString("distitle"); city= bundle.getString("city"); temarr = (ArrayList<Actors>) bundle.getSerializable("temparr"); ccategtory = bundle.getString("ccategtory"); ccompany = bundle.getString("ccompany"); cassign = bundle.getString("cassign"); city = bundle.getString("city"); position = bundle.getString("position"); tv9.setText(" Followup for "+ distitle+" Service ,Location "+city); actorsList = new ArrayList<Actors>(); new JSONAsyncTask().execute("http://example.com/datacapture.php?userprivilege="+userprivilege+"&admin_name="+adminname+"&admintype="+admintype+"&crm_admin_id="+crmadminid+"&corporate="+corporate+"&crm_cmpid="+crmcmpid+"&s="+id+"&user_name="+username+"&corporate="+corporate+"&password="+password+"&fid="+fid); listview = (ListView) rootView.findViewById(R.id.list); adapter = new Followuphistoryadapter(getActivity(), R.layout.followuphistoryrow, actorsList); listview.setAdapter(adapter); b5.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { // Toast.makeText(mContext, "followupid"+fid, Toast.LENGTH_LONG).show(); Fragment fragment = null; fragment = new Reassign(); Bundle bundle = new Bundle(); bundle.putString("cid", id); bundle.putString("fid", fid); bundle.putString("distitle", distitle); bundle.putString("city", city); bundle.putString("ccategtory", ccategtory); bundle.putString("ccompany", ccompany); bundle.putString("cassign", cassign); String pos=String.valueOf(position); bundle.putString("position", pos); bundle.putSerializable("temparr",temarr); fragment.setArguments(bundle); FragmentManager fragmentManager = (getActivity()).getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.container, fragment).addToBackStack(null).commit(); } catch (Exception e) { Toast.makeText(getActivity(), String.valueOf(e.getMessage()), Toast.LENGTH_LONG).show(); } } }); return rootView; } class JSONAsyncTask extends AsyncTask<String, Void, Boolean> { @Override protected void onPreExecute() { bar.setVisibility(View.VISIBLE); super.onPreExecute(); } @Override protected Boolean doInBackground(String... urls) { try { //------------------>> HttpGet httppost = new HttpGet(urls[0]); HttpClient httpclient = new DefaultHttpClient(); HttpResponse response = httpclient.execute(httppost); // StatusLine stat = response.getStatusLine(); int status = response.getStatusLine().getStatusCode(); if (status == 200) { HttpEntity entity = response.getEntity(); String data = EntityUtils.toString(entity); JSONObject jsono = new JSONObject(data); JSONArray jarray = jsono.getJSONArray("followshistory"); msg=String.valueOf(jarray.length()); for (int i = 0; i < jarray.length(); i++) { JSONObject object = jarray.getJSONObject(i); Actors actor = new Actors(); actor.setcompanyname(object.getString("followedon")); actor.setcontactperson(object.getString("creadtedby")); actor.setproduct(object.getString("remarks")); actor.setAssign(object.getString("nextdueon")); actor.setnextdue(object.getString("status")); actor.setlastaction(object.getString("smsstatus")); actor.setmobile(object.getString("message")); actorsList.add(actor); } return true; } //------------------>> } catch (ParseException e1) { e1.printStackTrace(); msg=String.valueOf(e1.getMessage().toString()); } catch (IOException e) { e.printStackTrace(); msg=String.valueOf(e.getMessage().toString()); } catch (JSONException e) { e.printStackTrace(); msg=String.valueOf(e.getMessage().toString()); } return false; } protected void onPostExecute(Boolean result) { bar.setVisibility(View.GONE); adapter.notifyDataSetChanged(); if(actorsList.size()==0) { Toast.makeText(getActivity().getApplicationContext(), "No Follow up Hostory", Toast.LENGTH_LONG).show(); } } } }
Xml file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.system.soft.proj.Followupshistory"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceSmall" android:text="Followup History" android:id="@+id/textView9" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:gravity="center_vertical|center_horizontal" android:textColor="#ffff3d15" android:textStyle="bold" android:layout_marginLeft="5dp" android:layout_marginTop="5dp" android:layout_toStartOf="@+id/button5" android:layout_toLeftOf="@+id/button5" android:padding="5dp" /> <ListView android:id="@+id/list" android:layout_width="wrap_content" android:layout_height="match_parent" tools:listitem="@layout/followuphistoryrow" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_gravity="center_horizontal" android:layout_marginBottom="5dp" android:layout_below="@+id/button5"> </ListView> <ProgressBar android:id="@+id/progressBar" style="?android:attr/progressBarStyleLarge" android:layout_width="wrap_content" android:layout_height="wrap_content" android:indeterminateDrawable="@drawable/progress" android:layout_gravity="center" android:layout_centerVertical="true" android:layout_centerHorizontal="true"></ProgressBar> <Button style="?android:attr/buttonStyleSmall" android:layout_width="40dp" android:layout_height="40dp" android:id="@+id/button5" android:layout_gravity="right|top" android:gravity="center_vertical|center_horizontal" android:background="@drawable/edit" android:layout_alignTop="@+id/textView9" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" android:layout_margin="5dp" /> </RelativeLayout>
-32196880 1 Copying a list of lists into part of another one in the most pythonic way I have a large list of lists, for now containing only zeros. I have another, smaller list of lists which I want to copy to certain positions in the bigger list of lists. I want to replace the original values. The only way I've found so far is this:
start = (startrow, startcol) for i in range( start[0], start[0] + len(shortlist) ): for j in range( start[1], start[1] + len(shortlist[0]) ): longlist[i][j] = shortlist[i-start[0]][j-start[1]]
However, this doesn't feel very pythonic - as far as I know, list comprehensions are in general prefered to loops, and even though I didn't find it in few hours of searching, there might be some function doing this more elegantly. So is there some better solution than mine?
EDIT: I'm interested in NumPy solutions as well, or perhaps even more than in plain Python ones.
-18523387 0No you won't able to see the console of the iOS simulator.
You must build it for iOS device and use xcode to see the Corona SDK print.
-16611213 0Alternatively, you can write your PHP scripts as you would normally (with some limitations),
And use the following command line:
C:\php.exe -f "D:\phpFile.php"
-23710079 0 For everyone, who faced this problem too.
Here are necessary steps to make docx4j works fine with images:
ae
.sun.awt.AppContext
to ae.sun.awt.AppContext
.In org.apache.xmlgraphics.util.Service
manually fill list with preloaders:
private static List<String> getProviderNames(Class<?> cls, ClassLoader cl) { ... if (fillDefautsProviderNames(cls, l)) return l; ... } private static boolean fillDefautsProviderNames(Class<?> cls, List<String> l) { if (cls == org.apache.xmlgraphics.image.loader.spi.ImagePreloader.class) { l.add("org.apache.xmlgraphics.image.loader.impl.PreloaderTIFF"); l.add("org.apache.xmlgraphics.image.loader.impl.PreloaderGIF"); l.add("org.apache.xmlgraphics.image.loader.impl.PreloaderJPEG"); l.add("org.apache.xmlgraphics.image.loader.impl.PreloaderBMP"); l.add("org.apache.xmlgraphics.image.loader.impl.PreloaderEMF"); l.add("org.apache.xmlgraphics.image.loader.impl.PreloaderEPS"); l.add("org.apache.xmlgraphics.image.loader.impl.imageio.PreloaderImageIO"); return true; } return false; }
Delete function displayImageInfo(ImageInfo info)
in org.docx4j.openpackaging.parts.WordprocessingML.BinaryPartAbstractImage
.
I've prepared repositories with changes: ae-awt, ae-xmlgraphics-commons, docx4j-android.
You can find compiled libs here: docx4j_images_prepared_libs.zip
Enjoy!
-20029574 0 Insert to the database error javai got this error :
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "Xavega" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:492) at java.lang.Integer.parseInt(Integer.java:527) at inspection.management.system.RegistrationForm.InsertRecord(RegistrationForm.java:352) at inspection.management.system.RegistrationForm.button1ActionPerformed(RegistrationForm.java:256) at inspection.management.system.RegistrationForm.access$000(RegistrationForm.java:12) at inspection.management.system.RegistrationForm$1.actionPerformed(RegistrationForm.java:109) at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018) at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341) at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402) at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259) at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252) at java.awt.Component.processMouseEvent(Component.java:6505) at javax.swing.JComponent.processMouseEvent(JComponent.java:3320) at java.awt.Component.processEvent(Component.java:6270) at java.awt.Container.processEvent(Container.java:2229) at java.awt.Component.dispatchEventImpl(Component.java:4861) at java.awt.Container.dispatchEventImpl(Container.java:2287) at java.awt.Component.dispatchEvent(Component.java:4687) at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832) at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492) at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422) at java.awt.Container.dispatchEventImpl(Container.java:2273) at java.awt.Window.dispatchEventImpl(Window.java:2719) at java.awt.Component.dispatchEvent(Component.java:4687) at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:735) at java.awt.EventQueue.access$200(EventQueue.java:103) at java.awt.EventQueue$3.run(EventQueue.java:694) at java.awt.EventQueue$3.run(EventQueue.java:692) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76) at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87) at java.awt.EventQueue$4.run(EventQueue.java:708) at java.awt.EventQueue$4.run(EventQueue.java:706) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76) at java.awt.EventQueue.dispatchEvent(EventQueue.java:705) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138) at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
while trying to inserting JPasswordField text to the database
Here is my code:
String _passwordField1 = passwordField1.getText(); int _password = Integer.parseInt(_passwordField1); try { String driver = "sun.jdbc.odbc.JdbcOdbcDriver"; Class.forName(driver); String url = "jdbc:odbc:Database"; conn = DriverManager.getConnection(url); String command = "insert into Member (Password) values (?)"; PreparedStatement statement = conn.prepareStatement(command); statement.setInt(2, _password); statement.executeUpdate(command); } catch (Exception e) { System.err.println(e.getMessage()); _sound.PlaySound(2); _infoBox.ShowMessageBox(e.getMessage(), "Error", 2); _reminder = new Reminder(1); JOptionPane.showOptionDialog(null, "Program will be closed due to error", "Error", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, new Object[]{}, null); System.exit(0); }
-19438824 0 Is Better csv or sqlite for preload data into Core data? I have to preload data into my core data to have always my entities full of data, since the first time someone start the application. I have a database in csv and other sqlite. which is the best? and How should I do it? I mean, I guess I should have my database always in a folder of my app and the first time I launch the app I will fill data into database. isn't it? or I am wrong? if this is the good way? How I do it?
-13993551 0 Could I wrap c++ library to Adobe Air native extension for mobile IOS/AndroidCan I wrap a C++ library to Adobe Air native extension IOS/Android?
I have a C++ library that was written by third party. I want to use that library for an adobe air native extension for mobile? Will I be able to do it. If so, where can I find some guidelines?
-14186613 0 PDO rowCount ErrorI am using PDO for the first time. I created this method, and I am getting this error:
Call to a member function rowCount() on a non-object
The following is my code.
$db = new PDO("mysql:host=$dbhost;dbname=$dbname;charset=utf8", $dbuser, $dbpassword) function doesRecordExist($query) { global $db; try { $stmt = $db->query($query); $count = $stmt->rowCount(); return $count; } catch (PDOException $ex) { die($ex->getMessage()); } }
Can you help me please
-29780783 0 I don't know why my code won't runI'm making a calculator program, and I got everything setup and it was working earlier, but after I added a method, when I run in debug mode, Eclipse says I have an error in my main method. I don't know why it won't run.
The error I get: Exception in thread "main" java.lang.Error: Unresolved compilation problem:
at com.molotuff.main.Calculator.main(Calculator.java:13)
Here is my code:
package com.molotuff.main; import java.util.ArrayList; import java.util.Scanner; public class Calculator { private static Scanner reader = new Scanner(System.in); private static boolean running = true; private static boolean calcRunning = true; private static String command; private static ArrayList<Integer> nums = new ArrayList<Integer>(); public static void main(String[] args) { System.out.println("*****************************"); System.out.println("* Welcome to The Calculator *"); System.out.println("*****************************"); menu("help"); while(running) { System.out.println("Enter a command:"); command = reader.nextLine(); menu(command); if(command.equalsIgnoreCase("quit")) { running = false; } if(command.equalsIgnoreCase("add")) { getNums(); int answer = Calculations.sum(nums); System.out.println("The sum is: " + answer); } } } public static void menu(String command) { if(command.equalsIgnoreCase("help")) { System.out.println("Commands: "); System.out.println("Quit"); System.out.println("Help"); System.out.println("Add"); System.out.println("Subtract"); System.out.println("Divide"); System.out.println("Multiply"); System.out.println("Type help [command] for more info on that command"); } if(command.equalsIgnoreCase("help quit")) { System.out.println("Quit: quits the program."); } if(command.equalsIgnoreCase("help help")) { System.out.println("Help: prints the help menu."); } if(command.equalsIgnoreCase("help add")) { System.out.println("Add: takes numbers inputed and adds them together."); } if(command.equalsIgnoreCase("help Subtract")) { System.out.println("Subtract: takes a set of numbers and subtracts them \n (note: " + "subtracts in this order [first num entered] - [second num entered] " + "etc.)"); } if(command.equalsIgnoreCase("help multiply")) { System.out.println("Add: takes numbers inputed and multiplies them together."); } if(command.equalsIgnoreCase("help divide")) { System.out.println("Subtract: takes a set of numbers and divides them \n (note: " + "divides in this order [first num entered] / [second num entered] " + "etc.)"); } } } public static void getNums() { while(calcRunning) { String userInput = reader.nextLine(); int userNums; if(userInput.isEmpty()) { calcRunning = false; } else { userNums = Integer.parseInt(userInput); nums.add(userNums); } } } }
-10141995 0 Since you use jquery, you might as well use plugin jgrow for that
-15259915 0I realise this is an old question and you maybe already have an answer (or have no need for one now) but it looks like it's RML-1, assuming my searches were correct.
I first found this which showed very similar code to your example. It mentions ArtCAM and output for the MDX-540, a Roland machine.
Searching Roland's milling machines for information was a bit useless, but going through their 3D products for the MDX-540 mentions that the control command sets is "RML-1 and NC codes".
Then searching for RML-1 gives a result for a PDF manual.
Reading that PDF it looks like the single letter commands are "Mode 1", the ^ is used to select Mode2 and the 2 letter commands are Mode2 commands. !xx commands are common to both Mode1 and Mode2.
^PR sets the movement to relative mode. ^PA sets the movement to absolute mode. Z moves.
Looking at your code sample it appears as if most positions are absolute and you'd need to re-write them all.
-30165207 0git clone https://github.com/3rdcycle/pyqtgraph.git
git checkout origin/date-axis-item
pip uninstall pyqtgraph
python setup.py install
and changing your example to:
# -*- coding: utf-8 -*- """ Description of example """ import pyqtgraph as pg from pyqtgraph.Qt import QtCore, QtGui import numpy as np pg.mkQApp() axis = pg.DateAxisItem(orientation='bottom') pw = pg.PlotWidget(axisItems={'bottom': axis}) pw.setWindowTitle('pyqtgraph example: DateTimeAxis') pw.show() pw.setXRange(1383960000, 1384020000) ## Start Qt event loop unless running in interactive mode or using pyside. if __name__ == '__main__': import sys if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'): QtGui.QApplication.instance().exe
should work.
-5029940 0 ANT attribute in regex patternI'm writing an utility macro wich involves checking whether a comma-separated list list
contains or not a particular value value
.
<macrodef name="csvcontains"> <attribute name="value"/> <attribute name="list"/> <attribute name="casesensitive" default="false"/> <sequential> <condition property="matched" else="false"> <matches string="@{list}" pattern="TODO" casesensitive="@{casesensitive}"/> </condition> </sequential> </macrodef>
I cannot get the pattern right, because I'm not sure of how to escape @{value}
(and to match a comma-separated pattern).
How to build the pattern?
Thanks
-37164188 0 Calling variables from other classimport java.util.Scanner; public class ThreadClass{ public static void main(String[] args) { System.out.println("Enter the characters, Press Enter to begin"); System.out.println("The quick brown fox jumps over the lazy dog"); Scanner sc=new Scanner(System.in); String scr= sc.nextLine(); MyThread tr=new MyThread(); try { tr.sleep(11000); System.out.println("Time Over"); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public class MyThread extends Thread{ public void run() { System.out.println("Time over"); ThreadClass tc=new ThreadClass(); String str=tc.scr; if(str.equals("The quick brown fox jumps over the lazy dog")) { System.out.println("Successfully completed"); } else { System.out.println("The typed Words do not match"); } } }
I am trying to make an application that prompts the user to type a string within 11 seconds. To accomplish this I have two classes namely ThreadClass and MyThread. In Thread class I have defined methods to take input from the user and to set the timer to 10 seconds. In MyThread class I have defined methods for post thread completion i.e. what the program will do after the time is over. I want to add a feature in MyThread class so that it compares the user input with the string provided. The problem is that when I try to access the String variable scr, defined in ThreadClass from MyThread class by creating an it gives me an error. Even if I try to extend ThreadClass from MyThread class it gives me an error. Also declaring scr as static gives me the same result. Is there any possible way to use scr variable in MyThread?
-13118637 1 MongoKit's callable object has no attribute 'find_and_modify'I'm using MongoKit as ODM framework. I have object User:
class User(Document): __collection__ = 'users' ...
There is no __database__
here - I'm using different ones depend on current profile (development, testing etc.) I use queries like this to access data:
app.db.User.one({'email_confirmation_token.hex': token_hex})
It works fine. Now I need to use find_and_modify command. According to documentation, I should call this method from collection to get dict or from object to get object.
This call works:
app.db.users.find_and_modify({'email_confirmation_token.hex': token_hex}, {'$set': {'active': True}})
but this - doesn't:
app.db.User.find_and_modify({'email_confirmation_token.hex': token_hex}, {'$set': {'active': True}})
Error message is: AttributeError: 'CallableUser' object has no attribute 'find_and_modify'.
Why it doesn't contain this attribute?
-1980412 0 Section headerview in UITableView DuplicatedI am creating an application and I have a customized header of tableview. But sometimes the header gets duplicated. It takes the place of a row in tableview. How do I solve this strange problem? BTW, my tableviewstyle is plain, Header height is 44.0 and the footer height is 0.0. Here is an image how it displays. The header "comments" is duplicated just below the header "Messages" while it should be the row.
Here is the complete implementation of this view
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib. - (void)viewDidLoad { [super viewDidLoad]; TitleForSectionView=[[NSArray arrayWithObjects:@"Dates To Remember",@"Messages",@"Comments",@"Wishlist",@"Reminders",@"Bookmarks",nil] retain]; self.MySectionIndexArray=[[NSMutableArray alloc] init]; [self.MySectionIndexArray addObject:@"UP"]; [self.MySectionIndexArray addObject:@"DOWN"]; [self.MySectionIndexArray addObject:@"DOWN"]; [self.MySectionIndexArray addObject:@"DOWN"]; [self.MySectionIndexArray addObject:@"DOWN"]; [self.MySectionIndexArray addObject:@"DOWN"]; self.IconsForSectionsView=[[NSMutableArray alloc] init]; [self.IconsForSectionsView addObject:[UIImage imageNamed:@"IconCalender.png"]]; [self.IconsForSectionsView addObject:[UIImage imageNamed:@"IconMessage.png"]]; [self.IconsForSectionsView addObject:[UIImage imageNamed:@"IconComments.png"]]; [self.IconsForSectionsView addObject:[UIImage imageNamed:@"IconWishList.png"]]; [self.IconsForSectionsView addObject:[UIImage imageNamed:@"IconReminder.png"]]; [self.IconsForSectionsView addObject:[UIImage imageNamed:@"IconBookMark.png"]]; } - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 6; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { if ([[self.MySectionIndexArray objectAtIndex:section] isEqualToString:@"UP"]) { return 4; } else { return 0; } } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *MyDashBoardCell=nil; static NSString *AddNewDateCellIdentifier=@"AddNewDateCell"; static NSString *CellIdentifier = @"DashBoardCell"; DashBoardCustomCellObject = (DashBoardCustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (DashBoardCustomCellObject == nil) { [[[[NSBundle mainBundle] loadNibNamed:@"DashBoardCustomCell" owner:self options:nil] retain]autorelease]; } [DashBoardCustomCellObject SetDashBoardCellData:@"Mar 9" EventText:@"My Birthday"]; AddNewDateCellObject = (AddNewDateCell *)[tableView dequeueReusableCellWithIdentifier:AddNewDateCellIdentifier]; if (AddNewDateCellObject == nil) { [[[[NSBundle mainBundle] loadNibNamed:@"AddNewDateCell" owner:self options:nil] retain]autorelease]; } if(indexPath.section==0 && indexPath.row==0) { MyDashBoardCell=AddNewDateCellObject; } else { MyDashBoardCell=DashBoardCustomCellObject; } return MyDashBoardCell; } - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { // create the parent view that will hold header Label and button and icon image self.customView = [[[UIView alloc] initWithFrame:CGRectMake(0,0,tableView.bounds.size.width,44)] autorelease]; self.customView.backgroundColor=[UIColor whiteColor]; // create image object UIImageView *icon= [[[UIImageView alloc] initWithImage:[self.IconsForSectionsView objectAtIndex:section]] autorelease]; icon.contentMode=UIViewContentModeCenter; icon.frame = CGRectMake(0,0,40,40); // create the label objects UILabel *headerLabel = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease]; headerLabel.backgroundColor = [UIColor clearColor]; headerLabel.font = [UIFont boldSystemFontOfSize:13]; headerLabel.frame = CGRectMake(53,11,172,21); headerLabel.text = [TitleForSectionView objectAtIndex:section]; headerLabel.textColor = [UIColor blackColor]; headerLabel.highlightedTextColor=[UIColor whiteColor]; // create the button objects ButtonDrop = [[[UIButton alloc] initWithFrame:CGRectMake(278, 9, 25, 25)] autorelease]; ButtonDrop.tag=section; if ([[self.MySectionIndexArray objectAtIndex:section] isEqualToString:@"UP"]) { [ButtonDrop setBackgroundImage:[UIImage imageNamed:@"Up.png"] forState:UIControlStateNormal]; self.customView.backgroundColor=[UIColor blueColor]; headerLabel.highlighted=YES; } else { [ButtonDrop setBackgroundImage:[UIImage imageNamed:@"Down.png"] forState:UIControlStateNormal]; } [ButtonDrop addTarget:self action:@selector(checkAction:) forControlEvents:UIControlEventTouchUpInside]; [self.customView addSubview:icon]; [self.customView addSubview:headerLabel]; [self.customView addSubview:ButtonDrop]; return self.customView; } - (void)checkAction:(id)sender { UIButton *Button = (UIButton*)sender; NSLog(@"Button Tag=%d",Button.tag); if([[self.MySectionIndexArray objectAtIndex:Button.tag] isEqualToString:@"UP"]) { [self.MySectionIndexArray replaceObjectAtIndex:Button.tag withObject:@"DOWN"]; [ButtonDrop setBackgroundImage:[UIImage imageNamed:@"Up.png"] forState:UIControlStateNormal]; } else { [self.MySectionIndexArray replaceObjectAtIndex:Button.tag withObject:@"UP"]; [ButtonDrop setBackgroundImage:[UIImage imageNamed:@"Down.png"] forState:UIControlStateNormal]; } [TableDashBoard reloadSections:[NSIndexSet indexSetWithIndex:Button.tag] withRowAnimation:UITableViewRowAnimationFade]; }
-23098557 0 Your default from:
should be an email address rather than a URL. This specifies the address that will appear as the from in emails sent.
You can modify the from on a per message basis by putting it in your Mailer's methods.
-19475643 0 Prolog Time Overlap WoesSay I have this Knowledge Base:
free(ann,slot(time(8,0),time(9,0))). free(ann,slot(time(10,0),time(11,0))). free(bob,slot(time(7,0),time(8,30))). free(bob,slot(time(10,0),time(11,0))). free(carla,slot(time(8,0),time(9,0))). free(carla,slot(time(10,0),time(10,15))).
So, after a lot of effort, I managed to write something that prints the first person who has availability during a specific slot with the following code:
meetone(Person, slot(time(BeginHour, BeginMinute), time(EndHour, EndMinute))) :- free(Person, slot(time(BH, BM), time(EH, EM))), BH*60 + BM =< EndHour*60 + EndMinute, EH*60 + EM >= BeginHour*60 + BeginMinute. main :- (meetone(Person,slot(time(7,15),time(7,20))); halt), write(Person), nl, halt. :- initialization(main).
This prints bob, the expected result.
Here's where it gets complicated (at least for me). Let's say I want to find out all the time slots everyone in the Knowledge Base has in common. The following code demonstrates how I ultimately want to call this:
people([ann,bob,carla]). meet :- ??? main :- (setof(Slot,meet(Slot),Slots); halt), write(Slots), nl, halt. :- initialization(main).
Here's some vague pseudocode that I think might accomplish what I'm looking for, but I'm not experienced enough to get it working.
The final output would show slots of 8:00 - 8:30 and 10:00 - 10:15. Any help in accomplishing this would be greatly appreciated.
-2264442 0 How much precision for a bcmath PHP library?I'm writing a PHP library that has a Number class that uses the bcmath
extension for arbitrary precision.
I have two questions:
How much slower is bcmath compared to using the built-in int and float types?
bcmath
has an optional scale argument (that defaults to 3 digits). For an general purpose Number class that anyone could use, what would be a good level of precision? How do languages like Perl (that have arbitrary precision numbers) deal with scale?
The point is that your "password protection" is useless if a hacker can simply bypass that and read your database directly. We don't know if they can, but - as the docs say - the dev server has undergone no security testing whatsoever, so they might well be able to.
Plus, the server is single-threaded. It will only ever be able to serve one request at a time. That makes for a very slow experience for your users.
Seriously, there is no reason to do this. Setting up Apache + mod_wsgi, or whatever your preferred hosting environment is, is a five-minute process if you follow the very detailed instructions.
-41015274 0 Why NSDictionary will loose the proper formate after adding the data?I am trying to add data in the NSdictionary with the following format
{"task_id": "101", "user_id": "111", "parent": "0", "task_name": "buy gift for friends birthday party", "repeat_alarm": "0", "alert_type": "1", "alert_file_name": "mypersonal_reminder_audio", "notification_date": "2017-01-05", "notification_time": "11:15:00", "status": "1", "subtasks":"addTaskArray"}
But when i run the application it print in the different format.
{"task_id" = "1", "user_id" = "167", "parent" = "0", "task_name" = "buy gift for friends birthday party", "repeat_alarm" = "0", "alert_type" = "1", "alert_file_name" = "mypersonal_reminder_audio", "notification_date" = "2017-01-05", "notification_time" = "11:15:00", "status" = "1", "subtasks" = "addTaskArray"}
I need any one help me out how i will remove "=" sign from the NSDictionary,Even though i want to add this NSDictionary in the NSArray with following format.
[ {"task_id": "101", "user_id": "111", "parent": "0", "task_name": "buy gift for friends birthday party", "repeat_alarm": "0", "alert_type": "1", "alert_file_name": "mypersonal_reminder_audio", "notification_date": "2017-01-05", "notification_time": "11:15:00", "status": "1", "subtasks":"addTaskArray"} ]
I am trying to pass this parameter using "Alamofire" request but it gives me such a internal server error because of my request parameter which is wrong. Any one please help me out how i will create this request ? and i will successfully pass as parameter to "Alamofire".
I am trying to use this following code for post the request.
var request = URLRequest(url: url) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content- Type") values = ["task_id": "1", "user_id": "167", "parent": "0", "task_name": "buy gift for friends birthday party", "repeat_alarm": "0", "alert_type": "1", "alert_file_name": "mypersonal_reminder_audio", "notification_date": "2017-01-05", "notification_time": "11:15:00", "status": "1", "subtasks":"addTaskArray"] request.httpBody = try! JSONSerialization.data(withJSONObject: values) Alamofire.request(request).responseJSON { response in switch response.result { case .failure(let error): print(error) if let data = response.data, let responseString = String(data: data, encoding: .utf8) { print(responseString) } case .success(let responseObject): print(responseObject) } }
Your help will be appreciate.
Thanks.
-32492439 0try this (Pure JS Solution)
<p> Date: <input type="date" name="currentDate" id="currentDate" /> </p> <script> var today = new Date(); var dd = today.getDate(); var mm = today.getMonth() + 1; //January is 0! var yyyy = today.getFullYear(); if (dd < 10) { dd = '0' + dd } if (mm < 10) { mm = '0' + mm } var today = dd + '/' + mm + '/' + yyyy; document.getElementById('currentDate').value = today; </script>
Well some basic hints :
A lot more to be said. But try to do simple things first :) Then you can begin to read advanced article about loop unrolling and the rest.
EDIT:
As said in some comments, your compiler should optimize out some or all things I have pointed out. One can even argues that doing too many specific optimizations can be counter produtive as it might impair the compiler optimization capabilities.
So one basic advice : - mesure the perfs of your initial algorithm - do one possible optimization - mesure the gain
This way you will learn a lot about your compiler automatic optimization :)
EDIT 2:
As said in comments, my ubuntu 64bit with 4Gbytes RAM refuse to allocate the vector :) With a more reasonable billion limit, time give about 14 seconds. removing cout just gain about a second.
As andreas said, the problem is the storage of the result. you have to store the inner loop result on disk !
my 2 cents
-36127879 0 Get YouTube video embed code with getVideoData().video_idI have a page that loads several youtube videos and should do something when a video is paused.
So I have a test function that catches the pause event...
I need to make it dynamic (the function should by itself recuperate the ids of frame and the video that calls that function).
var player; function floaded(iframe) { // how to recuperate the video ID? player = new YT.Player(iframe.id, { videoId: 'amDMGIyyrlw', events: { 'onStateChange': function(event) { if (event.data == YT.PlayerState.PLAYING) { alert("Playing.."); } else if (event.data == YT.PlayerState.PAUSED) { alert("Paused.."); } } } }); }
<h2>Pause this video: </h2> <div style="width:250px"> <div class="video-container"> <iframe id="test456" src="https://www.youtube.com/embed/amDMGIyyrlw?enablejsapi=1" onload="floaded(this)"> </iframe> </div> </div>
The frame id is easy to recuperate from the iframe object: iframe.id
But the main problem is the video id... From the onStateChange event is very easy to recuperate the video embeded code:
?event.target.getVideoData().video_id "amDMGIyyrlw"
However is too late in the event, cause I need it before, when only creating the player object...
I know there is ways to recuperate the video embedded code by a regular expression.
However is there a way to use the getVideoData().video_id
to recuperate the video id dynamically?
Enum compareTo seems to be final and cant be overriden Why is compareTo on an Enum final in Java?
Just do Collections.sort() which will order the list in enum order as you need
-9567246 0 Use ptrace to obtain machine instructionsI wrote a simple program to get instructions of a process using ptrace. You can find the code here
I compiled and ran it in under Ubuntu 64bit.
What I got is something like this:
EIP: 7f7e5edf5c75 Instruction executed: 8824848948f0394c EIP: 7f7e5edf5c78 Instruction executed: 8824848948 EIP: 7f7e5edf5c80 Instruction executed: 84f6000000da840f EIP: 7f7e5edf5c86 Instruction executed: 2000000b42484f6 ... ... EIP: 400dab Instruction executed: e8c78948ef458d48 EIP: 400daf Instruction executed: fffffe29e8c78948 EIP: 400db2 Instruction executed: 458d48fffffe29e8 EIP: 400be0 Instruction executed: d680020148225ff ... ... EIP: 7f7e5ee012f0 Instruction executed: 2404894838ec8348 EIP: 7f7e5ee012f4 Instruction executed: 244c894824048948 ... ...
When I used gdb, I only can see those instruction under EIP: 400dab... I can't find those under 7f... so I guess It was wrong...
(gdb) x/20xg 0x0000000000400dab 0x400dab <main+135>: 0xe8c78948ef458d48 0xee458d48fffffe29 0x400dbb <main+151>: 0xfffffe4de8c78948 0x10c0834880458b48 0x400dcb <main+167>: 0x48ee558d48088b48 0x8948ce8948c0458d
Can anyone explain why my code is wrong and how to print only the correct EIP and instructions ?
-21062436 0The below mentioned link solution helps:
https://github.com/evrone/quiet_assets
Also as below it's working fine for me
3.1 (only) (3.2 breaks before_dipatch)
app\config\initializers\quiet_assets.rb Rails.application.assets.logger = Logger.new('/dev/null') Rails::Rack::Logger.class_eval do def before_dispatch_with_quiet_assets(env) before_dispatch_without_quiet_assets(env) unless env['PATH_INFO'].index("/assets/") == 0 end alias_method_chain :before_dispatch, :quiet_assets end 3.2 Rails - Rack root tap approach app\config\initializers\quiet_assets.rb Rails.application.assets.logger = Logger.new('/dev/null') Rails::Rack::Logger.class_eval do def call_with_quiet_assets(env) previous_level = Rails.logger.level Rails.logger.level = Logger::ERROR if env['PATH_INFO'].index("/assets/") == 0 call_without_quiet_assets(env).tap do Rails.logger.level = previous_level end end alias_method_chain :call, :quiet_assets end
-4083918 0 A quick way to do it would be if your javascript code is embedded in a php file (not an external link to a .js file), you could just do a PHP print right in between your <script></script>
tags. It would work with bookmarks and pasting the URL to the address bar.
For example:
<script type="text/javascript"> var get_var; get_var = <? print $_GET['varname']; ?>; // some jQuery code here </script>
This should only be used as a proof of concept. This is vulnerable to XSS attacks, and should not be used in production. This list of XSS prevention techniques is a good place to start (but outside the scope of the OP's question).
-15547783 0I had Problems with the automatic positioning of X-Axis labels. Positioning of rotated Text would be a good place to start. To give you an example what would not work - here is the function I found for simulating the getBBox() functionality:
ep = Element.prototype; ep.getBBox = function() { var w = 10; if (ep.tagName == "TEXT" && ep.firstChild) { var s = ep.firstChild.innerHTML; w = s.length * 5; } return { x : ep.offsetLeft ? ep.offsetLeft : 0, y : ep.offsetTop ? ep.offsetTop : 0, width : w, height : 16 }; };
As you see it is pretty barebones - just approximates Textlength and returns a default width and height otherwise.
-10417010 0 on using oracle database link theres an error "ORA-12154 TNS Could not resolve the connect identifier specified"I'm trying to define a database link on oracle 10.2 with connection identifier that throws the error in the question header. I have the connection identifier (service name) in my tnsnames.ora file. I can connect with sqlplus using this service name. no problem. This is the creation sql:
create database link dev1.REGRESS.RDBMS.DEV.US.ORACLE.COM connect to user1 identified by pass1 using 'dev1';
select using the link: select * from t_users@dev1;
I get: ORA-12154: TNS:could not resolve the connect identifier specified
connecting to oracle with sqlplus to the 'unidentified' service (with no problem): sqlplus user1/pass1@dev1
I defined another link to the same database I'm woking in (loopback) - works OK.
I read and tried anything I could find about the subject but did not solve this.
Any suggestions?
-5174329 0Assuming current version of Eclipse and Maven plugin, is this something that can be solved by adding Maven dependencies to "project deployment assembly"? If you have your project configured as Dynamic Web Project and Tomcat as server in Eclipse, this is under Project->Deployment Assembly->Add->java build path entries -> Maven dependencies.
-37089050 0using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO.Ports; namespace AGAING { public partial class Form1 : Form { // int[] OUT = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // The array must be send by AUNO the resend to it. byte[] OUT = new byte[12]; byte lamp = 0; // The index of lamp type array, and the indecation of the lamp type in the OUT array ti the AUNO. string[] lampType = { "ENERGY SAVER", "TUNGSTEN", "FLUORESCENT", "METAL HALIDE" }; // Array for lamp type identification. int sample; // The index of the report matrix, and giving number of test we did. int[] endsample = new int [12]; //index array for saving the ended sample date. int reportlenth = 3; // lenth of reporting arrays string[] smplNo = new string[3]; //Array for sample number reporting. string[] smpltype = new string[3]; // Array for sample lamp type reporting. string[] startdate = new string[3]; // Array for sample starting date reporting. string[] enddate = new string[3]; // Array for sample ending date reporting. public Form1() { InitializeComponent(); // getportnames(); //serialPort1.Open(); } // void getportnames() //{ // string[] port = SerialPort.GetPortNames(); //PortcomboBox1.Items.AddRange(port); // } void warning(string warning) // Worning message properties. { MessageBox.Show(warning, "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); } private void Form1_Load(object sender, EventArgs e) { serialPort1.Open(); } private void Form1_FormClosing(Object sender, FormClosingEventArgs e) { serialPort1.Close(); } private void lamptype_SelectedIndexChanged(object sender, EventArgs e) // Projection the combo box of lamp type to the OUT Array { if (lamptype.SelectedIndex == 0) { lamp = 1; } else if (lamptype.SelectedIndex == 1) { lamp = 2; } else if (lamptype.SelectedIndex == 2) { lamp = 3; } else if (lamptype.SelectedIndex == 3) { lamp = 4; } else if (lamptype.SelectedIndex == -1) { lamp = 0; } } private void out1_CheckedChanged_1(object sender, EventArgs e) { if (out1.Checked) {// If check box selected change its properties out1.Font = new Font(out1.Font, FontStyle.Bold); //Change text box properties. sampleno1.Clear(); sampleno1.Enabled = true; //Change text box properties. enddate1.Clear(); datetime1.Clear(); lamptype1.Clear(); } else {// unless reset the check box out1.Font = new Font(out1.Font, FontStyle.Regular); //Change text box properties. sampleno1.Enabled = false; // Reset the lamp type selection. lamptype.SelectedIndex = -1; lamptype.Text = "__Select lamp type__"; } // serialPort1.Write(OUT, 0, 12); } private void run1_Click_1(object sender, EventArgs e) {//Check if any data are not marked give wornings. if (out1.Checked == false) { warning("Select output"); } else if (lamptype.SelectedIndex < 0) { warning("Select Lamp Type"); } else if (String.IsNullOrEmpty(sampleno1.Text)) { warning("Enter sample number"); } else if (sampleno1.TextLength != 10) { warning("Enter sample number correctly"); } else {// If yes change check box properties out1.Enabled = false; // Change run button properties run1.Text = "In Use"; run1.Enabled = false; run1.BackColor = Color.LightGreen; run1.Font = new Font(run1.Font, FontStyle.Bold); // Change text box properties sampleno1.Enabled = false; // Change stop button properties stop1.Enabled = true; stop1.BackColor = Color.OrangeRed; stop1.Font = new Font(stop1.Font, FontStyle.Bold); // Marking lamp type na d aoth data in text bos and reset lamp type combo box lamptype1.Text = lampType[lamp - 1]; lamptype.Text = "__Select lamp type__"; // Show the starting date. datetime1.Text = DateTime.Now.ToString("dd/mm/yyyy, hh:mm:ss"); // Save the sample data. smplNo[sample] = sampleno1.Text; // Save the sample number. smpltype[sample] = lamptype1.Text; // Save the lamp type date. startdate[sample] = datetime1.Text; // Save the starting date. // Save the reporting index for the ending date. endsample[0] = sample; // Increase the reporting index to give the sample counter and show it. sample++; MessageBox.Show("This is test no. " + sample); // Worning to reset the saving data arraies. the reset it. if (sample == reportlenth - 1) { warning("Only 1 more sample and the reporting system will reset, please inform the responsible"); } else if (sample == reportlenth) { warning("The reporting system will reset, please inform the responsible"); sample = 0; } //******************************************************************************// // Set the output lamp type in the OUT array for AUNO. OUT[0] = lamp; } // //serialPort1.WriteLine("$"); serialPort1.Write(OUT, 0, 12); }
-16209348 0 it means 2*10^4
and try it in your console 2e4
the output will be 20000
the e
is the scientific notation
the code is equivilant to
... e.animate({along: 1}, 20000, function () { ....
-38010555 0 AngularJs2 get the find() method in component for element Here I want to check, if user click outside of my "DropdownComponent" element than hide some data. But "this.templateRef.nativeElement.find" I am not able to get "find()" method in angularJS2.
import { Component, EventEmitter, ElementRef, Output, HostListener } from '@angular/core'; export class DropdownComponent{ showValue = true; constructor(private templateRef: ElementRef) { }; @HostListener('document:click', ['$event']) handleKeyboardEvent(kbdEvent: any) { console.log("---"+ kbdEvent); var isClickedElementChildOfDropdownComponent = this.templateRef.nativeElement.find(kbdEvent.target).length > 0; if(isClickedElementChildOfDropdownComponent ) { return; } this.showValue = false; }
}
-26009265 0 How to do a validation to find duplicate entries ? knockoutI have a scenario when i dynamically add multiple rows using template
way i need to write down a validation if CountryCode
(which should be unique) having same value in two or more dynamically generated rows .
working fiddle : http://jsfiddle.net/JL26Z/73/
Well i am thinking can this be possible using custom validation code but i am not sure how to proceed i mean how to compare in validator
function inside validation
.
And the same can be done on click of submit
in save function like we run a foreach each aganist every row code
and do it but is it a good practice .
My view model:
function Phone() { var self = this; self.Code = ko.observable(""); // this should be unique self.Date = ko.observable(""); self.PhoneNumber = ko.observable(""); self.Validation = ko.validatedObservable([ self.Code.extend({ required: true }), self.Date.extend({ required: true }), self.PhoneNumber.extend({ required: true }) ]); } function PhoneViewModel() { var self = this; self.PhoneList = ko.observableArray([new Phone()]); self.remove = function () { self.PhoneList.remove(this); }; self.add = function () { self.PhoneList.push(new Phone()); // i add on click of add button }; } ko.applyBindings(new PhoneViewModel());
Any suggestions are appreciated .
-26748767 0You should not use static methods to share non-static data between activities. For this purpose please use Intent you passing as temporary storage of your data. For example you provided you can refer to putStringArrayListExtra()
-34557091 1 ImportError: cannot import name RemovedInDjango19WarningI'm on Django 1.8.7 and I've just installed Django-Allauth by cloning the repo and running pip install in the app's directory in my webapp on the terminal. Now when I run manage.py migrate, I get this error:
➜src git:(master) ✗ python manage.py migrate Traceback (most recent call last): File "manage.py", line 8, in <module> from django.core.management import execute_from_command_line File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 10, in <module> from django.apps import apps File "/Library/Python/2.7/site-packages/django/apps/__init__.py", line 1, in <module> from .config import AppConfig File "/Library/Python/2.7/site-packages/django/apps/config.py", line 6, in <module> from django.utils.module_loading import module_has_submodule File "/Library/Python/2.7/site-packages/django/utils/module_loading.py", line 4, in <module> from importlib import import_module File "/Library/Python/2.7/site-packages/django/utils/importlib.py", line 6, in <module> from django.utils.deprecation import RemovedInDjango19Warning ImportError: cannot import name RemovedInDjango19Warning ➜ src git:(master) ✗
I've checked and I'm still on django 1.8.7 so it wasn't accidently upgraded.
-4464759 0;WITH set1 AS (SELECT * FROM Privileges WHERE Privilege IN (1, 3)) SELECT up.UserId FROM UserPrivileges up INNER JOIN set1 ON set1.Privilege = set1.Privilege GROUP BY up.UserId HAVING COUNT(up.Privilege) = (SELECT COUNT(*) FROM set1);
-17634922 0 Haven't tested it, but I think the following should work.
def index @histories = History.all(:order => 'REPLACE(title,"Post","")+0 ASC') end mysql> desc z; +------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+--------------+------+-----+---------+-------+ | a | varchar(255) | YES | | NULL | | +-------+--------------+------+-----+---------+-------+ 1 row in set (0.00 sec) mysql> select * from z; +---------+ | a | +---------+ | post 1 | | post 11 | | post 2 | +---------+ 3 rows in set (0.00 sec) mysql> select * from z order by a asc; +---------+ | a | +---------+ | post 1 | | post 11 | | post 2 | +---------+ 3 rows in set (0.00 sec) mysql> select * from z order by REPLACE(a,"post","")+0 ASC; +---------+ | a | +---------+ | post 1 | | post 2 | | post 11 | +---------+ 3 rows in set (0.00 sec)
-477518 0 I believe this is a better alternative if you're optimizing for speed:
int n = 5; for(int i = n;i > 0;i--) { //executing 5times }
The reason for that is that comparing with 0 is faster.
-39019237 0In catch block,before rolling back the transaction,do the following...
DECLARE @TABLE AS TABLE (COL1 INT, COL2 INT ... ) INSERT INTO @TABLE SELECT * FROM #TEMP TABLE ROLLBACK TRANSCATION INSERT INTO DLWMS_ALLOCATIONMISSINGLOG select * from @table
References:
http://sqlmag.com/t-sql/table-variable-tip
You can also fudge multi-dimensional arrays if you always have all of the key values, or you just don't need to access the individual levels as separate arrays:
$arr{"foo",1} = "one"; $arr{"bar",2} = "two"; while(($key, $value) = each(%arr)) { @keyValues = split($;, $key); print "key = [", join(",", @keyValues), "] : value = [", $value, "]\n"; }
This uses the subscript separator "$;" as the separator for multiple values in the key.
-23120626 0 Word VBA: How to reference a chart in a tableIn a Word document, I have several tables into which I have placed charts within cells. Now I need to access these charts through VBA, to update data values and other properties. The logic driving the updates to the charts is linked to the table the charts are embedded in, so I need to know something about the table context when accessing the charts.
Originally, I had planned to bookmark the tables, and then iterate through the charts associated with each table. However, I now realise that the Word "Table" object doesn't have a "Shapes", or "Inlineshapes", or "Charts" collection.
So my question is: what is the best way to access/reference charts embedded in a table?
-32042151 0 mapPartitions returns empty arrayI have the following RDD which has 4 partitions:-
val rdd=sc.parallelize(1 to 20,4)
Now I try to call mapPartitions on this:-
scala> rdd.mapPartitions(x=> { println(x.size); x }).collect 5 5 5 5 res98: Array[Int] = Array()
Why does it return empty array? The anonymoys function is simply returning the same iterator it received, then how is it returning empty array? The interesting part is that if I remove println statement, it indeed returns non empty array:-
scala> rdd.mapPartitions(x=> { x }).collect res101: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)
This I don't understand. How come the presence of println (which is simply printing size of iterator) affecting the final outcome of the function?
-12699660 0Use the isArray
method to determine if a value is an array, and you can make it one if it isn't:
var arr = data.results.thing; if (!$.isArray(arr)) { arr = [arr]; }
Now it's always an array, so you can treat it the same way all the time.
-681266 0You can use template arguments to program against 'general' enum types. Much like this:
// enum.h struct MyClass1 { enum e { cE1, cE2, cELast }; }; // algo.h // precondition: tEnum contains enumerate type e template< typename tEnum > typename tEnum::e get_second() { return static_cast<typename tEnum::e>(1); } // myclass1.h // myclass.h template< typename tClass1 > class MyClass2 { tClass1 * ptr; void func( tClass1::e e ); }; // main.cpp #include "enum.h" #include "algo.h" int main(){ return get_second<Enum>(); }
-23758352 0 scope errors functions not declared Hi my problem is the following i want to compile my c project and it doesnt work saying that i some of my functions were not declared in scope, but they are and i dont understand why it doesnt compile
my code:
Header file:
#include<stdio.h> #include<stdlib.h> #include <string.h> #include <time.h> typedef struct s { int id; int tipo_sorte; char descricao[100]; int consequencia; } S; typedef struct sorte{ S s; struct sorte *anterior; struct sorte *proximo; }SORTE; typedef struct t { int id; int n_casa; } T; typedef struct tabuleiro{ T t; struct tabuleiro *anterior; struct tabuleiro *proximo; }TABULEIRO; typedef struct j { int id; char nome[50]; char sigla[5]; int jogadas; } J; typedef struct jogador{ J j; struct jogador *anterior; struct jogador *proximo; }JOGADOR;
main file:
#include "lista.h" int main() { int opcao=0, a = 0; SORTE *inicio = NULL; JOGADOR *ini = NULL; TABULEIRO *tini = NULL; SORTE *fim = NULL; TABULEIRO *tfim = NULL; JOGADOR *end = NULL; printf(" ----------------------------------------------------------------------------\n" "| Monopolio 2014. |\n" "| Bem-Vindo. |\n" " ----------------------------------------------------------------------------\n"); //carregaPerguntas(&inicio, &fim); //carregaJogadores(&ini, &end); // system("PAUSE"); do{ system("cls"); printf(" -----------------------------------------------------------------------------\n"); printf("| 1 - Jogar |\n"); printf("| 2 - Administrador |\n"); printf("| 3 - Recordes TOP 10 |\n"); printf("| 4 - Sair |\n"); printf(" -----------------------------------------------------------------------------\n\n->"); fflush(stdin); scanf("%d",&opcao); switch(opcao) { case 1 : system("cls"); // jogar(inicio,fim, &ini, &end); break; case 2 : system("cls"); a = validaLogin(); if(a==0){ menuAdmin(); } if(a==1){ menuAdmin1(&inicio, &fim); }else{ //menuAdmin2(&inicio, &fim); } break; case 3 : system("cls"); // carregaRecordes(&ini, &end); // listaRecordes(ini); break; case 4 : system("cls"); printf(" -----------------------------------------------------------------------------\n"); printf("| Obrigado por ter jogado. |\n"); printf(" -----------------------------------------------------------------------------\n"); system("PAUSE"); default : if(opcao<1 || opcao>4) { system("cls"); printf("Opcao Invalida.\n"); system("PAUSE"); } break; } }while(opcao!=4); // gravaRecordes(ini); system("cls"); return 0; }
admin file:
#include "lista.h" int validaLogin(){ system("cls"); char pass[20]="", passwd[20]=""; int n_tenta = 3; FILE *fp = fopen("pass.dat","r+b"); if(fp==NULL){ printf("Primeiro Acesso. Por favor defina a password.\n"); fflush(stdin); gets(pass); fclose(fp); fp=fopen("pass.dat","wb"); fwrite(pass,sizeof(pass),1,fp); printf("\n\nPassword definida com sucesso.\n"); system("PAUSE"); fclose(fp); return 0; } do{ fflush(stdin); fread(passwd,sizeof(passwd),1,fp); printf("Introduza a password de acesso ao modo de administracao.\n"); fflush(stdin); gets(pass); if(strcmp(pass,passwd)!=0){ system("cls"); n_tenta--; printf("Password invalida. Restam %d tentativas.\n",n_tenta); if(n_tenta==0){ printf("A sair do modo de administracao.\n"); system("PAUSE"); return -1; } } else{ printf("Password inserida com sucesso.\n"); system("pause"); } }while(strcmp(pass,passwd)!=0); fclose(fp); return 0; } void inserePergunta(SORTE **inicio, SORTE **fim){ SORTE *novo = (SORTE*) malloc(sizeof(SORTE); int gr=0, a=0; if(novo==NULL){ system("cls"); printf("Erro na reserva de memoria.\n"); system("pause"); return; } printf(" -----------------------------------------------------------------------------\n"); printf("| Insira o tipo de consequencia da carta da sorta |\n"); printf(" -----------------------------------------------------------------------------\n"); printf("| 1 - Recuar |\n"); printf("| 2 - Avancar |\n"); printf("| 3 - Saltar |\n"); printf(" -----------------------------------------------------------------------------\n->"); do{ fflush(stdin); scanf("%d",&gr); if(gr<1 || gr>3){ printf("Opcao errada.\nInsira novamente.\n->"); } }while(gr<1 || gr>3); novo->s.tipo_sorte = gr; system("cls"); printf("Insira o tipo da consequencia.\n->"); fflush(stdin); gets(novo->s.descricao); if(gr==1 || gr==2 || gr==3){ printf("Insira o numero de casas.\n->"); fflush(stdin); scanf("%d",&novo->s.consequencia); } if(*inicio==NULL){ novo->s.id=1; } else{ novo->s.id = (*fim)->s.id + 1; } inserirListaP(novo->s, &(*inicio), &(*fim)); printf("ID da casa - %d\n",novo->s.id); system("pause"); } int listaPerguntas(SORTE *inicio){ SORTE *auxi = inicio; char group[50]=""; if(auxi==NULL){ return -1; } while(auxi!=NULL){ if(auxi->s.tipo_sorte==1){ strcpy(group,"Recuar"); } if(auxi->s.tipo_sorte==2){ strcpy(group,"Avancar"); } if(auxi->s.tipo_sorte==3){ strcpy(group,"Saltar"); } printf(" -----------------------------------------------------------------------------\n"); printf("| ID: %d\n",auxi->s.id); printf("| Carta:\t%s\n",auxi->s.descricao); printf("| Tipo Carta: %d (%s)\n",auxi->s.tipo_sorte,group); printf("| Consequencia: %d\n",auxi->s.consequencia); printf(" -----------------------------------------------------------------------------\n\n"); auxi = auxi->proximo; } return 1; } void editaPergunta(SORTE *inicio){ system("cls"); SORTE *aux = inicio; int auxi=0, l=0, a=0; l = listaPerguntas(inicio); if(l==-1){ printf(" -----------------------------------------------------------------------------\n"); printf("| Nao existem cartas inseridas para poder alterar.\n"); printf(" -----------------------------------------------------------------------------\n"); system("pause"); return; } printf(" -----------------------------------------------------------------------------\n"); printf("| Insira o id da carta a alterar.\n"); printf(" -----------------------------------------------------------------------------\n->"); fflush(stdin); scanf("%d",&auxi); while(aux!=NULL){ if(aux->s.id == auxi) { printf("Edite a carta.\n->"); fflush(stdin); gets(aux->s.descricao); printf("Introduza nova consequencia.\n->"); fflush(stdin); scanf("%d",&aux->s.consequencia); } printf(" -----------------------------------------------------------------------------\n"); printf("| Dados editados com sucesso.\n"); printf(" -----------------------------------------------------------------------------\n"); system("pause"); return; } else { aux = aux->proximo; } } printf(" -----------------------------------------------------------------------------\n"); printf("| A carta com o id '%d' nao existe.\n",auxi); printf(" -----------------------------------------------------------------------------\n"); system("pause"); } void eliminaPergunta(SORTE **inicio, SORTE **fim){ SORTE *aux = *inicio; int l=0, i=0; l = listaPerguntas(*inicio); if(l==-1){ printf(" -----------------------------------------------------------------------------\n"); printf("| Nao existem cartas inseridas para poder eliminar.\n"); printf(" -----------------------------------------------------------------------------\n"); system("pause"); return; } printf(" -----------------------------------------------------------------------------\n"); printf("| Insira o id da carta a eliminar.\n->"); printf(" -----------------------------------------------------------------------------\n"); fflush(stdin); scanf("%d",&i); while(aux!=NULL && aux->s.id != i) { aux = aux->proximo; } if(aux==NULL){ printf(" -----------------------------------------------------------------------------\n"); printf("| A carta com o id '%d' nao existe.\n",i); printf(" -----------------------------------------------------------------------------\n"); system("pause"); return; } if(aux->anterior==NULL) { *inicio = aux->proximo; if(*inicio) (*inicio)->anterior = NULL; } else aux->anterior->proximo = aux->proximo; if(aux->proximo==NULL) { *fim = aux->anterior; if(*fim) (*fim)->proximo=NULL; } else aux->proximo->anterior = aux->anterior; free(aux); printf(" -----------------------------------------------------------------------------\n"); printf("| Carta removida.\n"); printf(" -----------------------------------------------------------------------------\n"); system("pause"); } void menuAdmin(){ system("cls"); system("cls"); printf(" -----------------------------------------------------------------------------\n"); printf("| Menu Administracao. |\n"); printf(" -----------------------------------------------------------------------------\n"); printf("| 1 - Gerir Cartas da sorte |\n"); printf("| 2 - Gerir Tabuleiro |\n"); printf("| 0 - Menu anterior |\n"); printf(" -----------------------------------------------------------------------------\n->"); } void menuAdmin1(SORTE **inicio, SORTE **fim){ system("cls"); int op=0; do{ system("cls"); printf(" -----------------------------------------------------------------------------\n"); printf("| Menu Administracao. |\n"); printf(" -----------------------------------------------------------------------------\n"); printf("| 1 - Inserir Pergunta |\n"); printf("| 2 - Editar Pergunta |\n"); printf("| 3 - Eliminar pergunta |\n"); printf("| 0 - Menu anterior |\n"); printf(" -----------------------------------------------------------------------------\n->"); fflush(stdin); scanf("%d",&op); switch(op){ case 1: system("cls"); inserePergunta(&(*inicio), &(*fim)); break; case 2: system("cls"); editaPergunta(*inicio); break; case 3: system("cls"); eliminaPergunta(&(*inicio), &(*fim)); break; default:if(op<0 || op>3){ printf("Opcao errada.\n"); system("PAUSE"); } gravaPerguntas(*inicio); system("PAUSE"); break; } }while(op!=0); }
error log:
C:\Users\JD\Desktop\Prog\main.c In function 'int main()': 42 41 C:\Users\JD\Desktop\Prog\main.c [Error] 'validaLogin' was not declared in this scope 44 38 C:\Users\JD\Desktop\Prog\main.c [Error] 'menuAdmin' was not declared in this scope 49 35 C:\Users\JD\Desktop\Prog\main.c [Error] 'menuAdmin1' was not declared in this scope 28 C:\Users\JD\Desktop\Prog\Makefile.win recipe for target 'main.o' failed
these functions are on admin file i dont understand why this errors please help me
-7814131 0 C++ Command Line: Output program variable valueI am writing a drop-down console for my app. Suppose I want to output the value of variable myvar
by using the following command:
]/get myvar
Is there a better way than to create a map so that the output is
return mymap[argv[0]]; ?
In other words, can I associate the input char array "myvar" to the variable named myvar without doing it manually for all the variables in the program.
-14011536 0Add your message to a text component that can wrap, such as JEditorPane
, then specify the editor pane as the message
to your JOptionPane
. See How to Use Editor Panes and Text Panes and How to Make Dialogs for examples.
Addendum: As an alternative to wrapping, consider a line-oriented-approach in a scroll pane, as shown below.
f.add(new JButton(new AbstractAction("Oh noes!") { @Override public void actionPerformed(ActionEvent action) { try { throw new UnsupportedOperationException("Not supported yet."); } catch (Exception e) { StringBuilder sb = new StringBuilder("Error: "); sb.append(e.getMessage()); sb.append("\n"); for (StackTraceElement ste : e.getStackTrace()) { sb.append(ste.toString()); sb.append("\n"); } JTextArea jta = new JTextArea(sb.toString()); JScrollPane jsp = new JScrollPane(jta){ @Override public Dimension getPreferredSize() { return new Dimension(480, 320); } }; JOptionPane.showMessageDialog( null, jsp, "Error", JOptionPane.ERROR_MESSAGE); } } }));
-12854294 0 Yes, it is possible. If there was problem with HttpPostAttribute
, you would not have been able to get inside LogOn
method. You should re-check that fields are sent from client and those fields are put inside request body, not query string. You could check it with chrome for example, by inspecting network traffic or simply by debugging HttpContext.Current.Request.Form property
Here is an interim solution (non D3) that I've come up with to structure the data the way that the D3 set up wants it. Comments welcome.
var data = [ {}, {}, {}, ... ] // see above var dataSets = ["a","b","c"] var newArr = []; data.map(function(a) { var prop; var _this = this; dataSets.map(function(k) { prop = a.date+"|"+k; if (!_this[prop]) { _this[prop] = { key: k, value: 0, date: a.date }; newArr.push(_this[prop]); } if (prop === a.date+"|"+k) { _this[prop].value += parseInt(a[k]); } }); }, Object.create(null)); console.log("reduced data", newArr);
-30291647 0 WPF - can't see a button in th View design I wrote a simple WPF window that shows a customers grid.
in the bottom of the grid I added a button "Add a new Customer, but it blended into the background of the window, and I can't see it in View design.
this is the code:
<Window x:Class="NihulMlay._1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title=" Customers " Height="120" Width="600"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="300" /> <ColumnDefinition Width="300" /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="40" /> <RowDefinition Height="40" /> </Grid.RowDefinitions> <Button FontWeight="Bold">Customer name</Button> <Button Grid.Column="1" FontWeight="Bold">Name</Button> <Label Grid.Row="1"></Label> <Label Grid.Column="1" Grid.Row="1"></Label> <Button Grid.ColumnSpan="2" Content="Add a new Customer" HorizontalAlignment="Left" Height="100" Margin="270,114,0,-173" Grid.Row="1" VerticalAlignment="Top" Width="75"/> </Grid> </Window>
thanks.
-14356547 0 localStorage doesn't refresh the gridI can't solve this problem.
Here is my code
var selectedID = ""; var selectedIDPremise = ""; var PremisesGrid = ""; var PremisesGrid2 = ""; var selectedIDPremise2 = ""; //var selectedOD2 = ""; var nova = ""; $(document).ready(function () { $("#routes").kendoDropDownList({ dataTextField: "Name", dataValueField: "Id", dataSource: { type: "application/jsonp", transport: { read: { url: "http://" + servername + "/uBillingServices/Administration/Administration.svc/getRoute", dataType: "json", data: { ID: 0 } } } }, select: onSelect }); //nova = PremisesGrid2.getKendoDropDownList().dataSource.transport.options.read.data.Route_ID; function onSelect(e) { //$.getJSON("http://" + servername + "/uBillingServices/Administration/Administration.svc/getRoute", { ID: nova }, function (json) { }); window.localStorage.setItem("Nova", ""); nova = this.dataItem(e.item.index()); window.localStorage.setItem("Nova", nova.ID); PremisesGrid2.getKendoGrid().dataSource.read(); //nova = PremisesGrid2.getKendoDropDownList().dataSource.transport.options.read.data.Route_ID; // var data = [{}]; //PremisesGrid2.getKendoGrid().dataSource.data(data) for (var i = 0; i < 3000; i++) { if (i == 2999) { PremisesGrid2.getKendoGrid().dataSource.read(); } } } PremisesGrid2 = $("#assignedRoute").kendoGrid({ //dataTextField: "Name", //dataValueField: "Id", dataSource: { type: "application/jsonp", transport: { read: { url: "http://" + servername + "/uBillingServices/Premise/Premise.svc/GetAllPremisesByRoute", dataType: "json", data: { Route_ID: window.localStorage.getItem("Nova"), UserName: userName, WorkStation: workStation } } }, schema: { model: { fields: { ID: { type: "string" }, PostalCode: { type: "string" }, Latitude: { type: "string" }, Longitude: { type: "string" }, IsMember: { type: "string" } } } } }, change: function (arg) { myIndex = this.select().index(); var PremisesRow = this.select(); }, dataBound: function (e) { row = e.sender.tbody.find(">tr:not(.k-grouping-row)").eq(0); if (row.length == 0) { e.sender.select(e.sender.tbody.find(">tr:first")); } else { e.sender.select(row); } }, selectable: true, scrollable: true, filterable: true, groupable: false, sortable: { mode: "single", allowUnsort: false }, height: 330, columns: [ { field: "PostalCode", title: "Assigned Route" } ]//, width: "100px" });
the localStorage is working fine(in resources it changes), but it doesn't refresh the grid when I select another Reon (form the DropDown list),and when I refresh the page it shows the last one I selected
Can anyone tell me what is the problem? Thanks
-533616 0Take a look at LinqPad for debugging and to understand how it works. But if you want it at run-time, I think you're out of luck.
-4423092 0You could consider an enum
type. An enum
is a defined list of possible string values, e.g:
create table stuff (status enum ("foo", "bar") not null);
-15182297 0 You just need to remove the padding from the button.
input { padding:0; }
This is caused by the following style applied in the Chrome user agent stylesheet.
input[type="button"], input[type="submit"], input[type="reset"], input[type="file"]::-webkit-file-upload-button, button { padding: 1px 6px; }
-2284291 0 Aaron Hallberg mentioned to me that you can change the MSBuild activity in the workflow to not set an OutDir. This worked, but caused the Binaries folder to not get a copy of the output.
"you [...] need to modify the workflow to not set the OutDir property of the MSBuild activity. I would suggest opening up the xaml in a text/XML editor rather than the WF designer so that you can just search for the string MSBuild."
-161866 0The cause for this error is most likely a missing syntax token that bash expects but the string you pass ends before bash encountered it. Look for ifs, fors etc. that have no closing fi or done.
-35691184 0All you need to do is rewrite HistoricalDataShift to operate on itself. It should work just fine then.
Sub HistoricalDataShift() Dim wb As Workbook Set wb = ThisWorkbook Dim ws As Worksheet For Each ws In wb.Worksheets ws.Activate ' ws.Rows("18:1000").Select Selection.Copy ws.Range("A19").Select ActiveSheet.Paste ws.Rows("15:15").Select Selection.Copy ws.Range("A18").Select ActiveSheet.Paste Next ws End Sub
Also to make your code work better, you can do this:
Sub HistoricalDataShift() Dim wb As Workbook Set wb = ThisWorkbook wb.Activate Dim ws As Worksheet For Each ws In wb.Worksheets Call ws.Rows("18:1000").Copy(ws.Range("A19")) Call ws.Rows("15:15").Copy(ws.Range("A18")) Next ws End Sub
-7789486 0 While the Windows Media Player Com might not officially support a feature like this, its quite easy to 'fake' this. If you use a CtlControls2, you have access to the built-in "step(1)" function, which proceeds exactly one frame.
I've discovered that if you call step(1) after calling pause(), searching on the trackbar will also update the video.
It's not pretty, but it works!
-2037044 0Why not simply use
let l=[1;2;5;3];; Seq.findIndex (fun x -> x= Seq.max l) l ;;
?
Or maybe as Johan Kullbom suggest in a comment:
"let m = Seq.max l in Seq.findIndex (fun x -> x = m) l"
if you what a little better O(n)
However, the need to get the index looks to me like a imperative "code smell" .
In FP it's usually better to use existing functions before you roll your own. I now this in the eyes of a C programmer seems like a for(i (for(j construct but I bet that you probably really don't need to know the index if you start think in FP.
More or less a duplicate of Finding index of element in a list in Haskell?
PS. I can't resist. In Haskell (ghc) the way should probably be something like
let cmpSnd (_, y1) (_, y2) = compare y1 y2 let maxIndex l= fst $ maximumBy cmpSnd $ zip [0..] l
However, since zip in F# doesn't seem to allow zip with unequal lengths of the list(?) the use of mapi is probably the way to go (my haskell version in F#)
let cmpSnd xs= snd xs ;; let zipIndex a= Seq.mapi (fun i x -> i,x) a;; let maxIndex seq=fst (Seq.maxBy cmpSnd (zipIndex seq));;
and the reason is only so that I can make a list
let l= [[0;199;1];[4;4];[0;0;399]]
test with makeIndex l;; and decide that what I really want is a
let cmpSnd' (a,(xs: int list)) = Seq.sum xs;; let maxIndex' seq=fst (Seq.maxBy cmpSnd' (zipIndex seq));;
Now time to decomposite and make makeIndex take a function
let maxIndexF seq maxF=fst (Seq.maxBy maxF (zipIndex seq));; val l : int list list = [[1; 2; 199]; [3; 3]; [4; 1]; [0; 299]] > maxIndexF l cmpSnd' ;; val it : int = 3 > maxIndexF l cmpSnd ;; val it : int = 2
Finish it up
let maxIndexF' maxF=fst << Seq.maxBy maxF << zipIndex ;; maxIndexF' cmpSnd' l;; maxIndexF' cmpSnd l;;
-23703941 0 How to correctly plot machine failures in a scatter plot using dc.js? I am using dc.js to make a simple dashboard. My data is composed of five columns, date
, node
,type
, variable
and value
. It combines resource monitoring data and events. They are defined in the variable column, under categories cpu, hd, int, mem and event. The type column is NA for resources and a certain string detailing the type of event. And the value column corresponds to the number of that certain resource in a certain moment or 1 if that row corresponds to an event.
Having said that, I want to plot a scatter plot with the date on the x axis and the presence or not of an event in the y axis, but I've not yet managed to do it. And I fear it has to do with an incorrect understanding of crossfilter. I'm fairly confident on how to code dimension, I have this:
var eventDim = ndx2.dimension(function(d){ if (d.variable=="event"){ return [d.Date.getTime(),d.type]; } });
But I can't grasp on how to create the group to do what I want and what valueAccessor I have to pass as a parameter to the scatter plot to plot what I want.
Any help would be appreciated.
Thanks in advance.
-25330954 0 Div not expanding to fill the windowI've been trying to find a solution to this for days, but haven't found anything that works. I thought I'd finally make an account on this great website, so here goes:
I am trying to have a div expand from left to right, with 170px of clearance on both sides. However, when there is no content on the page, or only a few words, the div doesn't expand. I've tried to add width: 100% in several different divs to try and have them take up the full space, but that either does nothing, or completely busts the page layout. for example, instead of filling out the page, the div that's supposed to hold the content moves off the right side of the screen, and also doesn't leave the 170px margin.
I hope you can be of help, my code is posted below: Thanks in advance, Chris
the html:
<html> <body> <div id="wrapper"> <div id="pagetopwrap"> </div> <div id="pagemainliquid"> <div id="pagemainwrap"> <div id="content"> <div id="headerwrap"> <div id="header_left"> </div> <div id="header_main"> <div id="logo_row"> <p id="logotext">Site Title</p> </div> <div id="menu_row"> <!-- irrelevant menu button code --> </div> </div> <div id="header_right"> </div> </div> <div id="contentbody"> <div id="contenttext"> <p id="contenttextmakeup">Lorum Ipsum Dolor Sit Amet</p> </div> </div> </div> </div> </div> <div id="leftcolumnwrap"> <div id="leftcolumn"> </div> </div> <div id="rightcolumnwrap"> <div id="rightcolumn"> </div> </div> <div id="footerwrap"> <div id="footer"> </div> </div> </div> </body> </html>
the css: It is not ordered too well, the uninteresting sides, top and footer are first, and the main part of the website at the bottom
body { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 13px; background-color: #0f0f0f; /* is normally an image */ } #wrapper { width: 100%; min-width: 960px; max-width: 1920px; margin: 0 auto; height: 100% } #pagetopwrap { height: 50px; width: 100%; float: left; margin: 0 auto; } #pagemainliquid { float: left; } #pagemainwrap { margin-left: 170px; margin-right: 170px; float: left; } #leftcolumnwrap { width: 170px; margin-left:-100%; float: left; } #leftcolumn { margin: 5px; } #rightcolumnwrap { width: 170px; margin-left: -150px; float: left; } #rightcolumn { margin: 5px; } #footerwrap { width: 100%; float: left; margin: 0 auto; clear: both; bottom:50px; } #footer { height: 0px; margin: 5px; } #headerwrap { width: 100%; margin: 0 auto; } #header_left { background-color: #ff0000; /* is normally an image */ width:25px; height:200px; float:left; } #header_right { background-color: #ff0000; /* is normally an image */ width:25px; height:200px; margin-left: 0px; float:right; position:relative; top:-200px; } #header_main { background-color: #00ff00; /* is normally an image */ margin-left: 25px; margin-right: 25px; height:200px; background-size: 100% 200px; } #contentbody { background-color: #E2E2E2; border-radius: 10px; margin-top:10px; border: 1px solid #A7A7B2; } #contenttext { margin-left:10px; margin-right:10px; } #logo_row { height:150px; width:100%; float:left; } #logotext { margin-top:20px; margin-left:10px; vertical-align: middle; font-size: 55px; font-family: "Arial Black", Arial; } #contenttextmakeup { margin-top:12px; margin-left:10px; vertical-align: middle; } #menu_row { width:100%; } button.menubutton { /* irrelevant button markup */ }
http://jsfiddle.net/w9qLh6tp/ if that helps, I've seen it a lot around here :)
-12250013 0 How to round down a float to the nearest value that can be divided by two without rest?For example I have a float 55.2f and want to round it down such that the result can be divided by two without rest.
So 55.2 would become 54 as that is the nearest smaller "step" that can be divided by two. Is there a function for this or must I write my own algorithm?
-2197313 0 WebBrowser Control blocking ajaxI'm using webbrowser control embeded in a winform in my C# app to do some scraping. The content I'm looking for is dynamically loaded with ajax. However, when I navigate to the page the content won't load unless I have no other code running. I tried doing
while(webbrowser1.isBusy);
But that's not helping. I also tried pausing the program for a few second to give it time to load
Thread.Sleep(2000);
but it's still not loading. If I navigate to the page with no code following, it loads fine. I'm not really sure how I could split this into threads. Any help would be appreciated.
-24549960 0 How to loop through Two arrays in TWO FOR Each loopThere are two FOR EACH loops in the code below. The first FOR loop cycles through the first array (shape 1,shape 2 ,shape 3).The second FOR loop cycles through the second array (0.3, 0.4, 0.5).
Shape 1 0.3
Shape 2 0.4
Shape 3 0.5
The second FOR loop colors the shape on my worksheet based on the value of second array. The problem is all of my shapes are being colored with first value (i.e 0.3). I want Shape 1 to be colored based on 0.3 , Shape 2 based on 0.4 and so on. Thanks for helping me with this.
Private Sub Worksheet_Calculate() Dim arr1 Dim arr2 Set arr1 = Worksheets("Sheet2").Range("valueforarr1") Set arr2 = Worksheets("Sheet2").Range("Valueforarr2") Dim c, d As Range For Each c In arr1 c = Replace(c, " ", "_") MsgBox c For Each d In arr2 If d >= 0.2 And d <= 0.3 Then Worksheets("Sheet1").Shapes(c).Fill.ForeColor.RGB = RGB(237, 247, 249) Exit For ElseIf d > 0.3 And d <= 0.4 Then Worksheets("Sheet1").Shapes(c).Fill.ForeColor.RGB = RGB(218, 238, 243) Exit For ElseIf d > 0.4 And d <= 0.5 Then Worksheets("Sheet1").Shapes(c).Fill.ForeColor.RGB = RGB(183, 222, 232) Exit For ElseIf d > 0.5 Then Worksheets("Sheet1").Shapes(c).Fill.ForeColor.RGB = RGB(146, 205, 220) Exit For ElseIf d Is Nothing Then Worksheets("Sheet1").Shapes(c).Fill.ForeColor.RGB = RGB(255, 255, 255) Exit For End If Next d Next c End Sub
-29885235 0 The while loop is synchronous. You'll need to use an asynchronous loop. You have a couple options for this:
var loop = function(f, callback){ setTimeout(function(){ var count=0; while(f>10){ count++; } callback(count); }, 0); };
or
var loop = function(f, callback){ var count = 0; var si = setInterval(function(){ count++ if(f<=10){ clearInterval(si); callback(count); } }, 1000); };
Using these functions:
loop(frequencyVariable, function(count){ //callback has been called successfully and the loop has ended. //do stuff here });
-29756431 0 jquery parse xml with unlimited child level category I'm fairly new on parsing xml with jquery, so if my question looks like noobish, please forgive me.
I have an xml it contains my recursive categories. Some of them has sub categories, some of them not. It has some deep level categories under sub categories.
Sample of xml;
<Urunler> <Urun> <ID>1</ID> <Parent>0</Parent> <Name>Red</Name> </Urun> <Urun> <ID>2</ID> <Parent>0</Parent> <Name>Green</Name> </Urun> <Urun> <ID>3</ID> <Parent>0</Parent> <Name>Blue</Name> </Urun> <Urun> <ID>4</ID> <Parent>3</Parent> <Name>Sky</Name> </Urun> <Urun> <ID>5</ID> <Parent>3</Parent> <Name>Sea</Name> </Urun> <Urun> <ID>6</ID> <Parent>5</Parent> <Name>Fish</Name> </Urun> <Urun> <ID>7</ID> <Parent>4</Parent> <Name>Bird</Name> </Urun> </Urunler>
Desired HTML output
<ul> <li>Red</li> <li>Green</li> <li>Blue <ul> <li>Sky <ul> <li>Bird</li> </ul> </li> <li>Sea <ul> <li>Fish</li> </ul> </li> </ul> </li> </ul>
I find an example on http://codereview.stackexchange.com/questions/43449/parsing-xml-data-to-be-put-onto-a-site-with-jquery unfortunately it supports only first child level.
if needed; i call my xml via $.ajax
$.ajax({ url: 'webservice/Resim/Kategori.xml', dataType: 'xml', cache:true, success: parseXml });
Any help will greatly appricated.
-37766027 0 What is the best method to define veriables in java?I have a question for you guys today. I've been working with java in a year now, and since java formatting can be done how you want, I'm now seeking the optimal method to define variables :-)
Let's say I want to create a new class with some fields:
public class Email { private String from, to, date, subject, content; public Email(String from, String to, String date, String subject, String content ) { this.from = from; // and so on...
Would that be better than doing it line for line like this?
public class Email { private String from; private String to; private String date; private String subject; private String content;
-10405671 0 UrlEncoding issue for string with ß character I have a parameter which I must pass as part of a url. The parameter contains this character: ß
When I encode this string, I am expecting this: %DF but instead i'm getting: %c3%9f
Here is a line of C# which I have been using to test
string test = HttpUtility.UrlEncode("ß");
-37023876 0 I've made a plunkr for you http://plnkr.co/edit/oMOvCgFzqtnYYPcE2U6j?p=preview
As @toskv suggested binding a string does not work like that. You define the string as a field in your component. And use it with double {{msg}}
tags in your template. Here's the short version:
@Component({ selector: 'app-main', template: `<h1>{{msg}}</h1>` }) export class AppComponent { msg = Welcome.GetWelcome(); }
-16743380 0 string to xmlNode delphi (or how to add an xml fragment to TXMLDocument) I Have a few text strings that contain well formed XML.
I would like to be able to (1) turn these strings into IXMLNodes
then (2) append them to an existing XMLDocument
. Preferably without declaring a new XMLDocument
first.
This doesn't seem possible?
Is there any easy way to accomplish something equivalent though? My initial thought was to use the IXMLNode.XML
(string) property and insert the new strings. No such luck as IXMLNode.XML
is Read Only.
Here is an example, if I had the following strings in a TStringList
,
<Property Name="Version" RttiType="tkString"></Property> <Property Name="ShowSubunit" RttiType="tkBoolean"></Property>
And I had the following XML, already loaded into a TXMLDocument
, how could I easily append the two lines above into the TXMLDocument
below?
<Program Name="PFOO"> <Class Name="CFOO"> <Property Name="DBN" RttiType="tkString"/> <Property Name="SDate" RttiType="tkClass" ClassType="TXSDATE">12/30/1899</Property> <Property Name="XForm" RttiType="tkEnumeration">xfXML</Property> <Property Name="Singleton" RttiType="tkBoolean">True</Property> </Class> </Program>
Any other (simple) ways to achieve this (no protected hack on the XML property please)?
Thank you!
-3736720 0My favorite tool for this kind of thing is HtmlAgilityPack. I use it to parse complex HTML documents into LINQ-queryable collections. It is an extremely useful tool for querying and parsing HTML (which is often not valid XML).
For your problem, the code would look like:
var htmlDoc = HtmlAgilityPack.LoadDocument(stringOfHtml); var images = htmlDoc.DocumentNode.SelectNodes("//img[id=lookforthis]"); if(images != null) { foreach (HtmlNode node in images) { node.Attributes.Append("alt", "added an alt to lookforthis images."); } } htmlDoc.Save('output.html');
-6153983 0 I'm not sure you can... one possible workaround (feels a bit hackish though) is to attach the style to your body tag, then change the css to be this:
body.standard_label_style label{ //Your styles here }
-11413096 0 show login form using ajax after session expiration in grails I had a list of users displayed in a table whose session expires after 20min, but after expiration it doesn't go to login page without refreshing and I want to show a pop-up to display a login form which after login will keep me to the same url. I'm working on grails; can anyone help with it?
-3648888 0Try this (note also that recent CMake means you don't need to USE_CAPS_ALL_THE_TIME):
get_target_property(FLAGS ${MyTarget} COMPILE_FLAGS) set_target_properties(${MyTarget} PROPERTIES COMPILE_FLAGS "${FLAGS} /FI\"${ForcedHeader_A}\"/FI\"${ForcedHeader_B}\"")
-38218234 0 Selected all Items in Custom product grid I have created a custom product grid in magento backend .I have used filters and csv export there and they working fine. but when i apply massaction to select all items it only select visible items.
it there any way to select all items of the grid even those are not visible.
Argh, Apple tends to change things without letting anyone know. The whole settings bundle thing is just not well integrated into XCode if you ask me. If you ever try to localize your application, you will find that you have to manually add the localization folders to the settings.bundle.
Looks like we have to do the same thing to add child menus now, as just adding the plist file does not put it into the settings.bundle.
Here is the set of steps I just tried that worked.
Possible solutions:
As far as I can see in the documentation, the define
method of Parse.Cloud
object requires a function which should take two parameters. Your function push_httpRequest
then is not correctly defined. From Parse documentation:
-37795417 0 Check/Uncheck radio on filling textbox
define( name, func )
Defines a Cloud Function.
Available in Cloud Code only. Parameters:
- name
<String>
The name of the Cloud Function- func
<Function>
The Cloud Function to register. This function should take two parameters aParse.Cloud.FunctionRequest
andParse.Cloud.FunctionResponse
I've got this little piece of code here I've been working on for a while, and for some reason it doesn't work. Can somebody have a look at it and tell me whats wrong with it?
All I need it to do is to check the "Other amount" radio box when someone enters an amount in the textbox. I'd also like to clear the amount written when any other radios are checked. Cross browser is a must.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Donation amount</title> <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> <script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script> <script type="text/javascript"> $("#donationAmountMan").on("input propertychange change paste keyup", function() { if ($("#donationAmountMan").val().length > 0) { $("#da_man").prop("checked", true); } else { $("#da_man").prop("checked", false); } }); </script> </head> <body> <label>Donation amount</label> <div> <label><input type='radio' name='donationAmount' id='da25' value='25' required /> $25</label> <label><input type='radio' name='donationAmount' id='da50' value='50' required /> $50</label> <label><input type='radio' name='donationAmount' id='da100' value='100' required /> $100</label> <label><input type='radio' name='donationAmount' id='da150' value='150' required /> $150</label> <label><input type='radio' name='donationAmount' id='da_man' value='0' required /> Other amount <input type='text' name='donationAmountMan' id='donationAmountMan'>$</label> </div> </body> </html>
Thank you all for your precious help!
-29361351 0Coded UI uses accessibility to expose properties and methods to the test runner. This means that unless specific properties and methods have been exposed they are simply not available to Coded UI.
In your situation Coded UI could be used, but I don't think it should be used unless you have a lot of time on your hands.
You would essentially need to replace MSAA, with a custom technology and then expose the custom properties and methods using that technology.
Huge amount of development effort to get what you already have with QTP.
-20739057 0 How to Display ListData() in CDetailView in YiiSuppose I have a code of CDetailView as shown in below
$this->widget('zii.widgets.CDetailView', array( 'data'=>$model, 'attributes'=>array( 'title', 'owner.name', 'description:html', array( 'label'=>'City', 'type'=>'raw', 'value'=>'', // ??? How to insert here ListData function that it will display list of different cities ), ), ));
Now in above code I want to insert the list of cities which is coming in list Data array.
$list = CHtml::listData($model->city, "city_id", "cities");
If i keep $list
in print_r()
. It gives out as in below.
Array ( [1] => London [2] => Paris [3] => New York )
Any Help Will be appreciated.
Thanks.
-13589867 0 Apply a tuple of functions to a value and return a tupleRight now, I have the following to apply two functions to a value and return a 2-value tuple:
template<typename F1, typename F2> class Apply2 { public: using return_type = std::tuple<typename F1::return_type, typename F2::return_type>; Apply2(const F1& f1, const F2& f2) : f1_(f1), f2_(f2) {} template<typename T> return_type operator()(const T& t) const { return std::make_tuple(f1_(t), f2_(t)); } protected: const F1& f1_; const F2& f2_; };
I wanted to generalize this to N functions:
template<typename ...F> class ApplyN { public: using return_type = std::tuple<typename F::return_type...>; ApplyN(const std::tuple<F...>& fs) : functions_(fs) {} template<typename T> return_type operator()(const T& t) const { return ???; } protected: std::tuple<F...> functions_; };
I know I probably need to use template recursion somehow, but I can't wrap my head around it. Any ideas?
-34533282 0 Cannot Alter Table Constraint on Mysqlanyone knows, i tried so many times to use alter table constraint in my mysql sql.
So i want to alter table constraint to add validation in gender column :
alter table jewerly add constraint checkGender CHECK(Gender='Male' OR Gender='female');
is that right ? i dont know what is the problem but it always return empty result on my mysql. why ?
i read from another thread, it said that is normal if return empty result.
but i try to export my sql and i see no contraint query added on my sql.
anyone knows the problem ?
======
Note : it marked as duplicate question, but the last thread only has sollution for checking gender constraint, how about if i want to add another constraint ? the constraint always missing after we add it.
-1857611 0This is really complicated. I understand that you can edit your spreadsheets with Python using their API, Google tends to offer that ability on many of their web services and it's all done by sending HTTP post requests made of XML somehow, I hope you know that part, I don't.
According to this you can at least add worksheets, read rows from other worksheets and write rows to worksheets. if you must, you could copy it one row at a time, however sending an additional POST request for each row seems like a horrible idea.
Edit:
I'm learning more and more about this, but still a long way off from solving your original problem. This overview of REST principles goes over the basic style of interaction that goes on between programs on the web. Google seems to be following it religiously.
It all takes place within the HTTP protocol, something I knew nothing about before today. In this HTTP specification the basic game is spelled out. Its not as dry as it looks, and maybe I'm just a huge geek, but I find it an inspiring read. Not unlike The Constitution of The United States.
So since you want to "clone" a document, your going to be using a GET request for a particular worksheet, and then sending that worksheet back as the payload of POST.
Getting closer :)
-7606590 0Please see the second answer on Possible to do In-App Purchasing using Adobe Air SDK which might help.
In short. With AIR 3 It is now possible to achieve all the functionalists you noted above.
For how To see: http://www.adobe.com/devnet/air/articles/extending-air.html
For readymade sample for In-App Purchases through AIR on iOS see: http://code.google.com/p/in-app-purchase-air-ios/
-1073380 0I imagine that using the appropriate LIMIT
clause in your SELECT
statement is more efficient (it will definitely save lookup time atleast), but I don't know how the internals of how mysql_data_seek
works, specifically if it reads x
records and discards them, or whether it works like filesystem seek
commands do (sends a signal to MySQL telling it to skip sending the next x
records).
If it works the first way, I'd expect a minimal speedup doing it this way. If it was the later way, I'd expect a speedup, but not as much as simply using the appropriate LIMIT
clause.
I see one problem here. The line:
execlp ("./dummy", "dummy", NULL); /* replace myself with a new program */
was very important in your original program. If it is commented out, the child will continue the loop and spawning it's own sub-childs in the loop. So you will create (n*(n-1))/2 processes which then exits or are killed in a an unpredictable way.
Also your timing is very tight. Try to use delays in order of tens of seconds, so that you can manually watch what happens in your system.
Otherwise the program seems OK for me.
Concerning order of execution once the new process is created it competes for CPU in the same way as its parent process. So it is basically unpredictable which one will run first and for how long. If there are several cores in your CPU, they can actually run in the same time.
-23586717 0I would suggest a console.log() before the if().
var url = "link"; $.getJSON(url,function(json) { console.log("Success received...") if ( json.length == 0 ) { console.log("NO DATA!") } });
The full reference is here: http://api.jquery.com/jQuery.getJSON/
And you could also use the .done() capability:
$.getJSON(url) .done(function(json) { console.log("Success received...") if ( json.length == 0 ) { console.log("NO DATA!") } });
It could be that somehow you json object is not empty.
-39237502 0git fetch /wp-contents/themes master git merge -s ours --no-commit FETCH_HEAD git read-tree --prefix=wp-contents/themes -u FETCH_HEAD git commit -m "message"
Actually i propose to merge directories manually and commit the changes.
-18713929 1 Subsample pandas dataframeI have a DataFrame loaded from a tsv file. I wanted to generate some exploratory plots. The problem is that the data set is large (~1 million rows), so it there are too many points on the plot to see a trend. Plus, it is taking a while to plot.
I wanted to sub-sample 10000 randomly distributed rows. Also, this should be reproducible, so the same sequence of random numbers is generated in each run.
Thanks for help.
This: Sample two pandas dataframes the same way seems to be on the right track, but I cannot guarantee the subsample size.
-16435836 0For anyone experiencing a similar problem, this is how I was able to solve this.
I first created the implementation and header files for a UIButton subclass with the NSIndexPath property. I assigned the uibutton in the Storyboard the superclass of this new custom unbutton with the NSIndexPath property. I added the following code to the segue identification step (the key was realizing i could use the sender object as the source of triggering the segue):
else if ([[segue identifier] isEqualToString:@"Add"]) { SearchAddRecordViewController *addRecordViewController = [segue destinationViewController]; addRecordButton *button = (addRecordButton*) sender; NSIndexPath *path = button.indexPath; SearchCell *cell = [self.tableView cellForRowAtIndexPath:path]; addRecordViewController.workingRecord = cell.record; }
-14931062 0 I don't think there is a straightforward way to do this in general. You could probably use an inline
operator with a mix of static member constraints to cover some of the cases that you want, but I don't think it will be very elegant.
For some operator names, you can however define a separate prefix and infix version, which covers the first two cases:
// Prefix version of the operator (when you write e.g. '+. 10') let (~+.) a = a * 10 // Infix version of the operator (when you write e.g. '1 +. 10') let (+.) a b = a + b // Sample use +. 10 10 +. 20
You still won't be able to write 10 +. 20 30 40
, because then you'd need an overloaded infix operator.
It is worth noting that you cannot do this for all operator names. Here is a syntax definition from the F# specification of the allowed operator names for infix operators:
infix-or-prefix-op :=
+, -, +., -., %, &, &&prefix-op :=
infix-or-prefix-op
~ ~~ ~~~ (and any repetitions of ~)
!OP (except !=)
PS: I'm not generally a big fan of custom operators - in some cases, they are nice, but they are difficult to discover (you do not see them in the IntelliSense) and unless you're using standard ones for numerical computing, it is often difficult to understand what they mean. So I would maybe consider other approaches...
-25241450 0 Setting CSS for Google Charts with generated div idsI have a page that projects a series of charts with ids generated with Mako
template language in Python
.
The chart div
s are defined like in below.
% for step_id in step_ids: ... <div id="step_chart_div${step_id}" style='width: 900px; height: 500px;'></div> ... % endfor
I want to separate the style part from HTML
, so I assigned a class name for the div, and put the style
in a separate .css
file like
.step_charts{ /* style.css */ width: 900px; height: 500px; } % for step_id in step_ids: ... <div class="step_charts" id="step_chart_div${step_id}"></div> ... % endfor
, but it shortens the height of the chart.
At least it allocates the height of 500px for the div
, without style
it is even shorter, but the size of the chart is short like that without style
.
How can I fix it? Thank you.
-22222489 0 Get number of facebook shares/likes for a url from a specific date to a specific dateI am making a campaign in which i specify that i need a number of likes for this week . for eg 500 likes from 3/3/2014 to 3/9/2014 . So i want to get likes/shares done for that url in my website between that date . I know how to get total number of likes/shares and i use the following code for that.
https://graph.facebook.com/fql?q=SELECT url, normalized_url, share_count, like_count, comment_count, total_count,commentsbox_count, comments_fbid, click_count FROM link_stat WHERE url='http://www.example.com'
But how to get it from a specific date to a specific date ?
-11725026 0 How to divide up a complex workflow into a template of Sub Tasks?Our company is moving over to Jira for all project management and issue resolution
We have a few major uses that i am trying to build templates for. One being a typical issue found and fixed and can easily be handled with a single issue with basically the included jira workflow.
A more complex one is following a Waterfall workflow where Requirements are gathered including an estimate. Then Development kicks off, and in parallel test scripts are made. After Development is done the project is tested and handed off to the client. And finally once all is tested we release the change and re-test. In total I have 30 different steps built across 5 Sub-Tasks (However this is all just mapped out in Visio and not actually in jira yet).
The splitting across Sub-Tasks I hope can accomplish 2 things. First is that we want to track open-close times and efforts (hours works and days needed). And we should have the workflow split to multiple people so the Developer can work while a Tester can build their testing plan. That is able to save a few days, however is not a deal breaker.
So a few questions that I hope can help make this possible, although I am quite new to the various add-ons for Jira, I have no idea if we will get everything we want.
1, Is there an add-on that builds templates of Sub-Tasks, since each Sub-Task needs its own workflow. Currently the rules for Jira is to assign a workflow based on Project+Issue Type. So I believe I can have the proper piece of the workflow assigned to each Sub-Task by creating many Issue Types, like "Custom-Dev-Analsys" for the Sub-Task called Analysis
2, Is it possible to have only 1 or a few of all Sub-Tasks being the "current" one? When the issue starts the first Sub-Task should be the only one worked on, with only 1 of the steps being assigned to someone. After sign-off there should be 2 Sub-Tasks, the Development one and building Test Scripts. But all 5 sub-tasks should not be started since the very beginning, but it seems thats what Jira will do. I have looked at the add-on "Structure" and while that has unlimited hierarchy, I do not think it will let the sub-tasks open up in order. There might be a simple way to make the workflow open the next task (I am very new to workflows and trying to learn as much as possible before messing with our site)
3, If anyone can think of some way to do what I need differently, I am all ears.
Thanks!
-1672773 0At first glance it may seem as if there should be no reason that one should not be allowed to do this, but however think about it from the perspective of code that must call this(these) method(s), how would it know which method to invoke?
From java.sun.com
-10362578 0The Java programming language supports overloading methods, and Java can distinguish between methods with different method signatures. This means that methods within a class can have the same name if they have different parameter lists (there are some qualifications to this that will be discussed in the lesson titled "Interfaces and Inheritance").
Overloaded methods are differentiated by the number and the type of the arguments passed into the method.
You cannot declare more than one method with the same name and the same number and type of arguments, because the compiler cannot tell them apart.
The compiler does not consider return type when differentiating methods, so you cannot declare two methods with the same signature even if they have a different return type.
Yes, the simplest way to do this is to use a server that keeps track of the states of the logged in users. Your question is not Android specific, and you could e.g. use a general Java based solution modified to fit your needs. Here is a simple example/tutorial.
-14367116 0The problem was resolved (sort of). The issue was that the page required a non-basic authentication on a separate web page. I bypassed it by editing code on the server, but could not solve the problem from within powershell
-31041821 0list has no entySet() method!
Try this:
final Iterator<Map<String, String>> it = list.iterator(); while (it.hasNext()) { Map<String, String> mapElement = it.next(); // do what you want with the mapElement }
Of course, you will need another loop to iterate over the elements in the map.
-12823794 0 Access network share from Store appStreamReader and HttpClient can't access network share path. Is it possible to access a file on LAN network from Windows Store app?
-19482386 0 Highlighting a single item in a list menu with many itemsI have a navigation menu and I'm trying to do two things. When I hover 1 list item I'm trying to get that single item to be highlighted, if I click on a single item, I'm trying to make a certain color or style to be applied indicating that this item is currently in focus or active. If I select another, the current item deactivates and the newly selected item becomes active.
This is the CSS I tried but right now all items are being highlighted as soon as I hover any list item, instead of just one:
#listContainer{ margin-top:15px; } #expList ul, li { list-style: none; margin:0; padding:0; cursor: pointer; } #expList p { margin:0; display:block; } #expList p:hover { background-color:#121212; } #expList li { line-height:140%; text-indent:0px; background-position: 1px 555555px; padding-left: 20px; background-repeat: no-repeat; margin-bottom: 5px; } #expList ul{ margin-top: 5px; } #expList li:hover{ background-color: #eee; This is where the problem is } /* Collapsed state for list element */ #expList .collapsed { background-image: url('https://hosted.compulite.ca/kc/MD/SiteAssets/collapsed.png'); } /* Expanded state for list element /* NOTE: This class must be located UNDER the collapsed one */ #expList .expanded { background-image: url('https://hosted.compulite.ca/kc/MD/SiteAssets/expanded.png'); }
Here's a JSFiddle with most of the code http://jsfiddle.net/aHSmy/1/
-8740865 0The problem is that num is not initializated, int num = -1; And the error will go away ;)
-12507646 0Your "error:function(msg)" callback function isn't using the right arguments.
I would suggest:
error: function(jqXHR, textStatus, errorThrown) { console.log(jqXHR, textStatus, errorThrown); //Check with Chrome or FF to see all these objects and decide what you want to display alert('Error! '+textStatus); }
http://api.jquery.com/jQuery.ajax/
Also, check your PHP error logs to see if it does what you intend it to do.
-26018088 0You can use
filters.reject { |k, v| v.empty? }.length # => 2
-28482060 0 Vlad's tip above gave me my correct direction, the XML Report Processing was a dead end regarding my question/search.
My conclusion: Since I am only interested in the Fitnessetest, i.e. JUnit test results, I try to avoid going for the full site documentation, but have probably not tuned everything ideally. But here it goes:
In my TeamCity buildstep Maven I made sure: - Maven Parameters are now "clean site surefire-report:report" - Artifact Paths is now: "target\site\surefire-report.html"
In Project Settings, Report Tabs, I added a new Build Report Tab: - Tab Title "FitnesseTest", Start Page: "surefire-report.html" (this file may be seen in the build artifact link after a successful build.)
I also made sure my pom.xml file was up to date regarding the reporting section. I.e. Reporting Plugins included up to date plugins: - maven-surefire-plugin - maven-surefire-report-plugin - maven-site-plugin - maven-jxr-plugin (not sure if I needed this one)
When I run this build, I get both listing of all tests under the Test tab, but also the html page with the JUnit Testresults under the new "FitnesseTest" tab.
Now I am only missing the Fitnesse formattet output...
-16208603 0Basically you need to select the nodes you want to remove and .remove() them. Assume mycontent
is a jQuery reference to the node with class item-options
:
var warranty = mycontent.children('#warranty'); var txtContent = warranty.siblings('dd').last(); warranty.remove(); txtContent.remove();
If mycontent
is a DOM
node then just select it with jQuery
:
var $mycontent = $(mycontent);
A suggestion would be to structure your DOM
such that the warranty
element holds nodes related to it as children
not as siblings
. Otherwise the semantics is lost.
I'm having issues with my CSS. There's a gap under my icons in Firefox, but not in Chrome. I'm really confused about where the issue is coming from.
Screenshot of Firefox footer: http://puu.sh/dqkrp/1ca27fd502.png
Screenshot of Chrome footer: http://puu.sh/dqkOw/ea7749b56c.png
<footer> <div id="contact-bar"> ... </div> </footer> #contact-bar { width:100%; height:auto; float:right; margin-bottom: auto; bottom: 0px; background-color: #000000; } #contact-bar ul { margin:auto; display: inline-block; list-style-type: none; padding: auto; float:right; } #contact-bar ul li{ float:right; } #contact-bar ul li a { text-decoration: none; } footer { position: fixed; z-index: 9999; clear:both; bottom:0; left:0; width:100%; margin:0px; padding:0px; }
-15990747 0 a.find('#modal-form-tag form')
?
If the gaps are being created by whitespace you can use the built in String method strip()
If its is a database artifact you may have to give us more information.
-6629680 0 How to attach a xml file to a SMS/MMS message using the Android APII have a custom file type (MIME_TYPE), basically xml, that I'd like to enable users to send to each other. Implementing the email send feature with the xml file as an attachment was straight forward but I'm kinda stuck on the SMS/MMS send feature. Anyone have any guidance?
final Intent intent = new Intent(Intent.ACTION_SEND, Uri.parse("mms://")); intent.setType("text/plain"); intent.putExtra("address", "2125551212"); String url = "content://myFile.txt"; intent.putExtra(Intent.EXTRA_STREAM, Uri.parse(url)); intent.putExtra("sms_body", "some text goes here"); startActivityForResult(Intent.createChooser(intent, "mms-sms:"), SENT_TEXT);
the intent.putExtra(Intent.EXTRA_STREAM... doesn't seem to work, I get an error message: "UNABLE TO ATTACH. FILE NOT SUPPORTED"
-20401142 0Do you really need to hide it for ALL other browsers? you should generaly use feature detection and allow any browser with the capabilities to play the video.
<video width="320" height="240" controls> <source src="movie.mp4" type="video/mp4"> Your browser does not support the video tag. </video>
http://www.w3schools.com/html/html5_video.asp
-5609354 0Nevermind, I figured it out. It was very simple, I just needed to delete the same value from the array that I was deleting from the database - it was always working on the same object so that variable never changed and each subsequent call once again saw previously deleted messages as valid messages.
-32427048 0Try adding Flags to your rules :
RewriteRule ^jokes-([^/]+)/([a-zA-Z0-9-]*)/?$ jokes.php?c=$1&id=$2 [QSA,NC,L] RewriteRule ^jokes-([a-zA-Z_]+)/?$ jokes.php?c=$1 [QSA,NC,L] RewriteRule ^jokes/?$ jokes.php [NC,L]
-31940390 0 function myFunction(response) { var arr = JSON.parse(response); var Profile = arr.value[0].PROFILE; var jsonProfile = JSON.parse(Profile); var out = "<table>"; for(var i=0;i<jsonProfile.Shortcuts.length;i++) { out += "<tr><td>" + jsonProfile.Shortcuts[i].EnvId + "</td></tr>"; } out += "</table>"; document.getElementById("id01").innerHTML = out; }
After going thru your answers, I was finally able to modify my code and it works fine now.
-10097525 0I too have the same issue. I have a SSH
share via MacFusion
and OSXfusion
that has the same issues with very long file saves.
Maybe be a better place is here...
hope this helps!
-116941 0Backgrounding a process is a shell function, not an OS function.
If you want an app to start in the background, the typical trick is to write a shell script to launch it that launches it in the background.
#! /bin/sh /path/to/myGuiApplication &
-12527400 0 Suggested by remi, I implemented the same matrix multiplication using Eige. Here it is:
const int descrSize = 128; MatrixXi a(nframes, descrSize); MatrixXi b(vocabulary_size, descrSize); MatrixXi ab(nframes, vocabulary_size); unsigned char* dataPtr = DATAdescr; for (int i=0; i<nframes; ++i) { for (int j=0; j<descrSize; ++j) { a(i,j)=(int)*dataPtr++; } } unsigned char* vocPtr = vocabulary; for (int i=0; i<vocabulary_size; ++i) { for (int j=0; j<descrSize; ++j) { b(i,j)=(int)*vocPtr ++; } } ab = a*b.transpose(); a.cwiseProduct(a); b.cwiseProduct(b); MatrixXi aa = a.rowwise().sum(); MatrixXi bb = b.rowwise().sum(); MatrixXi d = (aa.replicate(1,vocabulary_size) + bb.transpose().replicate(nframes,1) - 2*ab).cwiseAbs2();
The key line is the line that says
ab = a*b.transpose();
vocabulary an DATAdescr are arrays of unsigned char. DATAdescr is 2782x128 and vocabulary is 4000x128. I saw at implementation that I can use Map, but I failed at first to use it. The initial loops for assigment are 0.001 cost, so this is not a bottleneck. The whole process is about 1.23 s
The same implementation in matlab (0.05s.) is:
aa=sum(a.*a,2); bb=sum(b.*b,2); ab=a*b'; d = sqrt(abs(repmat(aa,[1 size(bb,1)]) + repmat(bb',[size(aa,1) 1]) - 2*ab));
Thanks remi in advance for you help.
-10253582 0 Ruby on Rails get key by value from two dimensional arrayI have a two dimensional array that looks like this:
TITLETYPE = [['Prof.', '4'], ['Dr.', '3'], ['Mrs.', '2'], ['Ms.', '1'], ['Mr.', '0']]
I need to get the key for value 1 for example (which should be 'Ms.') How should I go about doing that?
-12581309 0 hosting tomcat on mac osI'm using mini mac and tomcat 7.0.29, I want to host it from my computer so other computer outside the network could connect to it. I have set the port forwarding into 80 both start and end. set static IP on my mini mac. however, after getting the router IP address from ip2location.com and access to it from external computer,it display "it works!" screen, not the tomcat home page. this page is also displayed when I use localhost instead localhost:8080. Here is some snap shot that I've taken from both computer http://i182.photobucket.com/albums/x38/DNK90/staticIP.jpg
http://i182.photobucket.com/albums/x38/DNK90/portforwarding.jpg
And this one is from external computer
i182.photobucket.com/albums/x38/DNK90/tomcat.jpg
anybody who know how to access directly to the localhost:8080 through router IP, tell me ^^
-27697184 0 Get http-response header with Perl's File::FetchI want to download a file in a Perl script.
If the download is OK, this works fine,
use File::Fetch; $ff = File::Fetch->new(uri => 'http://some.where.com/dir/a.txt'); $where = $ff->fetch() or die $ff->error;
If there is an error, I want to see the http-response header. How can I do this?
-2815064 0It is not recommended to add controls like this. What you ideally do in WPF is to put a ListBox(or ItemsControl) and bind your Business object collection as the itemsControl.ItemsSource property. Now define DataTemplate in XAML for your DataObject type and you are good to go, That is the magic of WPF.
People come from a winforms background tend to do the way you described and which is not the right way in WPF.
-7035164 0<?php echo sprintf("Your price %.2f", $sum); ?>
-15099488 0 As written in the answer, you'll need to provide hard links for bots.
Just treat it like a user without JavaScript. You should support users with no JavaScript. Feel free to implement the <noscript>
tag.
You use getattr:
getattr(object, var)
Anyways, just an additional comment that you are not referencing object variables, you are referencing instance variables. If you want an instance variable, you need to do something like this:
# Note: object is reserved, it's the built-in base class for new-style classes class MyObject: def __init__(self): self.name = 'name' myobj = MyObject() getattr(myobj, 'name')
But getattr doesn't care - classes or instances, they are both Python objects, it works the same way.
-39610464 0 Settng the schema of a Hibernate entity extra to the default schema configurationI have a Hibernate / Spring 4 application, where the default schema of the entity classes is already configured, e.g. they end up mapped as testschema.table
or prodschema.table
.
However there is another entity class which needs its own configurable schema, e.g. only this entity must be mapped to testschema2.anothertable
or prodschema2.anothertable
.
Nice would be something like this:
@Entity @Table(name="anothertable", schema = "${db.AntherEntitySchema}") public class AnotherEntity { // .. }
where the schema gets injected from the properties file, but such a feature seems only to work with the @Value
annotation. Any idea how to proceed?
From Activity you send data with intent as:
Intent recipientsIntent = new Intent(this, RecipientsActivity.class); recipientsIntent.setData(mMediaUri); String fileType; if (requestCode == TAKE_PHOTO_REQUEST) { fileType = ParseConstants.TYPE_IMAGE; } else { fileType = ParseConstants.TYPE_VIDEO; } recipientsIntent.putExtra(ParseConstants.KEY_FILE_TYPE, fileType); // set Fragmentclass Arguments Fragmentclass fragobj = new Fragmentclass(); fragobj.setArguments(recipientsIntent );
and in Fragment onCreateView method:
public class Fragmentclass extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { String mFileType = getArguments().getString(ParseConstants.KEY_FILE_TYPE); } }
-19530832 0 Most names are case-sensitive. It should work if you use lexer_filetype=CSS
. Also, I'm not positive, but you might want to name the file as filetypes.SASS.conf
even it's not required (not sure), it's somewhat of a convention for custom filetypes.
Sadly, if you want to find the available lexer filetypes, you'll have to read the source.
-18880964 0The problem is that your $HTMLtargets
and $SVGtargets
variables are not what you want them to be inside your event handler callback because when the event fires (sometime later), your outer for
loop has already finished and thus those two variables are on their ending value.
You will need a closure to capture those variables separately for each event handler. Here's one way to do that:
// create closure to freeze the target variables (function(hTargets, sTargets) { for(var i = 0; i < $allTargets.length; i++) { $allTargets.get(i).addEventListener('mouseover', function(e) { hTargets.css('color', '#990000'); sTargets.attr('fill', '#990000'); }, false); } })($HTMLtargets, $SVGtargets);
FYI, I changed the name of the variables inside the closure to make it more obvious what was happening. It is not required to change the name of the arguments to the immediately executing function expression as they will just override the previously defined ones, but I think it's clearer what is happening if you change the names.
-31492440 0 Parsing this kind of dataI have written a wrapper for an API. Previously I'd worked on simple string-based GET requests to PHP scripts using Perl.
As part of analysing the response, I have to analyse the following data which appears to be an object. Unfortunately, I'm not sure how to extract usable data from this.
print Dumper
on the data returns this:
$VAR1 = bless( { '_rc' => '200', '_request' => bless( { '_uri_canonical' => bless( do{\(my $o = 'http://example.com/?list=1&token=h_DQ-3lru6uy_Zy0w-KXGbPm_b9llY3LAAAAALSF1roAAAAANxAtg49JqlUAAAAA')}, 'URI::http' ), '_content' => '', '_uri' => $VAR1->{'_request'}{'_uri_canonical'}, '_method' => 'GET', '_headers' => bless( { 'accept-charset' => 'iso-8859-1,*,utf-8', 'accept' => 'image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, image/png, */*', 'cookie' => 'GUID=cHoW3DLOljP4K9LzposM', 'user-agent' => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7) Gecko/20041107 Firefox/1.0', 'authorization' => 'Basic YWRtaW46bmljb2xl', 'cookie2' => '$Version="1"', '::std_case' => { 'cookie' => 'Cookie', 'cookie2' => 'Cookie2' }, 'accept-language' => 'en-US' }, 'HTTP::Headers' ) }, 'HTTP::Request' ), '_headers' => bless( { 'client-peer' => 'myip:8085', 'content-type' => 'text/plain', 'cache-control' => 'no-cache', 'connection' => 'keep-alive', 'client-date' => 'Sat, 18 Jul 2015 12:41:00 GMT', '::std_case' => { 'client-response-num' => 'Client-Response-Num', 'set-cookie2' => 'Set-Cookie2', 'client-date' => 'Client-Date', 'client-peer' => 'Client-Peer', 'set-cookie' => 'Set-Cookie' }, 'client-response-num' => 1, 'content-length' => '8684' }, 'HTTP::Headers' ), '_msg' => 'OK', '_protocol' => 'HTTP/1.1', '_content' => '{"build":30470,"torrents": [ ["043CC5FA0C741CDAD9D2E5CC20DF64A4A400FA34",136,"Epi.S01E03.720p.HDTV.x264-IMMERSE[rarbg]",690765843,39,26951680,671744,24,0,0,0,"",0,1454,0,114,2436,1,663814163,"","","Stopped","512840d7",1437022635,0,"","/mydir/Epi.S01E03.720p.HDTV.x264-IMMERSE[rarbg]",0,"0368737A",false], ["097AA60280AE3E4BA8741192CB015EE06BD9F992",200,"Epi.S01E04.HDTV.x264-KILLERS[ettv]",221928759,1000,221928759,8890308649,40059,0,0,0,"",0,1461,0,4395,65536,-1,0,"","","Queued Seed","512840d8",1437022635,1437023190,"","/mydir/Epi.S01E04.HDTV.x264-KILLERS[ettv]",0,"8F52310A",false]], "label": [],"torrentc": "350372445" ,"rssfeeds": [] ,"rssfilters": [] } ', '_msg' => 'OK', '_protocol' => 'HTTP/1.1' }, 'HTTP::Response' );
I would like to extract each of the following strings from the returned object
097AA60280AE3E4BA8741192CB015EE06BD9F992 200 Epi.S01E04.HDTV.x264-KILLERS[ettv]
Unfortunately, my understanding of objects in Perl is very elementary.
The original code which returns this data looks like this:
my $ua = LWP::UserAgent->new(); my $response = $ua->get( $url, @ns_headers ); print Dumper($response);
How can I work on the strings that of interest?
-25919487 0 Jquery ajax call throws empty JS exception?This function works on one page but not another. I've added all sorts of logging to try to find the error, but cannot. The output of this code on the broken page is:
[13:59:56.427] "here" [13:59:56.428] "beforesend: /admin/test.html?server=eferbelly&port=24466&username=akilandy&password=vkjvkc9776A" [13:59:56.428] "fileName=undefined" [13:59:56.428] "lineNumber=undefined" [13:59:56.428] "columnNumber=undefined" [13:59:56.428] "here6"
That tells me it's getting into the exception handler, completely skipping my ajax() call, but it's not telling me the exception.
function test(server, port, username, password, spanId) { spanId = "#" + spanId; $(spanId).html("<img src='/images/ajax-small.gif'/>"); console.log("here"); try { $.ajax({ dataType: "json", type: "GET", url: "/admin/test.html?server=" + server + "&port=" + port + "&username=" + username + "&password=" + password, success: function(json){ console.log("here2"); if (json.httpStatus == "200") { // Change the image to show success $(spanId).html("<img src='/images/accept.png' title='success'/>"); } else { console.log("here7"); // Change the image to show failure $(spanId).html("<span style='color:#b22222;'>" + json.httpStatus +"</span> <img style='vertical-align: middle;' src='/images/cancel.png' title='placeholder'/>"); } console.log("here8"); $(spanId).tooltip({ content: json.msg}); }, // Display the URL beforeSend: function(b,c,d) {console.log("beforesend: " + c.url);}, error: function(b,c,d) {console.log("here5");} }); } catch(e) { console.log(e); for (var i in e) console.log(i + "=" + i[e]); } console.log("here6"); }
What could I do further to debug this?
UPDATE: Output of code on a working page
Here's the output of the exact same code but on the page where it is working:
[15:01:20.158] "here" [15:01:20.159] "beforesend: /admin/test.html?server=eferbelly&port=24466&username=akilandy&password=vkjvkc9776A" [15:01:20.159] "here6" [15:01:21.661] GET https://localhost/images/accept.png [HTTP/1.1 200 OK 2ms] [15:01:21.599] "here2" [15:01:21.600] "here8"
So it obviously gets through the ajax call with flying colors. No errors, nothing. How can I find the problem on the page where it doesn't work?
-10853657 0You will have to use a complex combination of the SUBSTR
and LOCATE
functions that are in MYSQL.
For details on SUBSTR
click here.
For details on LOCATE
click here.
XML represents structured information, you can enforce the structure by adding a DTD or xsd to your xml, but you can not represent constants.
-8185701 0I had to DisableProxyCreation in the context configuration:
[OperationContract] [WebGet(UriTemplate = "")] public List<ParentClass> GetParents() { using (DBContext context = new DBContext()) { context.Configuration.ProxyCreationEnabled = false; List<ParentClass> parents = context.Parents .Include("Children") .ToList(); return playlists; } }
This worked out for me fine.
-12752478 0 -27341709 0I'm working with LibreOffice 4.2.0.4 and the following Code works for me:
Dim Dir as String GlobalScope.BasicLibraries.loadLibrary("Tools") Dir = Tools.Strings.DirectoryNameoutofPath(ThisComponent.url, "/")
The variable "dir" contains now the path of the current document.
-11121579 0I had a similar problem with SVG for a responsive design I was working on. I ended up removing the height and width attributes on the SVG element, and setting them via CSS instead. There is also a viewBox attribute on my SVG element and preserveAspectRatio="xMidYMin meet". With that setup I was able to have an SVG element that resizes dynamically based on viewport size.
-33305635 0Since x
has been declared as var
. Closure will capture x
as mutable version. Therefore, x
will increase overtime when the loop pass.
You can capture x
with let
. Since let
is immutable . It will never be changed. Use that value inside the closure. For example
for var x = 0; x < tableArray.param.count; ++x { let capturedX = x // do something with capturedX self.tableArray.param[capturedX].revision = rev.stringValue }
or just use range loop. It's more elegant and clean.
for x in 0..< tableArray.param.count{ // do the same way you do with x // ... }
-25614319 0 How to get the "this" from parent function I am building a simple tab system with angularjs, but I'm having trouble referring to this
in the parent function. I know I might be misunderstanding some fundamentals, so please educate me:
js:
$scope.tabs = { _this: this, // doesn't work open: function(elem) { $scope.tabsOpen = true; if(elem) $scope[elem] = true; }, close: function() { $scope.tabsOpen = false; }, about: { open: function() { $scope.aboutOpen = true; _this.notification.close(); // doesn't work $scope.tabs.notification.close(); // works }, close: function() { $scope.aboutOpen = false; } }, notification: { open: function() {/*etc*/}, close: function() {/*etc*/} }, message: { open: function() {/*etc*/}, close: function() {/*etc*/} }, }
-33121344 0 R dygraph prediction plotted along with original values I need to plot a time series in Dygraphs, where multiple time series are plotted together.
As data we can use
df <- cbind(mdeaths, fdeaths)
as is done on dygraphs website: https://rstudio.github.io/dygraphs/
However I would like to make the prediction of both time series continue in the same image as the original data. I have made a crude drawing of what I want to achieve
One way is naturally to make the predictions with i.e auto.arima separately and then combine the data once again. I am wondering if there is a functionality, that can do it all in one shot?
-39225629 0Keep it simple
-- Your original declaration declare @myVariable nvarchar(max) set @myVariable = 'Select ROWGUID from MySampleTable' -- Additional code declare @myQuery nvarchar(max) = 'SELECT ROWGUID FROM myTable WHERE ROWGUID in (' + @myVariable + ')' exec (@myQuery)
-12484402 0 The fundamental problem is that your "findword" function isn't actually finding a word; it's just looking at one item in the list. It needs to loop.
-7300439 0This turned out to be yet another case of 'Make sure you are compiling everything statically'
-5737076 0 Simple Rspec test for positive number just won't passI'm new to rails and trying to write my first app. I have a table with columns order_size:integer and price:decimal(8,5). The price column holds currency prices so it needs to be really precise, in case you're wondering. I'm trying to write tests to make sure the price and order_size are a positive numbers, but no matter what I do they won't pass.
Here are the Rspec tests
it "should require a positive order size" do @attr[:order_size] = -23 @user.orders.create!(@attr).should_not be_valid end it "should require a positive price" do @attr[:price] = -1.2908 @user.orders.create!(@attr).should_not be_valid end
Here are the Order class validations
validates_presence_of :user_id validates_numericality_of :order_size, :greater_than => 0, :only_integer => true validates_numericality_of :price, :greater_than => 0
Here's the test results
Failures: 1) Order validations should require a positive order size Failure/Error: @user.orders.create!(@attr).should_not be_valid ActiveRecord::RecordInvalid: Validation failed: Order size must be greater than 0 # ./spec/models/order_spec.rb:39:in `block (3 levels) in <top (required)>' 2) Order validations should require a positive price Failure/Error: @user.orders.create!(@attr).should_not be_valid ActiveRecord::RecordInvalid: Validation failed: Price must be greater than 0 # ./spec/models/order_spec.rb:44:in `block (3 levels) in <top (required)>'
What exactly is going on here? I even tried running the test asserting they should be_valid, but they still fail. Any help would be appreciated.
-40000042 0try this
TypedQuery<A> query = em.createQuery("select b.a from B b inner join C c where c.d = :d",A.class); List<A> a = query.getResultList();
-29181507 0 TestNG ERROR Cannot find class in classpath: I have a Selenium project with Selenium 2.43.1 and below is my folder structure of the project.
F:\SeleniumProject F:\SeleniumProject\Workspace\UIAutomation F:\SeleniumProject>dir 20-Mar-15 02:10 PM <DIR> . 20-Mar-15 02:10 PM <DIR> .. 21-Mar-15 10:15 AM <DIR> eclipse 20-Mar-15 02:10 PM <DIR> Firefox 20-Mar-15 12:23 PM <DIR> Java 20-Mar-15 12:56 PM <DIR> selenium-2.43.1 20-Mar-15 12:41 PM <DIR> Workspace F:\SeleniumProject\Workspace\UIAutomation>dir 20-Mar-15 06:40 PM <DIR> . 20-Mar-15 06:40 PM <DIR> .. 20-Mar-15 01:17 PM 5,856 .classpath 20-Mar-15 12:36 PM 388 .project 20-Mar-15 12:36 PM <DIR> .settings 21-Mar-15 10:16 AM <DIR> bin 20-Mar-15 12:41 PM <DIR> src 21-Mar-15 02:38 PM <DIR> test-output 20-Mar-15 07:39 PM <DIR> testng
I have the .class of the test class in src\com\ui\test\scripts
I have the .class files of the library files in src\com\ui\test\lib
The testng.xml
is in the F:\SeleniumProject\Workspace\UIAutomation\testng
folder. When I try to execute a testng test from the command line,
java -cp "F:\SeleniumProject\selenium-2.43.1\libs\testng-6.8.jar" org.testng.TestNG testng.xml
it fails with the below error:
[TestNG] [ERROR] Cannot find class in classpath: com.ui.test.scripts.VerificationOfLoginTest
I have tried enough to fix this, but I am unable to do it. I almost spent one day to correct this. What could have gone wrong as I can run the tests from Eclipse successfully?
-29929133 0 Spring Boot & Security with AngularJS Login pageI'm following this tutorial/example of Dave Syer in order to implement a custom AngularJS login page with Spring Security. And the example works fine locally: https://github.com/dsyer/spring-security-angular/tree/master/single
However, when I try to implement this myself, changing some things in a way i would like them to be, I'm not able to authenticate, and I'm not sure where my mistake is. This is the console output where i try to log in:
2015-05-04 21:27:18.657 DEBUG 1260 --- [nio-8080-exec-5] o.s.s.w.util.matcher.AndRequestMatcher : Trying to match using Ant [pattern='/**', GET] 2015-05-04 21:27:18.657 DEBUG 1260 --- [nio-8080-exec-5] o.s.s.w.u.matcher.AntPathRequestMatcher : Request '/user' matched by universal pattern '/**' 2015-05-04 21:27:18.657 DEBUG 1260 --- [nio-8080-exec-5] o.s.s.w.util.matcher.AndRequestMatcher : Trying to match using NegatedRequestMatcher [requestMatcher=Ant [pattern='/**/favicon.ico']] 2015-05-04 21:27:18.657 DEBUG 1260 --- [nio-8080-exec-5] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/user'; against '/**/favicon.ico' 2015-05-04 21:27:18.657 DEBUG 1260 --- [nio-8080-exec-5] o.s.s.w.u.matcher.NegatedRequestMatcher : matches = true 2015-05-04 21:27:18.657 DEBUG 1260 --- [nio-8080-exec-5] o.s.s.w.util.matcher.AndRequestMatcher : Trying to match using NegatedRequestMatcher [requestMatcher=MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.ContentNegotiationManager@4c1b0a9b, matchingMediaTypes=[application/json], useEquals=false, ignoredMediaTypes=[*/*]]] 2015-05-04 21:27:18.658 DEBUG 1260 --- [nio-8080-exec-5] o.s.s.w.u.m.MediaTypeRequestMatcher : httpRequestMediaTypes=[application/json, text/plain, */*] 2015-05-04 21:27:18.658 DEBUG 1260 --- [nio-8080-exec-5] o.s.s.w.u.m.MediaTypeRequestMatcher : Processing application/json 2015-05-04 21:27:18.658 DEBUG 1260 --- [nio-8080-exec-5] o.s.s.w.u.m.MediaTypeRequestMatcher : application/json .isCompatibleWith application/json = true 2015-05-04 21:27:18.658 DEBUG 1260 --- [nio-8080-exec-5] o.s.s.w.u.matcher.NegatedRequestMatcher : matches = false 2015-05-04 21:27:18.658 DEBUG 1260 --- [nio-8080-exec-5] o.s.s.w.util.matcher.AndRequestMatcher : Did not match 2015-05-04 21:27:18.658 DEBUG 1260 --- [nio-8080-exec-5] o.s.s.w.s.HttpSessionRequestCache : Request not saved as configured RequestMatcher did not match 2015-05-04 21:27:18.658 DEBUG 1260 --- [nio-8080-exec-5] o.s.s.w.a.ExceptionTranslationFilter : Calling Authentication entry point. 2015-05-04 21:27:18.658 DEBUG 1260 --- [nio-8080-exec-5] o.s.s.w.a.Http403ForbiddenEntryPoint : Pre-authenticated entry point called. Rejecting access 2015-05-04 21:27:18.658 DEBUG 1260 --- [nio-8080-exec-5] w.c.HttpSessionSecurityContextRepository : SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession. 2015-05-04 21:27:18.658 DEBUG 1260 --- [nio-8080-exec-5] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed 2015-05-04 21:27:23.106 DEBUG 1260 --- [nio-8080-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/user'; against '/css/**' 2015-05-04 21:27:23.107 DEBUG 1260 --- [nio-8080-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/user'; against '/js/**' 2015-05-04 21:27:23.107 DEBUG 1260 --- [nio-8080-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/user'; against '/images/**' 2015-05-04 21:27:23.107 DEBUG 1260 --- [nio-8080-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/user'; against '/**/favicon.ico' 2015-05-04 21:27:23.107 DEBUG 1260 --- [nio-8080-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/user'; against '/error' 2015-05-04 21:27:23.107 DEBUG 1260 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy : /user at position 1 of 11 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter' 2015-05-04 21:27:23.107 DEBUG 1260 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy : /user at position 2 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter' 2015-05-04 21:27:23.107 DEBUG 1260 --- [nio-8080-exec-7] w.c.HttpSessionSecurityContextRepository : No HttpSession currently exists 2015-05-04 21:27:23.108 DEBUG 1260 --- [nio-8080-exec-7] w.c.HttpSessionSecurityContextRepository : No SecurityContext was available from the HttpSession: null. A new one will be created. 2015-05-04 21:27:23.108 DEBUG 1260 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy : /user at position 3 of 11 in additional filter chain; firing Filter: 'HeaderWriterFilter' 2015-05-04 21:27:23.108 DEBUG 1260 --- [nio-8080-exec-7] o.s.s.w.header.writers.HstsHeaderWriter : Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@248a309c 2015-05-04 21:27:23.108 DEBUG 1260 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy : /user at position 4 of 11 in additional filter chain; firing Filter: 'CsrfFilter' 2015-05-04 21:27:23.108 DEBUG 1260 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy : /user at position 5 of 11 in additional filter chain; firing Filter: 'LogoutFilter' 2015-05-04 21:27:23.108 DEBUG 1260 --- [nio-8080-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'GET /user' doesn't match 'POST /logout 2015-05-04 21:27:23.108 DEBUG 1260 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy : /user at position 6 of 11 in additional filter chain; firing Filter: 'RequestCacheAwareFilter' 2015-05-04 21:27:23.109 DEBUG 1260 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy : /user at position 7 of 11 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter' 2015-05-04 21:27:23.109 DEBUG 1260 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy : /user at position 8 of 11 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter' 2015-05-04 21:27:23.109 DEBUG 1260 --- [nio-8080-exec-7] o.s.s.w.a.AnonymousAuthenticationFilter : Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@9055c2bc: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS' 2015-05-04 21:27:23.109 DEBUG 1260 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy : /user at position 9 of 11 in additional filter chain; firing Filter: 'SessionManagementFilter' 2015-05-04 21:27:23.109 DEBUG 1260 --- [nio-8080-exec-7] o.s.s.w.session.SessionManagementFilter : Requested session ID 5140C94E8B1D8BF835A5A52AAA5F4D5B is invalid. 2015-05-04 21:27:23.109 DEBUG 1260 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy : /user at position 10 of 11 in additional filter chain; firing Filter: 'ExceptionTranslationFilter' 2015-05-04 21:27:23.109 DEBUG 1260 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy : /user at position 11 of 11 in additional filter chain; firing Filter: 'FilterSecurityInterceptor' 2015-05-04 21:27:23.109 DEBUG 1260 --- [nio-8080-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/user'; against '/index.html' 2015-05-04 21:27:23.109 DEBUG 1260 --- [nio-8080-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/user'; against '/home.html' 2015-05-04 21:27:23.109 DEBUG 1260 --- [nio-8080-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/user'; against '/login.html' 2015-05-04 21:27:23.109 DEBUG 1260 --- [nio-8080-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/user'; against '/' 2015-05-04 21:27:23.110 DEBUG 1260 --- [nio-8080-exec-7] o.s.s.w.a.i.FilterSecurityInterceptor : Secure object: FilterInvocation: URL: /user; Attributes: [authenticated] 2015-05-04 21:27:23.110 DEBUG 1260 --- [nio-8080-exec-7] o.s.s.w.a.i.FilterSecurityInterceptor : Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken@9055c2bc: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS 2015-05-04 21:27:23.110 DEBUG 1260 --- [nio-8080-exec-7] o.s.s.access.vote.AffirmativeBased : Voter: org.springframework.security.web.access.expression.WebExpressionVoter@61c084cb, returned: -1 2015-05-04 21:27:23.110 DEBUG 1260 --- [nio-8080-exec-7] o.s.s.w.a.ExceptionTranslationFilter : Access is denied (user is anonymous); redirecting to authentication entry point org.springframework.security.access.AccessDeniedException: Access is denied at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:83) at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:206) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:115) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:85) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:57) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192) at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:516) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1086) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:659) at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:223) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1558) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1515) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:745) 2015-05-04 21:27:23.111 DEBUG 1260 --- [nio-8080-exec-7] o.s.s.w.util.matcher.AndRequestMatcher : Trying to match using Ant [pattern='/**', GET] 2015-05-04 21:27:23.111 DEBUG 1260 --- [nio-8080-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Request '/user' matched by universal pattern '/**' 2015-05-04 21:27:23.111 DEBUG 1260 --- [nio-8080-exec-7] o.s.s.w.util.matcher.AndRequestMatcher : Trying to match using NegatedRequestMatcher [requestMatcher=Ant [pattern='/**/favicon.ico']] 2015-05-04 21:27:23.111 DEBUG 1260 --- [nio-8080-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/user'; against '/**/favicon.ico' 2015-05-04 21:27:23.111 DEBUG 1260 --- [nio-8080-exec-7] o.s.s.w.u.matcher.NegatedRequestMatcher : matches = true 2015-05-04 21:27:23.111 DEBUG 1260 --- [nio-8080-exec-7] o.s.s.w.util.matcher.AndRequestMatcher : Trying to match using NegatedRequestMatcher [requestMatcher=MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.ContentNegotiationManager@4c1b0a9b, matchingMediaTypes=[application/json], useEquals=false, ignoredMediaTypes=[*/*]]] 2015-05-04 21:27:23.111 DEBUG 1260 --- [nio-8080-exec-7] o.s.s.w.u.m.MediaTypeRequestMatcher : httpRequestMediaTypes=[application/json, text/plain, */*] 2015-05-04 21:27:23.111 DEBUG 1260 --- [nio-8080-exec-7] o.s.s.w.u.m.MediaTypeRequestMatcher : Processing application/json 2015-05-04 21:27:23.111 DEBUG 1260 --- [nio-8080-exec-7] o.s.s.w.u.m.MediaTypeRequestMatcher : application/json .isCompatibleWith application/json = true 2015-05-04 21:27:23.111 DEBUG 1260 --- [nio-8080-exec-7] o.s.s.w.u.matcher.NegatedRequestMatcher : matches = false 2015-05-04 21:27:23.111 DEBUG 1260 --- [nio-8080-exec-7] o.s.s.w.util.matcher.AndRequestMatcher : Did not match 2015-05-04 21:27:23.112 DEBUG 1260 --- [nio-8080-exec-7] o.s.s.w.s.HttpSessionRequestCache : Request not saved as configured RequestMatcher did not match 2015-05-04 21:27:23.112 DEBUG 1260 --- [nio-8080-exec-7] o.s.s.w.a.ExceptionTranslationFilter : Calling Authentication entry point. 2015-05-04 21:27:23.112 DEBUG 1260 --- [nio-8080-exec-7] o.s.s.w.a.Http403ForbiddenEntryPoint : Pre-authenticated entry point called. Rejecting access 2015-05-04 21:27:23.112 DEBUG 1260 --- [nio-8080-exec-7] w.c.HttpSessionSecurityContextRepository : SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession. 2015-05-04 21:27:23.112 DEBUG 1260 --- [nio-8080-exec-7] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
Notable changes (And most likely the source of my issues):
Since i wanted to use a database instead of property file, i added a user, userRepository, userDetailsService, and changed the security configuration a bit. Fronted code like Controllers (both from Spring MVC and Angular), .html & .js files are not changed, so i don't think that the problem is in those, nevertheless i paste those lines also:
PS: My test data is populated in db, can be read through JUnit tests with Spring Data like this (so i think that is also not the cause):
@Autowired private UserRepository userRepo; @Test public void testUserRepo() { User myUser = userRepo.findOneByUsername("myUser"); assertEquals("myPassword", myUser.getPassword()); Collection<SimpleGrantedAuthority> authorities = myUser.getAuthorities(); assertTrue(authorities.contains(new SimpleGrantedAuthority("ROLE_ADMIN"))); assertTrue(authorities.contains(new SimpleGrantedAuthority("ROLE_USER"))); }
Relevant Code:
User.java
@Document(collection = "User") public class User implements UserDetails { /** * */ private static final long serialVersionUID = 7206798553934461899L; @Id private Long id; @NotNull @Size(min = 1, max = 20) private String username; @NotNull @Size(min = 4, max = 8) private String password; private Set<SimpleGrantedAuthority> authorities = new HashSet<SimpleGrantedAuthority>(); @Override public Collection<SimpleGrantedAuthority> getAuthorities() { return authorities; }
UserRepository.java
public interface UserRepository extends MongoRepository<User, Long> { User findOneByUsername(String username); }
UserDetailsService.java
@Service public class UserDetailsService implements org.springframework.security.core.userdetails.UserDetailsService { @Autowired private UserRepository repository; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { return repository.findOneByUsername(username); } }
SecurityConfiguration.java
@Configuration @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER) public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/index.html", "/home.html", "/login.html", "/").permitAll().anyRequest() .authenticated(); } }
HomeController.java
@RestController public class HomeController { @RequestMapping("/user") public Principal user(Principal user) { return user; } @RequestMapping("/resource") public Map<String, Object> home() { Map<String, Object> model = new HashMap<String, Object>(); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); model.put("id", auth.getName()); model.put("content", "Hello World"); return model; } }
Application.java
@SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
login.html
<div class="alert alert-danger" ng-show="error"> There was a problem logging in. Please try again. </div> <form role="form" ng-submit="login()"> <div class="form-group"> <label for="username">Username:</label> <input type="text" class="form-control" id="username" name="username" ng-model="credentials.username"/> </div> <div class="form-group"> <label for="password">Password:</label> <input type="password" class="form-control" id="password" name="password" ng-model="credentials.password"/> </div> <button type="submit" class="btn btn-primary">Submit</button> </form>
hello.js (AngularJS Controller)
angular.module('hello', [ 'ngRoute' ]).config(function($routeProvider, $httpProvider) { $routeProvider.when('/', { templateUrl : 'home.html', controller : 'home' }).when('/login', { templateUrl : 'login.html', controller : 'navigation' }).otherwise('/'); $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'; }).controller( 'navigation', function($rootScope, $scope, $http, $location, $route) { $scope.tab = function(route) { return $route.current && route === $route.current.controller; }; var authenticate = function(credentials, callback) { var headers = credentials ? { authorization : "Basic " + btoa(credentials.username + ":" + credentials.password) } : {}; $http.get('user', { headers : headers }).success(function(data) { if (data.name) { $rootScope.authenticated = true; } else { $rootScope.authenticated = false; } callback && callback($rootScope.authenticated); }).error(function() { $rootScope.authenticated = false; callback && callback(false); }); } authenticate(); $scope.credentials = {}; $scope.login = function() { authenticate($scope.credentials, function(authenticated) { if (authenticated) { console.log("Login succeeded") $location.path("/"); $scope.error = false; $rootScope.authenticated = true; } else { console.log("Login failed") $location.path("/login"); $scope.error = true; $rootScope.authenticated = false; } }) }; $scope.logout = function() { $http.post('logout', {}).success(function() { $rootScope.authenticated = false; $location.path("/"); }).error(function(data) { console.log("Logout failed") $rootScope.authenticated = false; }); } }).controller('home', function($scope, $http) { $http.get('/resource/').success(function(data) { $scope.greeting = data; }) });
-10160326 0 Macro to allocate struct on stack with pre-computed member lengths I have a struct of the form:
typedef struct node { unsigned int * keys; unsigned int * branches; } NODE;
The number of keys and branches is determined at runtime, but is known. It is derived from another struct:
typedef struct tree { unsigned int num_keys_per_node; } TREE;
In order to allocate a NODE
for this TREE
, the manual steps would be:
NODE node; unsigned int keys[tree->num_keys_per_node]; unsigned int branches[tree->num_keys_per_node + 1]; node.keys = keys; node.branches = branches;
I need to allocate a lot of these nodes inside tight loops, only temporarily as I traverse a data structure, discarding them quickly as the node traversal continues. I could write a function that returns a pointer and malloc()
the keys and branches on the heap and free()
them manually, but I'd prefer to use the stack if possible.
Since this initialization logic is going to be repeated in a number of places, how can I define a macro, so that I can effectively do something like:
NODE node = CREATE_NODE_FOR_TREE(tree);
I'm having difficultly seeing a way to do this which will result in the preprocessor giving a valid syntax.
Happy to hear other approaches to dynamic struct allocation on stack memory too.
EDIT | I should never need more than one node in memory at the same time, so I can re-use the one struct repeatedly too.
-8533105 0 Minimum C# code to extract from .CAB archives or InfoPath XSN files, in memoryLately I've been trying to implement some functionality which extracts files from an InfoPath XSN file (a .CAB archive). After extensive searching around the internet, it seems that there is no native .NET API for this. All current solutions are centered around large libraries i.e. managed C++ which wrap up Cabinet.dll.
All of this, sadly, falls foul of my companies "No third party libraries" policy.
As of 2.0, .NET gained an attribute called UnmanagedFunctionPointer which allows source level callback declarations using __cdecl. Prior to this, __stdcall was the only show in town, unless you didn't mind fudging the IL, a practice also outlawed here. I immediately knew this would allow the implementation of a fairly small C# wrapper for Cabinet.dll, but I couldn't find an example of one anywhere.
Does anyone know of a cleaner way than the below to do this with native code?
My current solution (executes unmanaged code, but fully working, Tested on 32/64-bit):
[StructLayout(LayoutKind.Sequential)] public class CabinetInfo //Cabinet API: "FDCABINETINFO" { public int cbCabinet; public short cFolders; public short cFiles; public short setID; public short iCabinet; public int fReserve; public int hasprev; public int hasnext; } public class CabExtract : IDisposable { //If any of these classes end up with a different size to its C equivilent, we end up with crash and burn. [StructLayout(LayoutKind.Sequential)] private class CabError //Cabinet API: "ERF" { public int erfOper; public int erfType; public int fError; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] private class FdiNotification //Cabinet API: "FDINOTIFICATION" { public int cb; public string psz1; public string psz2; public string psz3; public IntPtr userData; public IntPtr hf; public short date; public short time; public short attribs; public short setID; public short iCabinet; public short iFolder; public int fdie; } private enum FdiNotificationType { CabinetInfo, PartialFile, CopyFile, CloseFileInfo, NextCabinet, Enumerate } private class DecompressFile { public IntPtr Handle { get; set; } public string Name { get; set; } public bool Found { get; set; } public int Length { get; set; } public byte[] Data { get; set; } } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr FdiMemAllocDelegate(int numBytes); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void FdiMemFreeDelegate(IntPtr mem); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr FdiFileOpenDelegate(string fileName, int oflag, int pmode); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate Int32 FdiFileReadDelegate(IntPtr hf, [In, Out] [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2, ArraySubType = UnmanagedType.U1)] byte[] buffer, int cb); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate Int32 FdiFileWriteDelegate(IntPtr hf, [In] [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2, ArraySubType = UnmanagedType.U1)] byte[] buffer, int cb); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate Int32 FdiFileCloseDelegate(IntPtr hf); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate Int32 FdiFileSeekDelegate(IntPtr hf, int dist, int seektype); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr FdiNotifyDelegate( FdiNotificationType fdint, [In] [MarshalAs(UnmanagedType.LPStruct)] FdiNotification fdin); [DllImport("cabinet.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "FDICreate", CharSet = CharSet.Ansi)] private static extern IntPtr FdiCreate( FdiMemAllocDelegate fnMemAlloc, FdiMemFreeDelegate fnMemFree, FdiFileOpenDelegate fnFileOpen, FdiFileReadDelegate fnFileRead, FdiFileWriteDelegate fnFileWrite, FdiFileCloseDelegate fnFileClose, FdiFileSeekDelegate fnFileSeek, int cpuType, [MarshalAs(UnmanagedType.LPStruct)] CabError erf); [DllImport("cabinet.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "FDIIsCabinet", CharSet = CharSet.Ansi)] private static extern bool FdiIsCabinet( IntPtr hfdi, IntPtr hf, [MarshalAs(UnmanagedType.LPStruct)] CabinetInfo cabInfo); [DllImport("cabinet.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "FDIDestroy", CharSet = CharSet.Ansi)] private static extern bool FdiDestroy(IntPtr hfdi); [DllImport("cabinet.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "FDICopy", CharSet = CharSet.Ansi)] private static extern bool FdiCopy( IntPtr hfdi, string cabinetName, string cabinetPath, int flags, FdiNotifyDelegate fnNotify, IntPtr fnDecrypt, IntPtr userData); private readonly FdiFileCloseDelegate _fileCloseDelegate; private readonly FdiFileOpenDelegate _fileOpenDelegate; private readonly FdiFileReadDelegate _fileReadDelegate; private readonly FdiFileSeekDelegate _fileSeekDelegate; private readonly FdiFileWriteDelegate _fileWriteDelegate; private readonly FdiMemAllocDelegate _femAllocDelegate; private readonly FdiMemFreeDelegate _memFreeDelegate; private readonly CabError _erf; private readonly List<DecompressFile> _decompressFiles; private readonly byte[] _inputData; private IntPtr _hfdi; private bool _disposed; private const int CpuTypeUnknown = -1; public CabExtract(byte[] inputData) { _fileReadDelegate = FileRead; _fileOpenDelegate = InputFileOpen; _femAllocDelegate = MemAlloc; _fileSeekDelegate = FileSeek; _memFreeDelegate = MemFree; _fileWriteDelegate = FileWrite; _fileCloseDelegate = InputFileClose; _inputData = inputData; _decompressFiles = new List<DecompressFile>(); _erf = new CabError(); _hfdi = IntPtr.Zero; } private static IntPtr FdiCreate( FdiMemAllocDelegate fnMemAlloc, FdiMemFreeDelegate fnMemFree, FdiFileOpenDelegate fnFileOpen, FdiFileReadDelegate fnFileRead, FdiFileWriteDelegate fnFileWrite, FdiFileCloseDelegate fnFileClose, FdiFileSeekDelegate fnFileSeek, CabError erf) { return FdiCreate(fnMemAlloc, fnMemFree, fnFileOpen, fnFileRead, fnFileWrite, fnFileClose, fnFileSeek, CpuTypeUnknown, erf); } private static bool FdiCopy( IntPtr hfdi, FdiNotifyDelegate fnNotify) { return FdiCopy(hfdi, "<notused>", "<notused>", 0, fnNotify, IntPtr.Zero, IntPtr.Zero); } private IntPtr FdiContext { get { if (_hfdi == IntPtr.Zero) { _hfdi = FdiCreate(_femAllocDelegate, _memFreeDelegate, _fileOpenDelegate, _fileReadDelegate, _fileWriteDelegate, _fileCloseDelegate, _fileSeekDelegate, _erf); if (_hfdi == IntPtr.Zero) throw new ApplicationException("Failed to create FDI context."); } return _hfdi; } } public void Dispose() { Dispose(true); } private void Dispose(bool disposing) { if (!_disposed) { if (_hfdi != IntPtr.Zero) { FdiDestroy(_hfdi); _hfdi = IntPtr.Zero; } _disposed = true; } } private IntPtr NotifyCallback(FdiNotificationType fdint, FdiNotification fdin) { switch (fdint) { case FdiNotificationType.CopyFile: return OutputFileOpen(fdin); case FdiNotificationType.CloseFileInfo: return OutputFileClose(fdin); default: return IntPtr.Zero; } } private IntPtr InputFileOpen(string fileName, int oflag, int pmode) { var stream = new MemoryStream(_inputData); GCHandle gch = GCHandle.Alloc(stream); return (IntPtr)gch; } private int InputFileClose(IntPtr hf) { var stream = StreamFromHandle(hf); stream.Close(); ((GCHandle)(hf)).Free(); return 0; } private IntPtr OutputFileOpen(FdiNotification fdin) { var extractFile = _decompressFiles.Where(ef => ef.Name == fdin.psz1).SingleOrDefault(); if (extractFile != null) { var stream = new MemoryStream(); GCHandle gch = GCHandle.Alloc(stream); extractFile.Handle = (IntPtr)gch; return extractFile.Handle; } //Don't extract return IntPtr.Zero; } private IntPtr OutputFileClose(FdiNotification fdin) { var extractFile = _decompressFiles.Where(ef => ef.Handle == fdin.hf).Single(); var stream = StreamFromHandle(fdin.hf); extractFile.Found = true; extractFile.Length = (int)stream.Length; if (stream.Length > 0) { extractFile.Data = new byte[stream.Length]; stream.Position = 0; stream.Read(extractFile.Data, 0, (int)stream.Length); } stream.Close(); return IntPtr.Zero; } private int FileRead(IntPtr hf, byte[] buffer, int cb) { var stream = StreamFromHandle(hf); return stream.Read(buffer, 0, cb); } private int FileWrite(IntPtr hf, byte[] buffer, int cb) { var stream = StreamFromHandle(hf); stream.Write(buffer, 0, cb); return cb; } private static Stream StreamFromHandle(IntPtr hf) { return (Stream)((GCHandle)hf).Target; } private IntPtr MemAlloc(int cb) { return Marshal.AllocHGlobal(cb); } private void MemFree(IntPtr mem) { Marshal.FreeHGlobal(mem); } private int FileSeek(IntPtr hf, int dist, int seektype) { var stream = StreamFromHandle(hf); return (int)stream.Seek(dist, (SeekOrigin)seektype); } public bool ExtractFile(string fileName, out byte[] outputData, out int outputLength) { if (_disposed) throw new ObjectDisposedException("CabExtract"); var fileToDecompress = new DecompressFile(); fileToDecompress.Found = false; fileToDecompress.Name = fileName; _decompressFiles.Add(fileToDecompress); FdiCopy(FdiContext, NotifyCallback); if (fileToDecompress.Found) { outputData = fileToDecompress.Data; outputLength = fileToDecompress.Length; _decompressFiles.Remove(fileToDecompress); return true; } outputData = null; outputLength = 0; return false; } public bool IsCabinetFile(out CabinetInfo cabinfo) { if (_disposed) throw new ObjectDisposedException("CabExtract"); var stream = new MemoryStream(_inputData); GCHandle gch = GCHandle.Alloc(stream); try { var info = new CabinetInfo(); var ret = FdiIsCabinet(FdiContext, (IntPtr)gch, info); cabinfo = info; return ret; } finally { stream.Close(); gch.Free(); } } public static bool IsCabinetFile(byte[] inputData, out CabinetInfo cabinfo) { using (var decomp = new CabExtract(inputData)) { return decomp.IsCabinetFile(out cabinfo); } } //In an ideal world, this would take a stream, but Cabinet.dll seems to want to open the input several times. public static bool ExtractFile(byte[] inputData, string fileName, out byte[] outputData, out int length) { using (var decomp = new CabExtract(inputData)) { return decomp.ExtractFile(fileName, out outputData, out length); } } //TODO: Add methods for enumerating/extracting multiple files }
-4202779 0 Update your CSS like:
#wrapper { width: 80%; display: block; }
-25159022 0 Distorting a shape in Canvas by Clicking and Dragging a particular border point I'm creating a floor-plan application using HTML5 and kinetic js.Currently I'm able to create a rectangular container where you can drag and drop objects inside it. You can see it in action in this link http://jsfiddle.net/wQ8YA/29/
The js code to create it is..
//create a group var group = new Kinetic.Group({ draggable: true //make group draggable }); var rec = new Kinetic.Rect({ x: 10, y: 330, width: 600, height: 600 }); group.add(rec);
Currently the container looks like this
But i want to make it like this..
In the second image the user can distort the container by clicking on any point on the container border and dragging it.I tried doing it on my own but don't know where to start,what this concept is called and how to achieve it.Please Help..
-3992552 0It is because you are asking the program to read from the file file.txt
:
done <file.txt
Also looks like you have a typo here:
if [ $x = "true" ] ^^
which should be "$line"
.
Also note the "
, without them your program will break if the word read from the file has a space in it.
I think what you are looking for is something like:
foreach (var employee in details) { var groupCodes = from item in a where item.EmpID == employee.EmpID select item.GroupCode; // use groupCodes here... }
-25106011 0 Of course, in the second activity to make the users unable to go back to the login screen you use this code in the second activity overriding the back button functionality
@override public void onBackPressed() { }
And to go back to the log in screen, you can use the following code inside the function that delegates the button's click:
private void onClickLogOutButton() { Intent intent = new Intent(this, LogInActivity.class); startActivity(intent); this.finish(); }
The this.finish() will close the instance of the activity of the second screen, this will avoid the users to go back to the second activity pressing the back button.
-701621 0Firstly, you must decide on what you mean by "best" solution, of course that takes into account the efficiency of the algorithm, its readability/maintainability, and the likelihood of bugs creeping up in the future. Careful unit tests can generally avoid those problems, however.
I ran each of these examples 10 million times, and the results value is the number of ElapsedTicks
that have passed.
Without further ado, from slowest to quickest, the algorithms are:
int firstDigit = (int)(Value.ToString()[0]) - 48;
Results:
12,552,893 ticks
int firstDigit = (int)(Value / Math.Pow(10, (int)Math.Floor(Math.Log10(Value))));
Results:
9,165,089 ticks
while (number >= 10) number /= 10;
Results:
6,001,570 ticks
int firstdigit; if (Value < 10) firstdigit = Value; else if (Value < 100) firstdigit = Value / 10; else if (Value < 1000) firstdigit = Value / 100; else if (Value < 10000) firstdigit = Value / 1000; else if (Value < 100000) firstdigit = Value / 10000; else if (Value < 1000000) firstdigit = Value / 100000; else if (Value < 10000000) firstdigit = Value / 1000000; else if (Value < 100000000) firstdigit = Value / 10000000; else if (Value < 1000000000) firstdigit = Value / 100000000; else firstdigit = Value / 1000000000;
Results:
1,421,659 ticks
if (i >= 100000000) i /= 100000000; if (i >= 10000) i /= 10000; if (i >= 100) i /= 100; if (i >= 10) i /= 10;
Results:
1,399,788 ticks
Note:
each test calls Random.Next()
to get the next int
I could not figure out a proper solution to the timming issue so here is a workaround:
function resize(){ $("#id_permissions_from").css("height", 600); $("#id_permissions_from").css("overflow", "scroll"); $("#id_permissions_to").css("height", 600); $("#id_permissions_to").css("overflow", "scroll"); } $(function() { setTimeout(function() { resize() }, 1000); //resize(); })
-24123732 0 Elegant way of turning Dictionary or Generator or Sequence in Swift into an Array? Is there an elegant way to convert Dictionary (or Sequence or Generator) into an Array. I know I can convert it by looping through the sequence as follows.
var d = ["foo" : 1, "bar" : 2] var g: DictionaryGenerator<String, Int> = d.generate() var a = Array<(String, Int)>() while let item = g.next() { a += item }
I am hoping there is something similar to Python's easy conversion:
>>> q = range(10) >>> i = iter(q) >>> i <listiterator object at 0x1082b2090> >>> z = list(i) >>> z [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>>
-30406849 0 glfwOpenWindow fail on osx yosemite I am trying to build and run the following project on OS X Yosemite to play with ray marching & shaders:
https://github.com/lightbits/ray-march/blob/master/raymarch-dev.md
I am not too familiar with compilation on OS X nor openGL.
The error:
I got the project to compile but « glfwOpenWindow » fail on,
glfwOpenWindow( width, height, 8, 8, 8, 0, 24, 8, false )
I don’t get any error message and don’t know why it failed. I think the problem comes from what I did to build the codebase.
What I did:
The external includes are:
#include <glload/gl_3_1_comp.h> // OpenGL version 3.1, compatability profile #include <glload/gll.hpp> // The C-style loading interface #include <GL/glfw.h> // Context #include <glm/glm.hpp> // OpenGL mathematics #include <glm/gtc/type_ptr.hpp> // for value_ptr(matrix) #include <string>
I replaced, in "opengl.h",
#include <glload/gl_3_1_comp.h> // OpenGL version 3.1, compatability profile #include <glload/gll.hpp> // The C-style loading interface
with,
`#include <OpenGL/gl3.h>`
I removed, in "opengl.cpp".
if(glload::LoadFunctions() == glload::LS_LOAD_FAILED) return false;
my current compiling command is:
g++ main.cpp fileio.cpp opengl.cpp -I /usr/local/include/GL/ -L /usr/local/lib/ -framework OpenGL -lGLFW
It's a quick question for you,
I need to select Jquery element by type AND by name.
I know that we can do something like:
$('.form-control input[type=text]')....
but I need to select by name too..
do you have another way to do that unless using:
$('.form-control input[type=text]').each(function (){ if($(this).attr('name') == 'search'){ // this is my selector } }
thank you
-33671497 0 RegEx with preg_match to find and replace a SIMILAR stringI am using regular expressions with preg_replace()
in order to find and replace a sentence in a piece of text. The $search_string
contains plain text + html tags +
elements. The problem is that only sometimes the
elements convert to white space on run time, making it difficult to find and replace using str_replace()
. So, I'm trying to build a pattern that is equal to the search string and will match anything like it which contains, or does not contain the
elements;
For example:
$search_string = 'Two years in, the company has expanded to 35 cities, five of which are outside the U.S. Plus, in April, <a href="site.com">ClassPass</a> acquired its main competitor, Fitmob.';
$pattern
= $search_string
(BUT IGNORE THE
elements in the subject)
$subject = "text text text text text". $search_string . "text text text text text";
Using A regular expression to exclude a word/string, I've tried:
$pattern = '`^/(?!\ )'.$search_string.'`'; $output = preg_replace($pattern, $replacement_string,$subject);
The end result will be that if the $subject does contains a string that is like my $seach_string
but without the
elements, it will still match and replace it with $replacement_string
EDIT:
The actual values:
$subject = file_get_contents("http://venturebeat.com/2015/11/10/sources-classpass-raises-30-million-from-google-ventures-and-others/"); $search_string = "Two years in, the company has expanded to 35 cities, five of which are outside the U.S. Plus, in April, ClassPass acquired its main competitor, Fitmob."; $replacement_string = "<span class='smth'>Two years in, the company has expanded to 35 cities, five of which are outside the U.S. Plus, in April, ClassPass acquired its main competitor, Fitmob.</span>";
-15942721 0 Square brackets means that it's an array (basic javascript). Your require array only contains 1 item now, but it can contain more items. Your controllers is an array of 2 items.
In your define example xtype doesn't expect an array but a string. Same with extend, you can only extend from one component.
This info can be found in the docs of ExtJS aswell. For example the controllers config from your example above:
http://docs.sencha.com/ext-js/4-1/#!/api/Ext.app.Application-cfg-controllers
The docs mention this controllers : String[]
. Which means it expects an array of strings.
Sorry fo my english. I worked 2 days on this problem and i found that installutil works only if installutil and service and dependencies files in one directory.
installutil service -> works fine installutil ServicePath\service -> dont work if dependencies in ServicePath directory.
-8637520 0I recently ran some benchmarks to compare ""+myInt vs Integer.toString(myInt).
And the winner is... Integer.toString() ! Because it does not create temporary strings, uses only a adequately-sized char buffer, and some funky algorithms to convert from a digit to its char counterpart.
Here is my blog entry if you read french (or use the sidebar translation widget if you don't) : http://thecodersbreakfast.net/index.php?post/2011/11/15/Au-coeur-du-JDK-performance-des-conversions
-29008772 0 Change JLabel and wait for sometime to exitI want to change the label when I click the button, and then after 3 seconds exit the program. But if I click the button, label does not change. It just exits after 3 seconds. This is my logic
Change the label.
Sleep for 3 seconds
Then exit the program.
btnNewButton_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("Stopping the program."); state.setText("Bye..."); state.setBackground(SystemColor.textHighlight); doStop(); } }); state = new JLabel("Not listening"); state.setForeground(new Color(255, 255, 255)); state.setBackground(new Color(204, 0, 51)); state.setHorizontalAlignment(SwingConstants.CENTER); state.setBounds(10, 222, 488, 24); state.setOpaque(true); frame.getContentPane().add(state);
public void doStop() { try{ Thread.sleep(3000); } catch(InterruptedException e){ } System.exit(0); }
I am trying to create a vbscript that automatically clears files/folders from the recycle bin that have been there for more than x days. the problem is, when I get the deletion date of the files, the DateDiff function returns a mismatch error.
const Active = TRUE const MaxAge = 30 const RECYCLE_BIN = &Ha& checked = 0 deleted = 0 Set objFso = CreateObject("Scripting.FileSystemObject") Set objShell = CreateObject("Shell.Application") Set objFolder = objShell.Namespace(RECYCLE_BIN) Set colItems = objFolder.Items For Each objItem In colItems Checked = Checked + 1 dateDeleted = objFolder.GetDetailsOf(objItem, 2) 'the deletion date per file/folder If DateDiff("D", dateDeleted, Now()) > MaxAge Then If objItem.Type = "File Folder" Then Deleted = Deleted + 1 objFso.DeleteFolder(objItem.Path) Else Deleted = Deleted + 1 objFso.DeleteFile(objItem.Path) End If End If Next if Active then verb = " file(s) deleted" Else verb = " file(s) would be deleted" WScript.Echo Checked & " file(s) checked, " & Deleted & verb
I have also tried doing this but this also returned to mismatch error:
const Active = TRUE const MaxAge = 30 const RECYCLE_BIN = &Ha& checked = 0 deleted = 0 Set objFso = CreateObject("Scripting.FileSystemObject") Set objShell = CreateObject("Shell.Application") Set objFolder = objShell.Namespace(RECYCLE_BIN) Set colItems = objFolder.Items For Each objItem In colItems Checked = Checked + 1 dateStr = objFolder.GetDetailsOf(objItem, 2) 'the deletion date per file/folder dateArr = Split(dateStr, " ") If DateDiff("D", dateArr(0), Now()) > MaxAge Then If objItem.Type = "File Folder" Then Deleted = Deleted + 1 objFso.DeleteFolder(objItem.Path) Else Deleted = Deleted + 1 objFso.DeleteFile(objItem.Path) End If End If Next if Active then verb = " file(s) deleted" Else verb = " file(s) would be deleted" WScript.Echo Checked & " file(s) checked, " & Deleted & verb
AND tried: const Active = TRUE const MaxAge = 30 const RECYCLE_BIN = &Ha&
checked = 0 deleted = 0 Set objFso = CreateObject("Scripting.FileSystemObject") Set objShell = CreateObject("Shell.Application") Set objFolder = objShell.Namespace(RECYCLE_BIN) Set colItems = objFolder.Items For Each objItem In colItems Checked = Checked + 1 dateStr = objFolder.GetDetailsOf(objItem, 2) 'the deletion date per file/folder dateArr = Split(dateStr, " ") dateDeleted = cDate(dateArr(0)) If DateDiff("D", dateDeleted, Now()) > MaxAge Then If objItem.Type = "File Folder" Then Deleted = Deleted + 1 objFso.DeleteFolder(objItem.Path) Else Deleted = Deleted + 1 objFso.DeleteFile(objItem.Path) End If End If Next if Active then verb = " file(s) deleted" Else verb = " file(s) would be deleted" WScript.Echo Checked & " file(s) checked, " & Deleted & verb
but again this does not work and creates a mismatch error on the cDate.
any help would be appreciated
-22083208 0 compile time check template type C++I am trying to check a template type and appropriate invoke a function. However, this doesn't seem to work. I tried with is_same, C++ compile-time type checking, compile-time function for checking type equality and the boost::is_same. Everything is giving me the same error. The following is a sample code.
#include <iostream> #include <type_traits> using namespace std; class Numeric { public : bool isNumeric() { return true; } }; class String { }; template <class T> class Myclass { private: T temp; public: void checkNumeric() { if(std::is_same<T,Numeric>::value) { cout << "is numeric = " << temp.isNumeric(); } else { cout << "is numeric = false" << endl; } } }; int main() { Myclass<Numeric> a; a.checkNumeric(); Myclass<String> b; b.checkNumeric(); }
While compiling the above code, I am getting the following error.
make all Building file: ../src/TestCPP.cpp Invoking: GCC C++ Compiler g++ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/TestCPP.d" -MT"src/TestCPP.d" -o "src/TestCPP.o" "../src/TestCPP.cpp" ../src/TestCPP.cpp:36:36: error: no member named 'isNumeric' in 'String' cout << "is numeric = " << temp.isNumeric(); ~~~~ ^ ../src/TestCPP.cpp:51:4: note: in instantiation of member function 'Myclass<String>::checkNumeric' requested here b.checkNumeric(); ^ 1 error generated. make: *** [src/TestCPP.o] Error 1
In this case, I neither have String or Numeric class. It comes out of a third party library. I implement only MyClass which will be packaged as another library. I expect the application that uses MyClass will either pass me a String or Numeric which belongs to a third party class. MyClass is a specialized matrix operation and Dense/Sparse matrix are the Numeric and String like classes that comes from a third party library. I want to check if the application that uses my library and the third party library is invoking MyClass based on the class type that belongs to the third party library.
Kindly let me know how to fix this problem.
-26115891 0 Jar generated via warbler is not able to open bundled Poltergeist gemI have created a plugin with jruby-1.7.9 and added below gems inside my gemspec
spec.add_dependency 'phantomjs' spec.add_dependency 'capybara' spec.add_dependency 'poltergeist'
Created JAR for this plugin using Warbler(version:1.4.4). This JAR consist of below code :
require 'capybara' module Zerp class Chatter def say_hello Capybara.visit 'http://google.com' puts "#{Capybara.page.text}" end end end
The JAR is executing successfully while running it inside the plugin.
Now I copied JAR at another location and tried to run it from there. Then I'm getting below error when JAR is executing first line of the code(visit google home page) :
Can't open '/home/ndashore/nikhil/zerp.jar!/gems/poltergeist-1.5.1/lib/capybara/poltergeist/client/compiled/main.js'
Have checked file location, the file exist there and I'm able to open it.
Also have tried to use other Gem (tried with phantomjs). It works properly and do the stuff.
Please help me to use poltergeist as bundled gem.
-31827720 0I add this as a response as I can't add long comments. I have checked the .pom files of the maven repository. The main difference between 2.3.2 and 2.4.0/2.5.0 is that 2.4.0/2.5.0 add some exclusions to the dependency:
<exclusions> <exclusion> <artifactId>crashlytics-core</artifactId> <groupId>com.crashlytics.sdk.android</groupId> </exclusion> <exclusion> <artifactId>crashlytics-ndk</artifactId> <groupId>com.crashlytics.sdk.android</groupId> </exclusion> <exclusion> <artifactId>digits</artifactId> <groupId>com.digits.sdk.android</groupId> </exclusion> <exclusion> <artifactId>crashlytics</artifactId> <groupId>com.crashlytics.sdk.android</groupId> </exclusion> <exclusion> <artifactId>beta</artifactId> <groupId>com.crashlytics.sdk.android</groupId> </exclusion> </exclusions>
-33173835 1 Django Class Based View use @cache_page I want to add @cache_page
to a class based view however because of the way I have my url url(r'^/(?P<shortcut>coming-soon)$', MovieList.as_view(), name='movie_list_coming_soon'),
it brings an error MovieList has no .as_view
The class MovieList is:
class MovieList(ListView): model = Movie paginate_by = 20 context_object_name = 'movies' category = None venue = None date = None slug_level = "" def get_queryset(self): today = datetime.date.today() qs = Movie.objects.filter(visible=True,).order_by('-hot', '-showing', 'name') if self.request.mobile: self.template_name = 'mobile/movies.html' if self.kwargs.get('category', None): slugs = self.kwargs['category'].strip('/').split('/') self.category = get_object_or_404(Category, slug=slugs[-1]) category_ids = [c.id for c in self.category.get_child_categories()] category_ids.append(self.category.id) qs = qs.filter(categories__in=category_ids) if self.kwargs.get('venue', None): .....
-21408343 0 How to run javascript inside browser safely and securely? I need to eval()
the code inside my page because I am working on something jsFiddle-like. Since eval
has such a bad reputation, how can I interpret the user input code safely and securely? Or as safely and securely as possible?
The problem is that everytime you click deleteData
you will bind click to yes
and no
, to if you click deleteData
twice, you bind click to yes
and no
twice, because it's inside deleteData
click event.
So, to prevent this behaviour you have to remove it from inside deleteData
event.
You can try this demo.
Try to comment the line, where it is pointing out and check if the error is really with this function or not. You can also use debugger and execution transcript to figure out the issue. Also try to search it here. I saw many ticket issue about your problem.
-11926754 0You must use full scope names of types in signal declaration even if you're in same scope. Replace signal void mouseHoveredOnElemSig(AbstractFvOverlay *i);
with void mouseHoveredOnElemSig(rf::AbstractFvOverlay *i);
or use AbstractFvOverlay without scope in your connect.
I have 3 MongoDB collections and each of them are defined something like:
@app.route('/getMyData', methods=['GET']) def getMyData(): myDataCollection = db["data_1"] data = list(myDataCollection.find({},{"Name":1,"Website":1,"Twitter":1,"Description":1,"_id":0})) return jsonify(data=data)
Then I retrieve these data using AJAX requests (one for each collection so 3 requests) as follows:
function getDataFromDB() { $.ajax({ url: '/getMyData', type: 'GET', contentType: 'application/json; charset=utf-8', dataType: 'json', async: false, success: function (data) { // code goes here } }); }
How can I simplify this? It seems like I cannot query multiple collections in MongoDB.
-7160960 0 Access 2003 - count unique valuesHow to count unique values in Access 2003? When i write sth like this:
SELECT DISTINCT Customer FROM CustomersTable;
I've got as result unique customers, but how count them if this code doesn't work:
SELECT COUNT(*)
FROM (SELECT DISTINCT Customer FROM CustomersTable )
(it causes error: "The Microsoft Jet database engine cannot find the input table or query 'SELECT DISTINCT Customer FROM CustomersTable'. Make sure it exists and that its name is spelled correctly")
Example of database
--Customer -- Address -- X NY X OR Y AR Z WA
And I'd like to have as result 3 (three unique Customers.)
-33481785 0In Ember v1.13 it can be done simply by creating a component named j-check in my occasion(no layout content required):
import Ember from 'ember'; export default Ember.Checkbox.extend({ change(){ this._super(...arguments); this.get('controller').send(this.get('action')); } });
And then you just call it from your template like this:
{{j-check checked=isOnline action="refreshModel" }}
-16585624 0 awk '/^INSERT|^UPDATE|^DELETE/{i=1} /;/{i=0} {printf("%s ",$0);if(!i) print""}' <filename>
this will find the Keywords and then set a flag, which will be reset only when a ;
is found. Now till the flag is set, newline won't be printed. So it will take care if the ;
is present in the same line, if any other words are there without ;
, it will not touch those
Experiment
[[bash_prompt$]]$ cat log INSERT INTO EMP; (EMP,ENAME) VALUES ('1', 'John'); set term off; UPDATE EMP SET ENAME='Samantha' WHERE DEPT=20; INSERT INTO EMP (EMP,ENAME) VALUES ('1', 'John'); [[bash_prompt$]]$ awk '/^INSERT|^UPDATE|^DELETE/{i=1} /;/{i=0} \ {printf("%s ",$0);if(!i) print""}' log INSERT INTO EMP; (EMP,ENAME) VALUES ('1', 'John'); set term off; UPDATE EMP SET ENAME='Samantha' WHERE DEPT=20; INSERT INTO EMP (EMP,ENAME) VALUES ('1', 'John');
-5607794 0 Emacs: Switching Between Buffers with the Same Name but in Different Directories I have two files with the same name but in different directories:
apples/main.cpp oranges/main.cpp
I open them in one emacs window via emacs apples/main.cpp oranges/main.cpp
When I use C-x b
to switch between these two buffers, the buffer names are "main.cpp" and "main.cpp<2>". I would love to be able to see the full path of these two files when switching buffers, so that I may disambiguate between the apples and the oranges version. Is there a way to do this?
One way could be to modify whatever code generates the <2> after the second main.cpp when Emacs detects that a buffer with that name is already open. However, I couldn't find how to do this.
-23023609 0You could join user_roles
just once and it might help performance a tiny bit. I cannot make up my mind right now which query I like more.
SELECT u.fname ,u.lname ,c.country ,c.postal FROM [user] u INNER JOIN company c ON (u.company_id = c.id) CROSS APPLY ( SELECT SUM (IIF(role_id = 3, 1, 0)) AS role3Count, SUM (IIF(role_id = 4, 1, 0)) AS role4Count FROM users_roles ur WHERE role_id BETWEEN 3 AND 4 AND u.id = ur.user_id ) ur WHERE role3Count > 0 AND role4Count = 0 ORDER BY c.country, c.postal
This has the chance of being slightly faster because a single index seek on users_roles
with range role_id BETWEEN 3 AND 4
is enough to retrieve the roles. In your query, there were two seeks. On the other hand this query does some aggregates and computations. You'd need to measure.
I'm not convinced this is a nicer query. It is more complex than yours. I'll propose it anyway. You decide.
-1040677 0A variety of hacks:
convert
to convert your datetime to a string using just the date portionsubstring
to chop off the endfloor
The compiler needs to have access to the entire template definition (not just the signature) of addItem
in order to generate code for each instantiation of the template, so you need to move its definition to your header i.e follow the inclusion model.
Infact modern C++ compilers do not easily support the separate compilation model for templates.
-1823515 0 Expression Encoder SDK - WMA Pro Codec Issues with Windows Server 2003I am using the Expression Encoder SDK to encode .avi and Flash files to a .wmv format suitable for Silverlight. By default, EE encodes files with audio using the the WMA PRO codec. If you are running Windows Server 2003, this is a problem as it doesn't support the WMA PRO codec and produces and error message similar to the following.
Error Message: The Audio Profile settings do not match a valid system profile. Error Source: Microsoft.Expression.Encoder Error Target Site: System.String GetProfileString()
I am looking for a way to change the default audio codec to something suitable for WS 2003.
I am aware that although not supported natively, there is a highly invasive way to install Windows Media Player 11 and it's codecs on WS 2003 but this involves registry tinkering and other hacks not suitable for our production environments so that solution is out.
-19923653 0this may not be the direct answer, but in such "multiple parameter search" situations i just forget about anything and do the simple thing, for ex: Search By Car Manufacturer, CategoryId, MillageMax, Price :
var searchResults = from c in carDb.Cars where (c.Manufacturer.Contains(Manufacturer) || Manufacturer == null) && (c.CategoryId == CategoryId || CategoryId == null) && (c.Millage <= MillageMax || MillageMax== null) && (c.Price <= Price || Price == null) select c
now if any of the parameters is null
it cancels the containing line by making the whole expression in brackets True
and so it does not take a part in search any more
My application is using a database first EDMX in EF 4. I would like to upgrade everything to EF 6. After getting EF 6 with NuGet I had to make a lot of changes to my classes that are using my EF model, because namespaces have been changed in EF 6. Then I realized, that the code generated by my EDMX does also use the wrong namespaces etc. I'm not using a custom T4 so far.
How would I upgrade my existing EDMX to EF 6.
Thank you.
-7605385 0One way to accomplish this is to put all your strings into a header file, and name them:
// StringHeader.h #define helloWorld "Hello World" #define error_invalid_input "Error: Invalid Input" #define this_could_get_tedious "this could get tedious"
Then you can use those strings:
#include "StringHeader.h" std::cout << this_could_get_tedious << std::endl;
Then you can run a program on your StringHeader.h
to hash each string, and generate a replacement header file:
// Generated StringHeader.h #define helloWorld 097148937421 #define error_invalid_input 014782672317 #define this_could_get_tedious 894792738384
That looks very manual and tedious, at first, but there's ways to automate it.
For example, you could write something to parse your source code, looking for "quoted strings". Then it could name each string, write it to a single StringHeader.h
, and replace the inline quoted string with the new named string constant. As an additional step when you create the file, you could hash each string - or you could has the file in one go after you've created it. This could let you create a hashed and non-hashed version of the file (which could be nice to create a non-hashed Debug version, and a hashed Release version).
If you do try that, your initial parser to look for strings will have to handle edge cases (comments, #include lines, duplicated strings, etc).
-11138172 0You can create a class to represent a property. and use a List in your object.
class Property{ enum dataType; //create a specific enum String name; Object value; }
If you want to go further then you could inherit from this property to add somme type specialised class like BooleanProperty or StringProperty.
-17275363 0instead of saying if == 1, do
for (int i = 0; i < aStudentNumber; i++) { String aStudentName = getInput2(); String aStudentAnswer = getInput3(); int aScore = CalcScore(aStudentAnswer, aMemo); StudentInfo(aStudentName, aScore); }
Now, if you want to store that data programmatically so you can access it later on, change your StudentInfo method to something like
public static StudentInfo createStudentInfo(String bStudentName, int bScore){ ... return someObj; }
where someObj
is a an instance of a StudentInfo class (that you have to create) that actually holds all of the data you want to keep track of. Then, simply add that class to a list (inside your loop):
ArrayList<StudentInfo> siList = new ArrayList<StudentInfo>(); for (int i = 0; i < aStudentNumber; i++) { String aStudentName = getInput2(); String aStudentAnswer = getInput3(); int aScore = CalcScore(aStudentAnswer, aMemo); //StudentInfo(aStudentName, aScore); // get rid of this line since we are adding it to a list now siList.add(createStudentInfo(aStudentName, aScore)); }
Now you can recall all of that data if need be.
The biggest thing is that you need a loop. Loop until the index is at your count, and perform the same actions for each answer set.
Edit: The following is to address the question posted in the comments.
I think you're better off with a constructor. Use a class something like this:
public class StudentInfo { private String bStudentName; private int bScore; public StudentInfo (String bStudentName, int bScore) { this.bStudentName = bStudentName; this.bScore = bScore; } public String getStudentName() { return this.bStudentName; //'this' keyword not really necessary, but helpful } public int getScore() { return this.bScore;// again, 'this' not necessary } public void doStuff() { // optional method to do stuff with the data if need be ... } }
Then, in your loop, do
ArrayList<StudentInfo> siList = new ArrayList<StudentInfo>(); for (int i = 0; i < aStudentNumber; i++) { String aStudentName = getInput2(); String aStudentAnswer = getInput3(); int aScore = CalcScore(aStudentAnswer, aMemo); //StudentInfo(aStudentName, aScore); // get rid of this line since we are adding it to a list now //siList.add(createStudentInfo(aStudentName, aScore)); StudentInfo si = new StudentInfo(aStudentName, aScore); si.doStuff(); // optional method call in case you want to do something with the data other than store it. siList.add(si); }
your StudentInfo
class should be in the same package as your main class. If, for some reason, it is not, at the top of your main class add include theotherpackage.StudentInfo;
I just installed vifm-0.7.4. It included much more functions than version 0.4. However, I am missing one behavior in the old version. That is, if you enable screen
in vifm
:
:screen
once you press l or Enter on a text file, the file will be open in vi
in a new screen
window. However, in the new version, the file is open in the same window as vifm
interface. I can open the file in a new screen
window using the edit
command:
:e
But it is less convenient than a single l. Is it possible to go back to the old behavior in the new version?
-35331199 1 How to pass parameters to error handler?In this, there is:
from flask import render_template @app.errorhandler(404) def page_not_found(e): return render_template('404.html'), 404
What is e
and how do I pass a value to page_not_found
to display?
My code is for a REST web service. It import abort
, and if a request for a resource results in the resource not available, I call abort(404)
, as illustrated here (about ¼ down). I would like to provide more information about the nature and circumstances of the 404 to the caller.
For global lock you need mutex
// The key can be part of the file name - // be careful not all characters are valid var mut = new Mutex(true, key); try { // Wait until it is safe to enter. mut.WaitOne(); // here you manipulate your file } finally { // Release the Mutex. mut.ReleaseMutex(); }
-13377768 0 apply an active class to li. Relevant selector/markup: .nav-list > .active > a, .nav-list > .active > a:hover { applies a style to ul.nav-list li.active a; if that's what you mean –
Ross 17 hours ago
-1800832 0 Learning dojo: Chaining animations on a collection of objectsI'm doing some basic exercises with dojo to learn its syntax and methods.
I've created a simplified example below for the purpose of learning chaining animations on a group of items.
Could anyone offer some feedback on the dojo code I have created? Am I utilising the correct library features in this circumstance? Which of the dojo options do you think is the best solution for this use case?
For reference, in jQuery I would accomplish this with:
$(function() { // jQuery $('div').fadeOut().fadeIn(); })
For the dojo solution, I've come up with four solutions that rely on the presence of different dojo components:
// dojo dojo.require("dojo.fx"); dojo.require("dojo.NodeList-fx"); dojo.addOnLoad(function() { // Option 1: Using dojo.js only dojo.forEach(dojo.query('div'), function(div) { dojo.fadeOut({ node: div, 'onEnd': function() { dojo.fadeIn({ node: div }).play(); } }).play() }); // Option 2: Using dojo.js and dojo.fx dojo.forEach(dojo.query('div'), function(div) { dojo.fx.chain([dojo.fadeOut({node: div}), dojo.fadeIn({node: div})]).play(); }); // Option 3: Using dojo.js, dojo.fx and dojo.NodeList-fx var divs = dojo.query("div"); divs.fadeOut({ 'onEnd': function() { divs.fadeIn().play(); } }).play() // Option 4: Using base, dojo.fx and dojo.NodeList-fx var divs = dojo.query('div'); dojo.fx.chain([divs.fadeOut(), divs.fadeIn()]).play(); });
-13984371 0 Your code had too many errors due to mismatch of " & '. Fixed:
$("#busca").on('click', function() { $.ajax({ type : "POST", url : "service.php", dataType : "json", data : { action : "fullProjects", }, success : function(data) { var i; for ( i = 0; i < data.data.length; ++i) { console.log(i); var thisData = data.data[i]; var divCreator = ''; divCreator += '<div id="grupo' + i + '" class="typeface-js" style="font-family:GreyscaleBasic">'; divCreator += '<div class="tipo-pro">'; divCreator += '<div id="tipo_' + i + '" class="tipo"></div>'; divCreator += '<div id="tipo_arq_abajo' + i + '" class="abajo"></div>'; divCreator += '</div>'; divCreator += '<div id="fotoproyectos' + i + '" class="foto"><img src="' + thisData.path + '" height="128" width="160"></div>'; divCreator += '<div id="nombreproyectos' + i + '" class="nombre-pro"><form method="post" name="projectsearch" id="projectsearch' + i + '" action="proyectos_arq.php">'; divCreator += '<span style="cursor: pointer;" onclick="document.getElementById("projectsearch' + i + '").submit()">' + thisData.projectName + '</span>'; divCreator += '<input name=\"project_id\" type=\"hidden\" id=\"project_id\" value="' + thisData.projectId + '">'; divCreator += '</form></div>'; divCreator += '</div>'; divCreator += '<br><br><br><br><br><br>'; $("#contiene-pro").append(divCreator); }; } }); });
-15986605 0 You have to call the function for each of the images.
$(document).ready(function(){ $('img.profilepicture').each(function() { $(this).imgscale({ parent : '.ppparent', fade : 1000 }); }); });
-9631832 0 Defining a Panel and instantiating it in a viewport I am trying to get Ext.define & Ext.create working in Sencha touch 2, so that I can define everything in my library and just create stuff pre-configured.
However, Ext.define is not doing what I would expect it to in anything I've tried.
Why does the following code not create a panel inside the viewport with the field label "Tame"?
Ext.define('mobi.form.Login',{ extend:'Ext.form.Panel', items: [{ xtype: 'textfield', name: 'Tame', label: 'Tame' } ] }); Ext.application({ viewport: { layout:'fit' }, launch: function(){ var form = Ext.create('Ext.form.Panel', { items: [{ xtype: 'textfield', name: 'name', label: 'Name' } ] }); Ext.Viewport.add(Ext.create('mobi.form.Login')); // This doesnt add anything to the viewport Ext.Viewport.add(form); //magically this works } })
-17231524 0 Drupal db_select PDO Statement: ORDER BY CASE Hi I have written a MySQL statement that has a conditional order by clause which you can see in the example below.
MySQL Example:
SELECT title, description FROM books WHERE title LIKE "%keyword%" OR description LIKE "%keyword%" ORDER BY CASE WHEN title LIKE "%keyword%" THEN 1 ELSE 2 END
I am now trying to recreate this statement in Drupal using its PDO style db_select() function. But I have got stuck when writing the ORDER BY clause.
Drupal Example:
$node_select = db_select('node', 'n'); $node_select->fields('n', array('title', 'description')); $node_select->condition( db_or()->condition('n.title', '%'.$keyword.'%', 'LIKE') ->condition('n.description', '%'.$keyword.'%', 'LIKE') ); $node_select->order();
Can anyone point me in the right direction on how you would write the ORDER BY section?
-11375476 0I have found the following link which is like a pseudocode, a guideline of using condition variable. I hope it will greatly help students working on their nachos project or learning pthreads.
https://computing.llnl.gov/tutorials/pthreads/#ConVarOverview
-22369189 0When you add a PhotoImage
or other Image object to a Tkinter widget, you must keep your own reference to the image object. If you don’t, the image won’t always show up. Here is essentially what I'm trying to say:
def displayLabel(): photoimage = ImageTk.PhotoImage(file="lena.png") canvas.create_image(0,0, image=photoimage, anchor = NW) canvas.image=photoimage #keep the reference!
I learned it from here.
Also you need to remove the parenthesis ()
b3 = Button(tk, text="Display Label", width=30, command= displayLabel) #no parenthesis
otherwise it will be called directly without even the button press. You might not have noticed it up until now since Tk
was just making the image blank as you may understand now from the link.
Also if you want to send some arguments to displayLabel
you need to use lambda
. For eg:
b3 = Button(tk, text="Display Label", width=30, command= lambda:displayLabel(args))
In your asked question,you were missing the colon :
My approach on structurizing my website is having a lot of small view files. My controllers look like this
$this->load->view('templates/header'); $this->load->view('templates/navmenu'); $this->load->view('products/create', $dat); $this->load->view('templates/footer');
In CodeIgniter-Google-Maps-V3-API-Library examples controller passes $data variable one view file
$this->load->library('googlemaps'); $this->googlemaps->initialize(); $data['map'] = $this->googlemaps->create_map(); $this->load->view('my_view', $data);
where my_view is:
<html> <head><?php echo $map['js']; ?></head> <body><?php echo $map['html']; ?></body> </html>
I have been trying to pass JS to my header view but with no success. My controller now:
$this->load->view('templates/header, $data'); $this->load->view('templates/navmenu'); $this->load->view('products/create', $data); $this->load->view('templates/footer');
and header view file:
<html> <head> <title>CodeIgniter Tutorial</title> <link rel = "stylesheet" type = "text/css" href = "<?php echo base_url(); ?>css/style.css"> <?php echo $map['js']; ?></head> <body>
Whatever I try to do (have spent a couple of hours) when I inspect the site I see that either JS or html part is not there.
I really liked that I had header.php view file that opened the <body>
tag. It is quite easy to mix different methods on one page.
What is the best practice for defining table indexes for entities supporting optimistic locking?
For sure, entity id has to be part of some index in DB to enable fast lookups by id. What about version column? Does it make sense to make it part of an index?
What if we do not define DB primary key, but create an index consisting of entity id + version column? Any risk of having two rows in DB with same entity id? Say two transactions persist two entities with the same entity id in parallel?
-13172159 0 Everytime I use content:"\005B" it becomes content:"�05B"I have a CSS text which is stored into mySQL database.
It's stored to ibf_css
table, css_text
column. css_text
collation is latin1_swedish_ci
.
It's the way the web application I'm using works. The CSS is stored into the database and loaded with css.php. It's not the usual style.css like Wordpress.
I have this in my CSS
#userlinks > span:before { content:"\005B";margin-right:4px; }
Everytime I save it into database (through the web application), it changed to this
#userlinks > span:before { content:"�05B";margin-right:4px; }
This happens with every line which has \0
. Like \005D
, \00D0
, etc. It changed to �05D
, �0D0
, etc.
If I edit with phpmyadmin, it's fine. But if I edit with the web application, it's troubled.
Help please? Much appreciated.
-4862923 0There is really no such simple concept as "next occurrences" in SQL because the sets/relations are by default unordered. You must explicitly state how the rows are to be ordered with an ORDER BY clause and then select from that ordered relation the row or rows you want (using TOP in SQL Server 2000). You don't appear to be sorting by C3 descending (since Jane has a 346 and you want her 245). What tacit order-by is implicit in your word "next" (i.e. you want the first row per distinct person) ? How do you wish to define first in this query? Do you want each person's lowest C3 value? If so you could group by person taking the min(c3) in an inline view and join that inline view to another inline view where you have selected the distinct C1.
-38616391 0I had the same issue and fix it as below :
With the update function, I'm currently getting the number of the affected rows. Is there any way I can get the key and values of that row instead of the count?
-25059775 0 R 3.1 sapply to a list of filesI want to parse the read.table()
function to a list of .txt files. These files are in my current directory.
my.txt.list <- list("subject_test.txt", "subject_train.txt", "X_test.txt", "X_train.txt")
Before applying read.table()
to elements of this list, I want to check if the dt has not been already computed and is in a cache directory. dt from cache directory are already in my environment()
, in form of file_name.dt
R> ls() "subject_test.dt" "subject_train.dt"
In this example, I only want to compute "X_test.txt" and "X_train.txt". I wrote a small function to test if dt has already been cached and apply read.table()
in case not.
my.rt <- function(x,...){ # apply read.table to txt files if data table is not already cached # x is a character vector y <- strsplit(x,'.txt') y <- paste(y,'.dt',sep = '') if (y %in% ls() == FALSE){ rt <- read.table(x, header = F, sep = "", dec = '.') } }
This function works if I take one element this way :
subject_test.dt <- my.rt('subject_test.txt')
Now I want to sapply
to my files list this way:
my.res <- saply(my.txt.list,my.rt)
I have my.res
as a list of df, but the issue is the function compute all files and does take into account already computed files.
I must be missing something, but I can't see why.
TY for suggestions.
-21779447 0 Scala: Thread safe mutable lazy Iterator with appendFor an immutable flavour, Iterator
does the job.
val x = Iterator.fill(100000)(someFn)
Now I want to implement a mutable version of Iterator
, with three guarantees:
fold
, foldLeft
, ..) and append
Iterator
should be destroyed.Is there an existing implementation to give me these guarantees? Any library or framework example would be great.
Update
To illustrate the desired behaviour.
class SomeThing {} class Test(val list: Iterator[SomeThing]) { def add(thing: SomeThing): Test = { new Test(list ++ Iterator(thing)) } } (new Test()).add(new SomeThing).add(new SomeThing);
In this example, SomeThing
is an expensive construct, it needs to be lazy.
Re-iterating over list
is never required, Iterator
is a good fit.
This is supposed to asynchronously and lazily sequence 10 million SomeThing
instances without depleting the executor(a cached thread pool executor) or running out of memory.
I am new to Appium IOS testing. I have some scripts which I am running with Eclipse and help of Appium on my iPad mini. The scripts were running quite good, but recently only I'm facing this issue.
Error launching instruments: Instruments crashed on startup
Any help is appreciated.
-23895858 0Since selectedItem
is an observable, you need to invoke it for accessing/changing it's data.
Try this:
<input type="text" id="textBoxAddressLine1" name="textBoxAddressLine1Name" data-bind="value: selectedItem() ? selectedItem().AddressLine1 : ''" />
And in your ViewModel:
selectItem: function(data) { this.selectedItem(data); }
-30344919 0 Version 2.6.7
Similar to what Aaron Geiser suggested, you can use customised form widgets to achieve this:
{# src/AppBundle/Resources/views/Form/fields.html.twig #} {% extends 'form_div_layout.html.twig' %} {%- block entity_widget -%} <div {{ block('widget_container_attributes') }}> {%- for n, child in form %} {{- form_widget(child, { 'entity': form.vars.choices[n].data }) -}} {{- form_label(child) -}} {% endfor -%} </div> {%- endblock %-} {%- block radio_widget -%} {# You now have access to entity #} {%- endblock -%}
-6154019 0 .live works when it shouldn't, and .bind doesn't work where it should I'm using this on an existing DOM element:
function questionsForm() { $("form[name='qc']:last").bind("focus", newTextLine); }
and it doesn't work, but when i replace .bind
with .live
it works this is the HTML where the handle is suppose to work:
<body> <div id="screen"> <div id="form"> <div id="insertQuestions"> <form id="qc" name="qc"> <h2>Create New Question!</h2> <div id="question">Question: <input type="text" name="Question" /></div><!--question--> <input type="submit" value="Submit" />
Why is it? jQuery 1.6
-31365498 0If its specifically an image element rather than a background-image property you want to be resized, you need to determine the proportions then assign the relative class to fit the screen
$(window).load(function() { $('.container').find('img').each(function() { var imgClass = (this.width / this.height > 1) ? 'wide' : 'tall'; $(this).addClass(imgClass); }) })
see http://jsfiddle.net/sjmcpherso/vhotnp1x/
-17140709 0While it is not free, there is the Data 24-7 service, which does have an API. Here is the link to their site:
-22659877 0 Form submit to another page and then review or write to a fileI have a script that users can submit certain data, and after a submit they can "review" the output and go back to previous page or submit to it again and there is my proble, the submitted page: How can I submit it again to write it to a file?
form.html
<form method="post" action="vaihe2.php"> <input name="laskuttaja" type="text" value="Nimi" size="25"> <input name="submit" type="submit" value="Lähetä" /> </form>
vaihe2.php
<? $laskuttaja = $_POST['laskuttaja']; $data = '<B>'.$laskuttaja.'</b>'; echo $data; ?>
So how can I post that $data to next page(vaihe3.php) with submit and let the script write it to a file. I know how php write file works but the post to third page is not working.
-24019383 0The method you want is toInt()
-- you have to be a little careful, since the toInt()
returns an optional Int.
let stringNumber = "1234" let numberFromString = stringNumber.toInt() // numberFromString is of type Int? with value 1234 let notANumber = "Uh oh" let wontBeANumber = notANumber.toInt() // wontBeANumber is of type Int? with value nil
-32901639 0 The one you have posted should work,
still try this, it should work
@Override public boolean onKeyDown(int keyCode, KeyEvent event) { final int keyCode = event.getKeyCode(); if (keyCode == KeyEvent.KEYCODE_MENU){ return true; } return super.onKeyDown(keyCode, event); }
-3108357 0 RTRIM removes characters specified in the second parameter from the end of the string specified in the first. Since the last character of 'VTR 564-31 / V16 H12 W08 E19 L14' is a '4', which is not specified in the second parameter ' /', there is nothing to trim.
It looks like you think it looks for the first occurence of ' /' in the first string and removes everything from there on, but that's not what it does.
For example:
SQL> select rtrim('AAABBBCCCBBBAAA','AB') from dual; RTRIM('AA --------- AAABBBCCC
RTRIM removed all the As and Bs from the end of the string.
Probably what you actually want is:
select substr(yourstring, 1, instr(yourstring, ' / ')-1) from dual;
i.e. use INSTR to locate the position of ' / ' and then SUBSTR to get just the part of "yourstring" before that.
-11129674 0 How the SVN handle the file access mode change?How the SVN handle the file access mode change?
For example:
I have a file foo.txt and its access mode is 644. Now I change it to 755 and use svn diff
, I got nothing. It looks like the SVN dosen't think anything change about that file. Then how could I generate patch for that case?
Thanks.
-30589701 0 how to undo event.preventdefault after some time on hyperlink using jquery or javascriptI want to my undo event.preventdefault after some time on hyperlink using jquery or javascript. when I click on my link then it should redirect me to the link given in href after some time because i want to send some ajax request in that time
Here is my HTML
<a href="http://localhost/rightA/en/admin/vacancies/activate/181999/1" class="btn-edit-vacancy"></a>
Here is my javascript
$('.vacancies_tbl').on('click', '.btn-edit-vacancy', function(e) { e.preventDefault(); var check = postuserWall(); alert(check); setTimeout(function(){window.location = $(this).attr('href'); }, 4000); });
the set timeout function is working but after some time it does not redirect me to desired link but it redirect me to this link
http://localhost/rightA/en/admin/vacancies/index/undefined
I have also tried the follwing
setTimeout(function(){$(this).trigger("click"); }, 5000); setTimeout(function(){alert('sdadsa'); $(this).unbind('click') }, 5000);
Here is my function postuserWall i am working on facebook javascript api
postuserWall(){ var body = 'Usama New Post'; FB.api('/me/feed', 'post', { message: body }, function(response) { if (!response || response.error) { console.log(response); alert('Error occured'); return false; } else { alert('Post ID: ' + response.id); return true; } }); }
the check show me undefined in the alert Thanks
-25381379 0Yes it's should be possible:
Try this:
findByProgrammeAndDirectorAndProgDateBetweenOrderByProgDateStartTimeAsc(String programme, String director, Date progStart, Date progEnd);
I have not tested the code, but according to things I've already done, it should work.
-29828601 0 E-goi what is the function name that makes the user 's email validation that will receive the newslettersim using e-goi and i whant to know if possibel what is the function name that makes the user 's email validation that will receive the newsletters.
tks
-11370116 0 jquery menu error displays block rather than inline on clickI've created a dropdown menu using jquery, it displays inline which is how i want it to display and then once clicked to display the other options. However once I click on the link it appears to put the LI tag back into blocks.
Anyone have any ideas as to why its doing this??
HTML
<!-- Navigation bar start --> <div id="navbar"> <!-- England nav bar start --> <li id="engmainnav"><a href="#">England</a> <ul id="engsubnav"> <li class="engli"><? echo $this->Html->link('News', array('controller'=>'Premiership', 'action' =>'news')); ?></li> <li class="engli"><? echo $this->Html->link('Results/Fixtures', array('controller'=>'Premiership', 'action' =>'resultsfixtures')); ?></li> <li class="engli"><? echo $this->Html->link('Teams', array('controller'=>'Premiership', 'action' =>'teams')); ?></li> <li class="engli"><? echo $this->Html->link('Table', array('controller'=>'Premiership', 'action' =>'table'));?></li> </ul> </li> <!-- England nav bar end --> <!-- La liga nav bar start--> <li id="sanav"><a href="#">Italy</a> <ul id="sasubnav"> <li class="sali"><? echo $this->Html->link('News', array('controller'=>'Italy', 'action' =>'news')); ?></li><br/> <li class="sali"><? echo $this->Html->link('Results/Fixtures', array('Italy'=>'Premiership', 'action' =>'resultsfixtures')); ?></li><br/> <li class="sali"><? echo $this->Html->link('Teams', array('controller'=>'Italy', 'action' =>'teams')); ?></li><br/> <li class="sali"><? echo $this->Html->link('Table', array('controller'=>'Seriea', 'action' =>'table'));?></li><br/> </ul> </li> </div> <!-- Navigation bar end -->
CSS
/* Navigation Style */ #navbar { background-color: #000666; margin: 0px 0px 0px 10px; } #engsubnav { list-style: none; margin:none; display: none; } #sasubnav{ list-style: none; margin:none; display: none; } .engli { margin: 0px 0px 0px -38px; display:block; } li { list-style: none; margin: 0px 0px 0px 10px; display:inline; } ul{ display:inline; }
Thanks in advance for any help
-21365866 0# first method : create a class with name customTextbox.cs and write down properties and events for textbox
public class customTextbox:TextBox { public customTextbox():base() { this.AcceptsReturn = true; this.AllowDrop = true; this.HorizontalAlignment = System.Windows.HorizontalAlignment.Left; //set your remaining propreties this.PreviewDragEnter +=customTextbox_PreviewDragEnter; this.PreviewDragLeave +=customTextbox_PreviewDragLeave; this.SelectionChanged += customTextbox_SelectionChanged; } void customTextbox_SelectionChanged(object sender, System.Windows.RoutedEventArgs e) { //code here } private void customTextbox_PreviewDragLeave(object sender, System.Windows.DragEventArgs e) { //code here } private void customTextbox_PreviewDragEnter(object sender, System.Windows.DragEventArgs e) { //code here } }
and in xaml
<Window x:Class="WpfApplication3.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525" xmlns:hp="clr-namespace:WpfApplication3"> <Grid Background="Transparent"> <Grid.RowDefinitions> <RowDefinition></RowDefinition> <RowDefinition></RowDefinition> <RowDefinition></RowDefinition> </Grid.RowDefinitions> <hp:customTextbox Height="100" Width="100" Grid.Row="0"></hp:customTextbox> <hp:customTextbox Grid.Row="1" ></hp:customTextbox> <hp:customTextbox Grid.Row="2" ></hp:customTextbox> </Grid>
#second method:create a usecontrol like this(http://prntscr.com/2mren4) and replace usercontrol with textbox like below
<TextBox x:Class="WpfApplication3.CustomTB" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300"> <!--set all properties and event you required inside textbox-->
and in .cs file use textbox instead of usercontrol like below
public partial class CustomTB : TextBox { public CustomTB() { InitializeComponent(); } }
and in another window add
<Window x:Class="WpfApplication3.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525" xmlns:hp="clr-namespace:WpfApplication3"> <Grid Background="Transparent"> <Grid.RowDefinitions> <RowDefinition></RowDefinition> <RowDefinition></RowDefinition> </Grid.RowDefinitions> <hp:CustomTB Grid.Row="0"/> </Grid>
-120908 0 LabVIEW holds Excel Reference I try to open and excel reference in LabVIEW and then close it after sometime. But the LabVIEW keeps holding the reference and does not release it unless I close the VI. Why is this happening? Is there anyway to force it to release the Reference?
I am checking the error out for any errors. But it is not throwing up any errors.
-40209680 0 J2ObjC with source jar fileI need to translate itext source jar to objective c using J2ObjC. I use the Xcode Build rules at here . But when I add this script
"${J2OBJC_HOME}/j2objc" --build-closure -d ${DERIVED_FILES_DIR} -sourcepath "${PROJECT_DIR}/" --no-package-directories "${PROJECT_DIR}/Classes/Othello/Engine/itext-2.1.7-sources.jar" ${INPUT_FILE_PATH};
This project was built and run successfully without my script. Please help me Thanks
-22282541 0 dropdown menu like http://www.teslamotors.com/My clients request is to make their website menu like http://www.teslamotors.com/. So far I have done is the following
HTML
<div id="header"> <div id="main-menu-back" class="short"><!-- Begin: main-menu-back --> <div id="main-menu-wrapper"> <ul id="main-menu"> <li id="about"><a href="about.php">About Us</a></li> <li id="service"><a href="service.php">Services</a></li> <li id="contact"><a href="contact.php">Contact</a></li> </ul> <div id="logo"><!-- Begin: logo --> <h1><a href="index.php"><img src="images/interface/logo_9.jpg" width="90" height="80" alt="img" /></a></h1> </div> <!-- End: logo --> </div> </div><!-- End: main-menu-back --> <div id="menu_slider" style="top: -55px;"> <div id="menu_slider_wrapper"> <div id="menu01" class="submenu" style="left: 100px;"> <ul> <li><a href="#">Office and Home Security Systems</a></li> <li><a href="#">Office and Home Interiors and Electrical Wiring</a></li> <li><a href="#">Biogas Power Plantations/ Solar Power Plantations</a></li> <li><a href="#">Vehicle Tracking Devices/ Vehicle Security System</a></li> <li><a href="#">Fire Alarm and Fire Hydrant Systems/Related Equipment Supply and Installations</a></li> <li><a href="#">Ventilation Systems/Related Equipment Supply and Installations</a> </li> </ul> </div> <div id="menu02" class="submenu" style="left: 300px;"> <ul> <li><a href="contact.php?type=location">Our Location</a></li> <li><a href="contact.php?type=contact">Contact Us</a></li> </ul> </div> </div> </div> <div id="header_bottom"> </div> </div>
CSS
#header { height: 90px; position: relative; width: 100%; z-index: 102; } #main-menu-back.short { background: url(../images/interface/header-top-back-short.JPG) repeat-x; height: 59px; } #main-menu-back { background: url(../images/interface/header-top-back.JPG) repeat-x scroll center top #DDDDDD; box-shadow: 0 1px 8px 1px #6D6B6B; font-size: 14px; font-style: normal; font-weight: 700; height: 90px; min-width: 960px; position: absolute; text-transform: uppercase; width: 100%; z-index: 3; } #main-menu-back.short #main-menu-wrapper { height: 62px; height: 62px; margin: 0 auto; position: relative; width: 960px; } #logo{ display: inline; width: 78px; position: absolute; left: 825px; z-index: 4 !important; } #logo h1 a img{ -webkit-box-shadow: 0px 0px 15px 0px rgba(0,0,0,0.75); -moz-box-shadow: 0px 0px 15px 0px rgba(0,0,0,0.75); box-shadow: 0px 0px 15px 0px rgba(0,0,0,0.75); } #header_bottom { background: url(../images/interface/header-bottom-back.png) repeat-x; width: 100%; height: 30px; text-align: left; -webkit-box-shadow: 0px 6px 3px 0px rgba(0,0,0,0.60); -moz-box-shadow: 0px 6px 3px 0px rgba(0,0,0,0.60); box-shadow: 0px 6px 3px 0px rgba(0,0,0,0.60); position: absolute; top: 59px; } ul#main-menu { margin:0; position: absolute; top: 30px; } ul#main-menu li { padding: 0 0 0 0px; list-style: none; margin: 2px 70px 0 0; display: inline; background: transparent; } ul#main-menu li a { color: #707070; font-size: 15px; font-weight: bold; text-shadow: 0 1px 0 #FFFFFF; } ul#main-menu li:hover a { color: #B80007; } #menu_slider { background: url(../images/interface/submenu-back.JPG) repeat-x; position: absolute; width: 100%; height: 111px; box-shadow: 0 1px 8px 1px #6D6B6B; overflow: hidden; z-index: 2 !IMPORTANT; } #menu_slider_wrapper { margin: 0 auto; position: relative; width: 960px; } #menu_slider div.submenu { position: absolute; top: 20px; vertical-align: top; text-align: left; } #menu_slider div.submenu ul { display: inline; float: left; min-width: 140px; padding-right: 10px; } #menu_slider div.submenu li { list-style-type: none; } #menu_slider div.submenu li a { color: #666666; font-size: 12px; font-style: normal; font-weight: 600; text-decoration: none; text-transform: uppercase; }
JS
$("ul#main-menu li").mouseenter(function () { var hoverCntrlId = $(this).attr("id"); console.log(hoverCntrlId); if (hoverCntrlId == "contact") { $("div#menu01").hide(); $("div#menu02").show(); } else if (hoverCntrlId == "service") { $("div#menu01").show(); $("div#menu02").hide(); } $('#menu_slider').animate({ top: '61px' }, 1000, function () { $('#menu_slider').slideDown(1000); }); }); $('ul#main-menu li, #menu_slider').mouseleave(function () { var hoverCntrlId = $(this).attr("id"); var msPosition = $("#menu_slider").attr("top"); if (msPosition == "61px") { $('#menu_slider').stop().animate({ top: '-55px' }); } if (hoverCntrlId == "menu_slider") { $('#menu_slider').stop(); $('#menu_slider').animate({ top: '-55px' }, 1000, function () { $('#menu_slider').slideUp(1000); }); } });
I am able to slide up and down the div containing submenu but animation problem occurs my mouse leaves menu_slider and enters #main-menu li, then the animation occurs twice. I am not able resolve the problem. Can anyone help.
-13565936 0 core data model mapping of attribute based on attribute of other entityi have a data model with two entities with a one-to-many relationship
Person { name:string, type:number, files<-->>File } File { reference:string, person<<-->Person }
i have updated the data model, removed the type attribute from Person, but the reference attribute of the File is dependent on the type of the Person : if type is 0, then reference must be "A", if type is 1, then the reference must be "B".
I cannot find a solution that can perform this mapping. Any idea's ?
EDIT :
I found a solution by creating two entity mappings, using the filter predicates to distinguish between type 0 and 1. For entity mapping with Person.type == 0, i set a hard coded attribute mapping of "A", and similar for type == 1>
-10066846 0Should be .index(i)
- parens, not brackets.
So only a quick question here regarding a switch case with a char.
So:
char c = a.charAt(i); switch(c){ case 'a': System.out.print("This is an a"); case ''': System.out.print("How can one get this character checked in the case?); }
So how can a case check for a letter ' when the style for checking the char in the case is ' ' ?
Help will be much appreciated.
-19674209 0 Clean rubbish Autofac configurations?Just wondering whether there is a good way to find out rubbish configurations in Autofac modules. I mean, while the project is growing bigger and bigger with lots of refactoring done, there could be some classes become unused but they are still registered in the module configurations. Those rubbish classes could get hidden from Reshaper because it is used in the configuration code. I just don't like to go through every line in the configuration code to find whether an interface or class is never used any more and delete them manually.
Would be nice if there is good idea to find out all those rubbish automatically. Please throw in your brilliant thoughts. Thanks.
-10107102 0This is not a complete answer in any way, but I did find it helpful to use this regular expression:
// *\#if|\#el|\#en
which searches for // followed by any amount of whitespace (including none) and then either #if, #el or #en (to exclude the possibility of throwing up all the pragma's etc - this could definitely be improved upon.
luckily I only have to search in my open documents, which is several hundred but it could be A LOT worse. Hope this helps someone in the future, this is horrible!
-17330067 0Sure.
You need a web server and a database on the back end.
Since you feel comfortable with Java, JSP/HTML would probably be an ideal solution.
IMHO...
-6354196 0 how to divide QGridLayout into rows and columns at Design Time in QT?how to divide QGridLayout into rows and columns at Design Time in QT ?
I want to design one form where i want to have 2 columns and 7 rows . I am designing using QTCreator but i am not getting any option of giving rows/columns.
It shows only these properties
If I understood it correctly you want to reference the fragment created by heat ($(TargetDir)$(ProjectName).wxs
) in your generic WiX source file?
If this is the case you just have to add a ComponentGroupRef
-tag below your Feature
-element (instead of a ComponentRef
-element you would use normally). As Id
for the elemenet you have to use the name of the ComponentGroup
that you used in the heat-commandline, harvestedComponents
in your example. E.g.
<Feature Id="MyFeature" ...> ... <ComponentRef Id="aNormalComponentFromTheCurrentFile" ... /> ... <ComponentGroupRef Id="harvestedComponents" /> </Feature>
Or did I miss the point?
-38124033 0Should use GCM high-priority messages to wake the app and access the network. Example of High priority GCM message:-
{ "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...", "priority" : "high", "notification" : { "body" : "This week’s edition is now available.", "title" : "NewsMagazine.com", "icon" : "new", }, "data" : { "volume" : "3.21.15", "contents" : "http://www.news-magazine.com/world-week/21659772" } }
See the "priority" key has value "high", this will awake the device and gcm message will be delivered instantly and it wont crash.
Check this out for more information https://developer.android.com/training/monitoring-device-state/doze-standby.html#whitelisting-cases
-12777200 0 Weird issue when looping using the Do While in CI'm running into a weird issue when I try and move my Do loop, or add another loop to nest it. I place the DO where you see it below, it loops through fine:
{ float numbers[MAX_DATA]; printf("Please Eneter the Amount of Numbers You Would Like to Use\n"); scanf("%d",&amount); if (amount>MAX_DATA) { printf("Your entry was too big"); } else { input(numbers,amount); do { printf("\nStatistical Calculator Menu\n"); printf("\n(1) Mean\n(2) Standard Deviation\n(3) Range\n(4) Restart/Exit\n"); scanf("%d",&input2); if (input2==1) { mean(numbers,amount); } else if (input2==2) { standard(numbers,amount); } else if (input2==3) { range(numbers,amount); } else if(input2==4) { printf("Would You Like to (5)Restart or (6)Quit?"); scanf("%d",&input2); } } while(input2!=4); } getch(); return 0; }
But if I place it here or add an additional do loop to nest it, I get a "expect while before getch" error.
{ int amount=0; int input2; do { float numbers[MAX_DATA]; printf("Please Eneter the Amount of Numbers You Would Like to Use\n"); scanf("%d",&amount); if (amount>MAX_DATA) { printf("Your entry was too big"); } else { input(numbers,amount); printf("\nStatistical Calculator Menu\n"); printf("\n(1) Mean\n(2) Standard Deviation\n(3) Range\n(4) Restart/Exit\n"); scanf("%d",&input2); if (input2==1) { mean(numbers,amount); } else if (input2==2) { standard(numbers,amount); } else if (input2==3) { range(numbers,amount); } else if(input2==4) { printf("Would You Like to (5)Restart or (6)Quit?"); scanf("%d",&input2); } } while(input2!=4); } getch(); return 0; }
Why do I get this error?
-2369353 0 How to Display a keyboard in an Android Application?Possible Duplicate:
How to Trigger the soft keyboard?
Any one please help me to display a keyboard in my app. I want to show my keyboard when i click on the textfield
-27398390 0As a matter of fact, OR Operator for two NOT EQUALS is always TRUE ( check boolean table for this) and the conditional statement "if" checks for TRUE or FALSE, hence your code will always return TRUE
Use something like
if(tanksize!=1 && tanksize!=2){ # Your code }
-32500106 0 vba lookup cell value on another worksheet and rename value? How to get the value from a cell on an active sheet and look it up on a non active sheet and then rename the value?
Dim rw As Long rw = ActiveCell.Row If Sheets("Home").Range("D" & rw).Value = "Tender" Then With Worksheets("Time Allocation").Columns("B:B") Set cell = .Find(What:=.Range("B" & rw).Value, After:=Range("B" & rw), LookIn:=xlFormulas, _ LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=False, SearchFormat:=False) If Not cell Is Nothing Then cell.Value = "test" Else cell.Value = "test" End If End With End If
I have tried using cell.value = "test" but this causes an error: object variable or block with variable not set
please can someone show me where I am going wrong?
-12517350 0Here is one way to copy n
double
s into a vector:
#include <vector> #include <iostream> #include <algorithm> #include <iterator> int main() { unsigned n; std::vector<double> xvec; std::cin >> n; xvec.reserve(n); std:generate_n(std::back_inserter(xvec), n, []() { double d; std::cin >> d; return d; }); std::copy(xvec.begin(), xvec.end(), std::ostream_iterator<double>(std::cout, " ")); std::cout << "\n"; return 0; }
Note: This alternative using std::copy_n
won't work:
std::copy_n(std::istream_iterator<double>(std::cin), n, std::back_inserter(xvec));
This actually reads n+1
elements but only copies n
of them (at least on g++ 4.6.3).
Note 2: Limiting the answer to C++98, here is one possible solution:
double GetD() { double d; std::cin >> d; return d; } ... std:generate_n(std::back_inserter(xvec), n, GetD);
-1023073 0 You can save keystrokes by holding the Ctrl key and using the arrow keys. Instead of moving one character, it moves one word at a time. This also works when backspacing. So Ctrl-Backspace will delete the entire word instead of just the last character.
-26140875 0It's really difficult to guess what's the issue there without more complete example. One thing that could be the reason is empty cells which are collapsing. Also I've moved the innerHTML to html variable which is appended just once..
to compensate that try this code which is adding a non breaking space to empty cells:
var Htmltable = document.getElementById('table'); var day = 1; var html = ''; for(i = 1; i <= 6; i++){ //weeks in a month (rows) html += '<tr>'; for(j = 0; j <= 6; j++){ //7 days in a week (coloumns) html += '<td>'; if(day <= wca.totDayInMonth){ html += day; day++; } else { html += " "; } html += '</td>'; } //if day > totDayMonth - stop making line html += '</tr>'; } Htmltable.innerHTML += html;
-25345627 0 Creating thread-safe non-deleting unique filenames in ruby/rails I'm building a bulk-file-uploader. Multiple files are uploaded in individual requests, and my UI provides progress and success/fail. Then, once all files are complete, a final request processes/finalizes them. For this to work, I need to create many temporary files that live longer than a single request. Of course I also need to guarantee filenames are unique across app instances.
Normally I would use Tempfile
for easy unique filenames, but in this case it won't work because the files need to stick around until another request comes in to further process them. Tempfile
auto-unlinks files when they're closed and garbage collected.
An earlier question here suggests using Dir::Tmpname.make_tmpname
but this seems to be undocumented and I don't see how it is thread/multiprocess safe. Is it guaranteed to be so?
In c I would open the file O_EXCL
which will fail if the file exists. I could then keep trying until I successfully get a handle on a file with a truly unique name. But ruby's File.open
doesn't seem to have an "exclusive" option of any kind. If the file I'm opening already exists, I have to either append to it, open for writing at the end, or empty it.
Is there a "right" way to do this in ruby?
I have worked out a method that I think is safe, but is seems overly complex:
# make a unique filename time = Time.now filename = "#{time.to_i}-#{sprintf('%06d', time.usec)}" # make tempfiles (this is gauranteed to find a unique creatable name) data_file = Tempfile.new(["upload", ".data"], UPLOAD_BASE) # but the file will be deleted automatically, which we don't want, so now link it in a stable location count = 1 loop do begin # File.link will raise an exception if the destination path exists File.link(data_file.path, File.join(UPLOAD_BASE, "#{filename}-#{count}.data")) # so here we know we created a file successfully and nobody else will take it break rescue Errno::EEXIST count += 1 end end # now unlink the original tempfiles (they're still writeable until they're closed) data_file.unlink # ... write to data_file and close it ...
NOTE: This won't work on Windows. Not a problem for me, but reader beware.
In my testing this works reliably. But again, is there a more straightforward way?
-28453472 0I solved the problem . But there is a bunch of work to do . So I write down here one by one ;
Session.getServletContext().getRealPath("Index.jsp"); is not true . But not the main problem . in the brackets we must write a folder not a file to find the parent folder. After correct this, it will return null again . because Java EE 7 does not support getRealPath() method. but at the end this will be already solved by changing the version.
On Netbeans IDE , at toolbar , tools >> Servers , I removed the tomcat server. and also uninstall the Apache Tomcat8 that comes with Netbeans8 because there may be a version problem as I read from the forums.
And I download Apache Tomcat7 from the official site of apache and installed service.
I configured tomcat-users.xml config file for admin priviledges.
And I add the Tomcat7 server at netbeans from the same toolbar (tools >> Servers)
What I saw was in the project the server was not there. I went inside project properties , from the menu > Run , and Server combo-box was empty. Because I was using Java EE7 and Tomcat7 needs at least Java EE6. So I needed to change the java ee version.
What to do : Click the files tab near projects tab. Under nbproject folder , select j2ee.platform , for Tomcat7 change the platform to 1.6 (Tomcat6 > Jave EE 1.5). than make a "clean and build" on the project . Now the server will come at Project > properties > Run > Servers
-" '127.0.0.1*' is not recognized as an internal or external command "
to correct that : Error starting Tomcat from NetBeans - '127.0.0.1*' is not recognized as an internal or external command
-25355329 0The following demonstrates how to 1) select a sprite that is within a specified distance from a touch event and 2) drag and drop the selected sprite to a new location.
@interface MyScene() @property (weak) SKSpriteNode *selectedNode; @end @implementation MyScene -(id)initWithSize:(CGSize)size { if (self = [super initWithSize:size]) { /* Setup your scene here */ self.backgroundColor = [SKColor colorWithRed:0.15 green:0.15 blue:0.3 alpha:1.0]; // Add three sprites to scene SKSpriteNode *sprite = [SKSpriteNode spriteNodeWithColor:[SKColor blueColor] size:CGSizeMake(32, 32)]; sprite.name = @"Blue"; sprite.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame)-64); [self addChild:sprite]; sprite = [SKSpriteNode spriteNodeWithColor:[SKColor redColor] size:CGSizeMake(32, 32)]; sprite.name = @"Red"; sprite.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame) + 64); [self addChild:sprite]; sprite = [SKSpriteNode spriteNodeWithColor:[SKColor greenColor] size:CGSizeMake(32, 32)]; sprite.name = @"Green"; sprite.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame)); [self addChild:sprite]; } return self; } #define kRadius 64 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { _selectedNode = nil; CGFloat minDistance = kRadius+1; for (UITouch *touch in touches) { CGPoint location = [touch locationInNode:self]; for (SKSpriteNode *node in self.children) { CGFloat dx = location.x - node.position.x; CGFloat dy = location.y - node.position.y; // Compute distance from sprite to tap point CGFloat distance = sqrtf(dx*dx+dy*dy); if (distance <= kRadius) { if (distance < minDistance) { // Select the closest node so far _selectedNode = node; minDistance = distance; } } } } } - (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event { UITouch *touch = [touches anyObject]; CGPoint location = [touch locationInNode:self]; if (_selectedNode) { // Move selected node to current touch position _selectedNode.position = location; } } - (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { // Unselect node _selectedNode = nil; } - (void) update:(CFTimeInterval)currentTime { /* Called before each frame is rendered */ } @end
-38550170 0 The text is only showing up in white when you hover over the link tage: <a>
, not the whole list item <li>
.
I think a better way to fix this is to make the link a block element, filling the whole list item space. If people hover anywhere over the list, they'll not only see the text in white, they'll also be able to click anywhere on the item.
Here's a rework:
#menu { margin-top: 10px; } #menu li { list-style:none; } #menu li a { font-family: 'Open Sans', sans-serif; font-weight: 400; font-size: 13px; padding:5px; text-decoration: none; line-height: 22px; width: 100%; color: #565656; border-bottom: 1px solid #e1e1e1; display:block; } #menu li a:hover { background-color: #c0392b; color: #FFF; }
<ul id="menu"> <li><a href="#">Strona główna</a></li> <li><a href="#">Historia szkoły</a></li> <li><a href="#">Absolwenci</a></li> <li><a href="#">Dokumenty szkoły</a></li> <li><a href="#">Ewaluacja wewnętrzna</a></li> <li><a href="#">Zasady rekrutacji</a></li> <li><a href="#">Nauczyciele</a></li> <li><a href="#">Samorząd Uczniowski</a></li> <li><a href="#">Rada Rodziców</a></li> <li><a href="#">Kierunki i wychowawcy klas</a></li> <li><a href="#">Kalendarz roku szkolnego</a></li> <li><a href="#">Profilaktyka</a></li> <li><a href="#">Kalendarz imprez i uroczystości</a></li> <li><a href="#">Olimpiady, konkursy, zawody</a></li> <li><a href="#">Koła zainteresowań</a></li> <li><a href="#">Matura</a></li> <li><a href="#">Egzamin zawodowy</a></li> </ul>
You can use array indexers in your bindings, so you can access the first index with $data[0]
:
<ul data-bind="foreach: city"> <li> <span data-bind="text: $data[0]"> </span> </li> </ul>
Working CodePen
A more view model oriented approach would be to create a proper "city" object which has a name
property:
var City = function(data) { this.name = data[0]; this.coords = data[1]; }
And use this City
when creating a state
:
var state = function(name, city) { this.name = name; this.city = ko.observableArray(city.map(function(c){ return new City(c)})); }
And your binding could look like this:
<ul data-bind="foreach: city"> <li> <span data-bind="text: name"> </span> </li> </ul>
Sample CodePen
-32747557 0try this , for first selected by defult you can use $first
<select ng-model="selectedRole"> <option ng-repeat="name in roleNames " ng-selected="$first" value="{{name}}">{{name}}</option> </select>
-31659897 0 R shiny reactive table, render plot can not work everyone. I am very new to shiny. I would like to plot a pie chart based on a filter data frame. Here is my data frame:
Duration Received Name Status 1 month 01/14/2014 Tim Completed 1 month 02/12/2014 Chris Completed 2 months 01/08/2015 Anna Completed 1 month 06/25/2014 Jenifer Completed 2 months 05/14/2015 Ruby Completed more than 3 months 11/05/2014 David Pending 2 months 05/12/2015 Anna Completed 1 months 03/26/2015 David Completed ... ...
There may be more than 500 lines in the data frame
First, I tried to subset the data frame by Received Date. And plot the Duration Freq in pie chart. For example, I would like to choose all records after 12/31/2014. So I can select my Received Date. Then, table() Duration column in the subset data frame. Last, plot the pie chart.
My problem is when I change the date Rang of the Received date, my pie plot keep the consistent, never update. Can anyone help me to debug my script and tell me why? Thank you
Here is my code: ui.R
library(shiny) library(ggplot2) ggpie <- function (dat, by, totals) { ggplot(dat, aes_string(x=factor(1), y=totals, fill=by)) + geom_bar(stat='identity', color='black') + guides(fill=guide_legend(override.aes=list(colour=NA))) + coord_polar(theta='y') + theme(axis.ticks=element_blank(), axis.text.y=element_blank(), axis.text.x = element_blank(), axis.title=element_blank()) + scale_y_continuous(breaks=cumsum(dat[[totals]]) - dat[[totals]] / 2, labels=dat[[by]]) } shinyUI(fluidPage( headerPanel("My App"), sidebarPanel( dateRangeInput("dates", label = h3("Received Date Range"), start = "2013-01-01", end = as.character(Sys.Date()) ) ), mainPanel( plotOutput("Duration"), tableOutput("test") ) ))
server.R
library(shiny) library(ggplot2) ggpie <- function (dat, by, totals) { ggplot(dat, aes_string(x=factor(1), y=totals, fill=by)) + geom_bar(stat='identity', color='black') + guides(fill=guide_legend(override.aes=list(colour=NA))) + coord_polar(theta='y') + theme(axis.ticks=element_blank(), axis.text.y=element_blank(), axis.text.x = element_blank(), #axis.text.x=element_text(colour='black',angle=45, size=10, vjust=0.5), axis.title=element_blank()) + scale_y_continuous(breaks=cumsum(dat[[totals]]) - dat[[totals]] / 2, labels=dat[[by]]) } shinyServer(function(input, output) { #table newData= reactive({ data1 = subset(data, input$dates[1]<=data$Received && data$Received<=input$dates[2]) data2 = as.data.frame(table(data1$Duration)) }) output$test<- renderTable({ newData() }) output$Duration<-renderPlot({ ggpie(newData(), by='Var1', totals="Freq") + ggtitle("Duration")+ scale_fill_discrete(name="Duration") }) })
-16916130 0 $f->fetch() moves the internal result pointer to the next value(if exists) thats why you get all the values when you call it in while();
-6505320 0In this case - and because I smell homework - you should use one base class Player
and a subclass for each player type.
Example:
public abstract class Player { // some attributes and methods all players share public abstract String whatTypeOfPlayer(); }
public WicketPlayer extends Player { @Override public String whatTypeOfPlayer() { return "Wicket Player"; } }
Bonus - then I'd use a factory to create players:
public PlayerFactory { enum PlayerType {WICKETPLAYER, BATSMAN, BOWLER, ALLROUNDER} public static Player createPlayer(PlayerType type, String name) { switch(type) { case WICKETPLAYER : return new WicketPlayer(name); //... } } }
-31734653 0 First of all: "Free" = 0, "Normal" = 1, "Featured" = 0. <-- Featured would be 3 Im right?
Theres nothing wrong with you saving the three different objects in three different classes, actually I personally think thats the best option, rather than just puting everything together in one class and make a mess.
-25140795 0I can obtain this information from qstat -j <job_id>
.
For example, submit some array jobs:
echo "sleep 60" | qsub -t 1-200
Use qstat to extract total tasks:
qstat -j <job_id> | grep tasks
grep
returns the following:
job-array tasks: 1-200:1
-15711676 0 One approach is two stages of aggregation
select browser, os, version, count(*) from (select order_id, max(case when `key` = 'browser' then `value` end) as browser, max(case when `key` = 'os' then `value` end) as os, max(case when `key` = 'version' then `value` end) as version from order_params op group by order_id ) p group by browser, os, version
If you actually want the string that you have, you can concat things together:
select concat(coalesce(concat('browser ', browser), ''), coalesce(concat('os ', os), ''), coalesce(concat('version ', version), ''), count(*) from (select order_id, max(case when `key` = 'browser' then `value` end) as browser, max(case when `key` = 'os' then `value` end) as os, max(case when `key` = 'version' then `value` end) as version from order_params op group by order_id ) p group by os, browser, version
-26025594 0 PhoneGap remote build ios gives [Error: ENOENT] Just want to upload my project to phonegap build(build.phonegap.com), and when I run this command in myproject folder:
phonegap remote build ios
It gives an error:
{ [Error: ENOENT, open '/Users/myname/Sites/myproject/www/config.xml'] errno: 34, code: 'ENOENT', path: '/Users/myname/Sites/myproject/www/config.xml' } [error] ENOENT, open '/Users/myname/Sites/myproject/www/config.xml'
Which means the path to config.xml file is incorrect I guess, but I double checked it, the config.xml file is in the right path. Can anyone help me with this please? How do I sorted it out?
-37445324 0Regarding your 2nd question: If you need cashing for fullName
, you may and should do it explicitly:
class Client { val firstName: String val lastName: String val fullName = "$firstName $lastName" }
This code is equivalent to your snipped except that the underlying getter getFullName()
now uses a final private field with the result of concatenation.
I have a navigation that I am animating. However the text jumps because it shows before the animation is done, so I want to set a delay of 300ms
before triggering the display:inline-block
. I cant get it to work? Any ideas?
$(".left-navigation ul li").hover(function(){ $(this).stop().animate({'width': '100%'}, 200); $(this).find("span.nav-text").delay(300).css("display", "inline-block"); }, function(){ $(this).stop().animate({'width': '35px'}, 200); $(this).find("span.nav-text").css("display", "none"); });
-29921172 0 Worked it out. I needed the following pattern:
(?<date>(?<day>\d{1,2})-(?<month>\d{1,2})-(?<year>(?:\d{4}|\d{2}))\s(?<time>(?<hour>\d{2}):(?<minutes>\d{2}):(?<seconds>\d{2})(?<milli>\.?\d{0,3})))\s(?<logEntry>.*)
-9952409 0 It's a shame I didn't see this sooner.
At one time I had a branch of the Cake build tool that had almost full Ivy support. I again have a need for this, but since Cake is now deprecated I've had to branch leiningen. I only just started but it works for resolving (including configurations, exclusions, branches, etc).
Right now it's based of the lein2 preview release. I'm not sure how much more work I'll put into it though. I'd like to create a complementary lein-ivy plugin that could add the features of the old Cake version (publishing, dependency reports, multiple publications, etc).
-18935675 0A label followed by an inline coment
Yes, Java has label
public static void main(String[] args) { hello: }
And of course online comments
public static void main(String[] args) { int i; // this is a comment. }
-37051604 0 To the best of my knowledge the issue comes from the position=position_dodge
.
Here you specify the distance between centers is lower than the width of your bars. You should try with position="dodge"
instead.
You should be able to use Grails filters to do this:
class TimeFilters { def filters = { timeCheck(controller: '*', action: '*') { before = { model -> ... } after = { model -> ... } } } }
If you look at the source code of java.util.Date
:
public Date() { this(System.currentTimeMillis()); }
So this is just a performance overhead to create and get time: new Date().getTime()
I've added a custom management command to an application developed using Django 1.6.11. This command, let's call it initdb
, performs a set of particualr actions:
syncdb
In other words, it's very handy for quick database initialization from total zero.
Now, I'm migrating to Django 1.8.5 and one thing I've noticed is that, before almost every command, Django automatically executes check
command from new system check framework, which among other stuff checks if database/user form settings.py
exist. That leads to a situation when I can't run my custom command because automatic check throws exceptions that there is no access to database (indeed, my custom command should create it).
Is there any way to force skipping automatic check
that Django makes, at least in custom management command?
I have the same result on my android device which means your device or computer works with 64 bits floating point representation. For correct result, you must limit displaying your result to 15 digits. I found this workaround : running :
var res = 1 - 0.8; var roundedRes = parseFloat(res.toPrecision(15) ) ; alert ("res="+res+"\n" + "roundedRes="+roundedRes);
ouputs : res=0.19999999999999996 roundedRes=0.2
-24425867 0You will be able to achieve this if you set a max-width value to the desired cells you want fixed.
Please note the fixed width must be in pixels so the cell knows when to cause overflow.
(However if your table has a fixed width this is not a problem).
.a25{max-width:75px;}
Either overflow / text-overflow or text-wrap must also be applied to designate what the text should do. This is already present in your example. (As below)
(Note .a25 is incorrectly .a24 in your demo)
FULL CSS (As per your demo)
body{width:750px} table{ display:block; border-width: 1px; border-style: solid; border-collapse: collapse; width: 100%; overflow: hidden; } #fx{ table-layout: fixed; overflow: hidden; } #fx2{ table-layout: fixed; } tr, th, td{ border-width:1px; border-style: solid; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } th{ width: 5%; } .over{overflow: hidden;} .a25{width:10%;max-width:75px;} .a75{width:60%} .he{height:130px;} .rotate{-webkit-transform:rotate(270deg);} .rr{height:-1px;width:130px;margin-left:-30px;}
CSS (CLEAN VERSION)
table{ table-layout: fixed; border-collapse: collapse; width: 100%; } tr, th, td{ border:1px solid #888; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .w25{width:10%;max-width:75px;} .w75{width:60%} .h130{height:130px;}
This example is currently a fluid table with overflow.
To fixed cell size either replace max-width with width or replace table width with fixed value.
-5933580 0 How can I reintegrate an already reintegrated and rolled-back branch in SVN?We did following ugly thing:
So, how can we achieve another reintegrate
?
What did I try so far?
trunk
(which should work, as it diffs the files with no svn only...)edit:
merge-infos for trunk do not show any merged revisions of the desired branch (as I've rolled them back with r101)
-18423303 0 how to determine the number of numbers in a text file in CI'm reading a text file of numbers and I want to get the sum of this number, how can I determine the number of numbers in the text file."my text file is consist of one line"
this is the code I have written, how to determine number of numbers in the text file to put it instead of the variable "number of numbers" in the secondline of code
int main() { FILE *file = fopen("numbers.txt", "r"); int integers[number of numbers]; int i=0; int j=0; int num; while(fscanf(file, "%d", &num) > 0) { integers[i] =num; printf("%d",integers[i]); printf("\n"); i++; } int sum=0; for(j=0;j<sizeof(integers)/sizeof(int);j++) { sum=sum+integers[j]; } printf("%d",sum); printf("\n"); fclose(file); return 0; }
-843353 0 Windows Mobile Pocket PC how to mute | unmute (microphone) How can i mute | unmute a windows mobile pocket pc device (i'm using symbol MC70) programmatically? Waht API do I need to use?
-26512972 0Yes they are kind of Observer pattern, or a specialization of this pattern.. However i found in a blog about Android-useful design patterns and they are mentioning Adapter Pattern as a separate thing.
-37380984 0 Firebase Facebook Login from Ionic (Cordova) app in iOS EmulatorI'm configuring my Ionic app to work with Facebook Authentication. Everything seems about right when I debug the app from my browser; however, when I deploy the app to the iOS emulator I get the following message in the safari console:
"This domain is not authorized for OAuth operations for your Firebase project. Edit the list of authorized domains from the Firebase console."
I suppose that makes sense. I went over to the Firebase console to add an additional domain name which my emulator was running on, but have no idea what the domain would be. I even tried logging "window.location.hostname" but it came up as completely blank when I run the app from the emulator (it's localhost when I run it from the browser). Any idea how to allow the emulator to utilize Firebase authentication? Thanks a bunch. Please let me know if I can provide additional details.
-10103712 0It's not top-left, top-right
but top left, top right
.
Instead of assigning the actual values to the attribute properties, assign keys for resource strings. Then, you can use a custom ModelMetadataProvider
that is aware of the localization context and will provide the appropriate string. To get a better solution, you can make your custom ModelMetadataProvider
infer conventions, (which cuts down on the need for verbose attributes).
Phil Haack has a blog article called Model Metadata and Validation Localization using Conventions that explains how this works. There is also a corresponding NuGet package called ModelMetadataExtensions with source code available on github at https://github.com/Haacked/mvc-metadata-conventions .
As a side note, I'd recommend reviewing some of the awesome answers I got on an old question of mine: Effective Strategies for Localization in .NET. They don't specifically address your question, but will be very helpful if you are working on a multilingual .NET app.
-13677252 0 How to check if EOF (after using getline)See update below!
My code (now I included more):
while(getline(checkTasks, workingString)){ countTheDays = 0; // Captures a clean copy of the line in tasks.dat in it's entirety, stores in workingString. char nlcheck; checkTasks.get(nlcheck); if(nlcheck == '\n'){ } else{ checkTasks.unget(); //getline(checkTasks, workingString); // Breaks that line up into more usable pieces of information. getline(check2,tName, '\t'); getline(check2,tDate, '\t'); getline(check2,trDate, '\t'); getline(check2,tComplete, '\n'); // Converts the string form of these pieces into usable integers. stringstream(tDate.substr(0,tDate.find_first_of('/'))) >> year; stringstream(tDate.substr(tDate.find_first_of('/')+1,tDate.find_last_of('/'))) >> month; stringstream(tDate.substr(tDate.find_last_of('/')+1,tDate.length()-1)) >> day; stringstream(tComplete) >> checkComplete; stringstream(trDate) >> checkReminder; // Adds the number of days until your task is due! if(year != date[0]){ for(int i = date[1]; i <= 12; i++){ countTheDays += System::DateTime::DaysInMonth(date[0], i); } countTheDays-= date[2]; for (int i = 1; i<= month; i++){ countTheDays +=System::DateTime::DaysInMonth(year, i); } countTheDays -= (System::DateTime::DaysInMonth(year, month) - day); } else if(month != date[1]){ for(int i = date[1]; i <= month; i++){ countTheDays += System::DateTime::DaysInMonth(date[0], i); } countTheDays -= (date[2]); countTheDays -= (System::DateTime::DaysInMonth(year, month) - day); } else{ countTheDays+= System::DateTime::DaysInMonth(date[0], month); countTheDays -= (System::DateTime::DaysInMonth(year, month) - day); countTheDays -= date[2]; } // If the task is nearing it's due date (the time frame specified to be notified) it'll notify user. // Only coded to work if the task is due in the current or following months. if(countTheDays <= checkReminder){ if( countTheDays < 0){ cout << endl << endl << tName << " is past due!" << endl; cout << "Should I keep reminding you about this task? Enter Y or N. "; cin >> continueToRemind; } else{ cout << endl << endl << tName << " is due in " <<countTheDays << " days! Don't forget!" << endl; cout << "Should I keep reminding you about this task? Enter Y or N. "; cin >> continueToRemind; } // If user doesn't want to be reminded, begins process of converting that line in the file to usable info // and 'overwriting' the old file by creating a new one, deleting the old one, and renaming the new one. if(continueToRemind == "n" || continueToRemind == "N"){ fileModified = true; string line; /* vector<string> lines; while(getline(tasksClone, line)){ lines.push_back(line); } lines.erase(remove(lines.begin(), lines.end(), workingString), lines.end()); if (!lines.empty()) { auto i=lines.begin(); auto e=lines.end()-1; for (; i!=e; ++i) { saveTasks << *i << '\n'; } saveTasks << *i; }*/ // This writes a copy of the tasks.dat file, minus the task that the user elected not to be notified of.' while(getline(tasksClone, testBuffer)){ if(testBuffer == workingString){ // This condition does nothing. Essentially erasing the 'completed' task from the list. } else if(testBuffer != workingString && tasksClone.eof()){ // This writes everything except the specified task to taskbuffer.dat saveTasks << testBuffer; } else { saveTasks << testBuffer << '\n'; } } } } } } } else{ cout << "The tasks file is empty, you must not have any tasks!" << endl; }
I hope that question makes sense!
Thanks
Marcus
UPDATE: Reworked the code, again. After telling it to delete 1 task, it never runs this loop. Current code:
while(getline(tasksClone, testBuffer)){ if(testBuffer == workingString){ // This condition does nothing. Essentially erasing the 'completed' task from the list. } else if(testBuffer != workingString && tasksClone.eof()){ // This writes everything except the specified task to taskbuffer.dat saveTasks << testBuffer; } else { saveTasks << testBuffer << '\n'; }
}
Input file:
test1 2012/12/13 10 0; test2 2012/12/23 20 0; test3 2012/12/31 28 0; \n
Output file (after telling it to delete test1 and 2):
test2 2012/12/23 20 0; test3 2012/12/31 28 0; \n
-4442567 0 You just need to add onScrollListener onto your View. Preferably Use ListView to show data
From the following code your can get the index of the current view.
ListView.OnScrollListener is the interface that you need to implement and give body to
following two methods.
listView.setOnScrollListener(new ListView.OnScrollListener(){
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { }
public void onScrollStateChanged(AbsListView view, int scrollState) { switch (scrollState) { case OnScrollListener.SCROLL_STATE_IDLE: mBusy = false; int first = view.getFirstVisiblePosition(); int count = view.getChildCount(); break; case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL: break; case OnScrollListener.SCROLL_STATE_FLING: break; } }
});
Try Printing the value of first and count variable it will solve your problem.Hopefully :)
-26132931 0 Titanium Studio JavaScript - adding buttons to table viewsIs it possible to add buttons to table views? I am trying to create a screen that resembles a settings screen on the iPhone.
I know you are able to add the little arrow that represents that the list has a child but what I'm specifically looking for is how to add a plus button to the right side of my table view.
-2988486 0 JavaFX media player in mobileDoes anyone have any tutorials in playing videos in javafx applications in mobile?
My codes strangely work only in desktop execution. But the official site of JavaFX says it plays in mobile phones. I used their sample code and guess what, it doesn't play on the mobile phone too.
Here is the sample code I used: http://javafx.com/docs/articles/media/EmbeddedPlayer.fx.jsp
Please help me guys. I'm on a dead-end here. =<
-27336470 0 Limit text to a certain number of chars, but stop when a period is found within the final 20 charsSo, I have this function to produce an excerpt from large texts.
function excerpt( $string, $max_chars = 160, $more = '...' ) { if ( strlen( $string ) > $max_chars ) { $cut = substr( $string, 0, $max_chars ); $string = substr( $cut, 0, strrpos( $cut, ' ' ) ) . $more; } return $string; }
This works just fine for it's intends - it limits a given text to a certain number of chars, without cutting words.
Here's a working example:
$str = "The best things in using PHP are that it is extremely simple for a newcomer, but offers many advanced features for a professional programmer. Don't be afraid reading the long list of PHP's features. You can jump in, in a short time, and start writing simple scripts in a few hours."; echo excerpt( $str, 160 );
This produces this output:
The best things in using PHP are that it is extremely simple for a newcomer, but offers many advanced features for a professional programmer. Don't be afraid...
However, I'm trying to figure out how to stop if a period, an exclamation or an interrogation mark is found within the excerpts last 20 chars. So, using the above sentence, it would produce this output:
The best things in using PHP are that it is extremely simple for a newcomer, but offers many advanced features for a professional programmer.
Any ideas how to archive this?
-35937899 0I see.. Because you must change browser css defaults use in reset.css or normalize.css
Example delete margin:
index.html page:
<html> <head> <style> html, body { height:100%; margin:0px; //--> added this line } </style> </head> <body style="height:100%;"> <div style="width:100%; height:100%;"> <div id="theHead" style="height:10%; "> </div> <div id="theMain" style="height:80%;"> </div> <div id="theBottom" style="height:10%;"> </div> </div> </body> </html>
Firefox default stylesheet file
Webkit default stylesheet file
-30450496 0It sounds like you're looking for the automatically-generated attribute for reverse lookups. You can get a QuerySet
of all InboxEntries
associated with a TaskBox
like this:
TaskBox.objects.filter(id=1).inboxentry_set.all()
See the documentation on related objects.
-30969955 0In 4 bit 2'scomplement -2 is 1110 and +3 is 0011 so
11110 carry 1110 -2 +0011 +3 ---- 10001 which is 0001 or simply 1 ignoring the carry in bit 5
Stepping through the process from the right to the left:
1 + 0 results in 1 with no carry
1 + 1 results in 0 with a carry of 1
1 + 0 + the carry of 1 results 0 with a carry of 1
1 + 0 + the carry of 1 results in 0 with a carry of 1
just the carry of 1 results in 1 with nothing more to carry
For reference see the Wikipedia article on 2's complement particularly the section on addition at https://en.wikipedia.org/wiki/Two%27s_complement#Addition. There are a number of online 2's complement calculators to help with conversions and one of them is at http://www.exploringbinary.com/twos-complement-converter/
Let me know if you want to see how -3 + -3 is done, since that is what you attempted. It is a similar process, but be sure start with bit length large enough to avoid overflow as determined when the leftmost two bits in the carry row have different values.
-14503052 0 Why exactly are Java arrays not expansible?Possible Duplicate:
Why aren’t arrays expandable?
I am starting to learn Java as my Computer Science school's assignments require this language and I'm liking the language. However, I've seen that Java arrays are not expansible - that is - you must declare their length before using them and it can't be changed further.
I'd like to know exactly why is that? Why the Java language designers chose to to make arrays as such? I guess it's for performance concerns but I'm not sure.
Thanks everyone in advance.
-19664524 0 Securing ASP.NET WebAPI - Custom Login + Social LoginI am writing an ASP.Net WebApi application and I want to secure it using a combination of Custom Login (like ASP.NET Membership) and Social Logins (Google,Facebook,Twitter,LinkedIn and hopefully many more). User should be able to select any of them.
My client is pure HTML/JS SPA application and for that i will need to implement Implict grant flow of OAuth.
The options i see right now are
Use Thinktecture's Identity Server and Authorization Server.
Use DotNetOpenAuth library.
Can anyone point me in the right direction ? Which one of the above options can work for me?
Thanks
-29704760 0 Does Symfony 2 support Cassandra DB?I wanted to know if I can use Symphony 2 and Cassandra Database for a web project. I know that Symphony 2 supports NoSQL databases like MongoDB, but I am not sure if it do the same with Cassandra.
Any clarification would be welcome.
-6519964 0If you look at the source, you'll see a GoogleItem::SetMerchantPrivateItemData
, which simply sets the GoogleItem::$merchant_private_item_data
property. Examining GoogleItem::GetXML
reveals GoogleItem::$merchant_private_item_data
can be a MerchantPrivate
(which appears to be unimplemented, but you can write your own as long as it has a MerchantPrivate::AddMerchantPrivateToXML(gc_XmlBuilder $xml)
method) or a string, which (after a pass through htmlentities
) becomes the content of the merchant-private-item-data
element. If you want to structure your private data with XML, you'll have to implement class MerchantPrivate
.
class MerchantPrivate { function AddMerchantPrivateToXML(gc_XmlBuilder $xml) { $xml->Push('merchant-private-item-data'); $this->_addMyData($xml); $xml->Pop('merchant-private-item-data'); } abstract protected function _addMyData($xml); } class ItemData extends MerchantPrivate { public $userid, $period, $attribute; function _addMyData(gc_XmlBuilder $xml) { $xml->Element('userid', $this->userid); $xml->Element('period', $this->period); $xml->Element('attribute', $this->attribute); } }
-37507362 0 How to convert a string (multi-byte) in to a int/hex value in VBScript I've requirement for getting a 4-byte hex value as a input, for which I'm using InputBox(), which is returning me the input value (for ex: 5C0F591C) as a string and hence it is failing when I'm comparing it with numerical equivalent.
By googling I found how to convert a char to int, I'd like to know if there are any procedures which can convert my 4-byte string in to a int/hex.
Also, it'd helpful if you can point to type conversion in VBScript for future purposes.
I'm very new to VBScript, correction can be made at any point, if I'm wrong
Appreciate your help, in advance.
-13103229 0 parallelize a large loopI have a large loop where I am trying to calculate certain attributes for each pixel in a DEM (4800x6000). I am calling a function demPHV in which I've vectorized all calculations that outputs a structure with 26 fields . I have 4 cores but also have access to a multi-core cluster. I would like to speed up the weeks it would take to run this.
Z is the dem for this example. R is the spatialref object (a vector for example's sake). latlim and lonlim are vectors of lat and long of the western US coastline (made up pairs in the example). for example:
Z=rand(48,60); R=makerefmat(120,40,.5,.5) latlim=[40:60]'; lonlim=[136:(143-136)/(length(latlim)-1):143]';
Then my original loop:
for col=11:size(Z,2)-11 for row=11:size(Z,1)-11 dpv=demPHV(Z,R,row,col,latlim,lonlim) fn=fieldnames(dpv); for k=1:length(fieldnames(dpv)) DEM_PHV.(fn{k}).{row,col}=dpv.(fn{k}); end end
Loops for parallelizing:
option 1:
[rows, cols] = meshgrid(12:(size(Z,1)-12), 12:(size(Z,2)-12)); inds = sub2ind(size(Z), rows, cols); inds = inds(:)'; parfor i=inds(1):inds(end) dpv=demPHV(Z,R,i,latlim,lonlim) end
This includes [r,c]=ind2sub(size(Z),i)
in the function to use in the function demPHV.
option 2:
parfor col=11:size(Z,2)-11 for row=11:size(Z,1)-11 dpv=demPHV(Z,R,row,col,latlim,lonlim) end end
parfor requires consecutive integers hence some of these changes. I have to exclude the bordering 11 rows and columns because my function uses surrounding pixels to calculate some of the attributes.
So, my questions:
parfor does not allow me to include the second part of my original loop:
fn=fieldnames(dpv);
for k=1:length(fieldnames(dpv))
DEM_PHV.(fn{k}).{row,col}=dpv.(fn{k});
end
during which I assign the output structure to another variable. The ultimate goal is to have the variable DEM_PHV have fields for every attribute I need, and every field to be a matrix size(Z) where every cell is the corresponding value for that attribute. I've tried to have my function output the values in the correct cell of the matrix, but then I get a matrix size(Z) with []
everywhere except for the value at location row,col
. This seems like a horribly inefficient use of memory... any better suggestions? I hope I covered everything. Thanks for looking!
On InfoQ there is a very interesting summary of the OOPSLA Panel from 2007 discussing this topic:
No Silver Bullet Reloaded Retrospective OOPSLA Panel Summary
There are a lot of gems in this discussion!
Especially cool is Martin Fowler disguised as a Werewolve and playing advocatus diaboli.
There is also a video from Fowler as Werewolve on YouTube
The sarcastic comments from Fowler alone are worth the read of the summary!
Reading the summary there seems to be a general consensus that there is really no silver bullet.
But this is also a dangerous consensus. As Bertrand Meyer (also in the summary) poses it:
according to his experience, many people, especially managers, rejected new ideas of the ‘80s and ‘90s like OOP, which actually were old ones, because they did not believe the new technology proposed to them would have a serious impact on development,
Using the insight, that there is no silver bullet as an excuse to stop trying to improve is certainly not the way to go!
I was a student of Bertrand Meyer at university, and he was a critic of Brooks paper, because he claimed that it was smothering innovation and the desire for improvement.
-19537575 0The more specific you can be with your question the better the answers you receive will be. Nevertheless, here is an index that sets up an analyzer (with filter) and tokenizer (EdgeNGram) and then uses them to create an autocomplete index on the Name field of a Tag class.
public class Tag { public string Name { get; set; } } Nest.IElasticClient client = null; // Connect to ElasticSearch var createResult = client.CreateIndex(indexName, index => index .Analysis(analysis => analysis .Analyzers(a => a .Add( "autocomplete", new Nest.CustomAnalyzer() { Tokenizer = "edgeNGram", Filter = new string[] { "lowercase" } } ) ) .Tokenizers(t => t .Add( "edgeNGram", new Nest.EdgeNGramTokenizer() { MinGram = 1, MaxGram = 20 } ) ) ) .AddMapping<Tag>(tmd => tmd .Properties(props => props .MultiField(p => p .Name(t => t.Name) .Fields(tf => tf .String(s => s .Name(t => t.Name) .Index(Nest.FieldIndexOption.not_analyzed) ) .String(s => s .Name(t => t.Name.Suffix("autocomplete")) .Index(Nest.FieldIndexOption.analyzed) .IndexAnalyzer("autocomplete") ) ) ) ) ) );
There is also a fairly complete mapping example in NEST's unit test project on github. https://github.com/elasticsearch/elasticsearch-net/blob/develop/src/Tests/Nest.Tests.Unit/Core/Map/FluentMappingFullExampleTests.cs
Edit:
To query the index, do something like the following:
string queryString = ""; // search string var results = client.Search<Tag>(s => s .Query(q => q .Text(tq => tq .OnField(t => t.Name.Suffix("autocomplete")) .QueryString(queryString) ) ) );
-22912168 0 How to visualize relation between objects in a database? I have a database which I want to visualize in some kind of tool. Let me explain the basic: Company A does business with Transport Company A and Transport Company B. Transport Company A does business with Company A, Company B and Company C. Company C does business with Transport Company A and Transport Company B.
As you can see every Company does business with different Transport Companies and vice versa. These relationships can be implemented in a database, and when drawing a visual model on paper this is also very easy.
Of course the model should contain hundreds of Companies and Transport Companies. So I want to have a visualizing tool, where a overview of these relations can be displayed.
My question is which tools can be used for realizing this?
-38146308 0There is a Unix-only solution based on the PTools.jl package (https://github.com/amitmurthy/PTools.jl).
It relies on parallelism via forking instead of the Julia in-built mechanism. Forked processes are spawned with the same workspace as the main process, so all functions and variables are directly available to the workers.
This is a similar to the Fork clusters in R parallel package, so it can be used as the mclapply function.
The function of interest is pfork(n::Integer, f::Function, args...) and one noticeable difference with mclapply in R is that the function f must take as first argument the index of the worker.
An example:
Pkg.add("PTools") Pkg.checkout("PTools") #to get the last version, else the package does not build at the time of writing using PTools f(workid,x) = x[workid] + 1 pfork(3, f, [1,2,3,4,5]) #Only the three first elements of the array will be computed 3-element Array{Any,1}: 2 3 4
I expect that an interface to pfork will be built so that the first argument of the function will not need to be the index of the worker, but for the time being it can be used to solve the problem
-32300427 0Some brief information about Stash and Git.
Git is a distributed version control system.
Stash is a repository management system of Atlassian. It can be used to manage Git repositories, also it can be used to manage repositories of other version control system like mercurial.
A good overview for each product can be found in their official sites;
Atlassian official site, stash product home page
There are many repository management system you can use with Git. One of the most popular is Stash in Enterprise world. But when you look to open source world, GitHub is the most popular one as far as I know.
You can create repository, push, or pull your code into Git repositories whether they are in your local computer or they are in remote corporate servers. Using a repository management system ( like Stash) for this kind of task is not necessary, but It is sometimes preferred, especially by the companies which has huge It departments.
So, Git, and Stash are not alternative but complementary to each other. You can think Git as a kernel and stash as the shell surrounding the kernel.
But, why we need repository management systems;
Now, Lets try to answer your questions;
I can access my company Stash project repositories. I cloned the project into my local Git repository
Whether Code repository is on remote server behind stash or it is in local computer. It is a Git repository.
Git is just a facilitator to communicate with Stash?
No, Vice versa is more correct. Git is the core of VCS, you use stash to make it more manageable, secure, and easy to use in your corporate.
Can't we use Git as distributed repository instead of Stash?
First you can not use Git instead of Stash, because they are not alternative to each other. But they are complement to each other.
If you mean using Git as remote repository, sure you can use it.
For clarification, Git is distributed not because you can have remote repositories. Whether centralized or distributed, you can have remote repository on all VCS. Distributed means, when you clone a repository, you also clone all history etc. In this structure, you can have a central repository but it is not required. If centrol repository get corrupted, it is not a big deal, any node can become new central repository. Even though in corporate world having a central repository is best practice, some open source projects ( for instance Linux kernel) don't have a central repository.
What is the relationship between those two tools?
I think it is already explained above. They are complementary to each other. Git is the VCS, and stash is repository management tool. It makes Git more secure and manageable for corporate IT departments.
Without Git, can the code be cloned, committed to Stash? Or, without Git, can Stash exist?
It is already explained as well. You can use Stash with other VCS. Git is not necessary. But you need at least one VCS.
You can not commit/clone code to/from stash. You can commit/clone code to/from VCS via stash.
VCS: Version Control System
-15224042 0This seems to work:
function isTouchEnabled() { return !!document.createTouch; }
-18768537 0 You can do this in MVVM but you will need to use a service. In fact, this is where MVVM is weak (without using a framework such as Prism et al.). The following is a link to disore's DialogService class on CodeProject. it is awesome, but it will take time to get to grips with how it works.
The above library will enable you to close a View from a ViewModel.
I hope this helps.
-13054616 0 Calling js function declared in html file from a .js fileI'm working in my .js file. When my function, mainPaginationClicked is called, I want it to also execute another function, rotateMessage. rotateMessage is declared in the script tags of my html document. Is there a way to call this function from my .js file?
-36397663 0From the error message it seems like your @users is not an array or ActiveRecord::Relation.
I would print out the @users on the view to debug. Also, find(:all, :conditions => ["status = ?", "online"])
is not the preferable way to query.
Use User.where(:status => "online")
. Reference - http://guides.rubyonrails.org/active_record_querying.html#conditions
You need now check the format of the request to know what your want really served. It's really better than to know if you request is or not in xhr. This trick was bad because can be not support by all Javascript script.
-1454257 0The speed of the JavaScript engine depends on several factors, including the code itself. Some code can be optimized for specific browsers, although developers aren't supposed to do such a thing.
Does it matter? It sure does! With the current Web 2.0 developments, where we have JavaScript doing all kinds of Ajax things, speed suddenly becomes important. Even this site uses JavaScript, even though it's just to notify me that another answer has posted while I was typing this message.
Most browsers have their own engine and they're competing very hard with one another to get the best performance. The fastest one? Undetermined since most comparisons have been a bit colored in favor of the company that sponsored the comparison.
Still, a fast engine is useless when the code is written in a bad way...
-27832159 0This is a printing poblem:
double d = 1.5; System.out.println(String.format("%.2f", d)); // 1.50
-38762319 0 The easiest way to do it, is to record an App Preview for the biggest screen size and then scale it down with tools like After Effects or Final Cut Pro. I'm not 100% sure, if you can also do it with iMovie. If you're supporting iPad, you need to create another version for iPads.
Here are the official sizes (Landscape only for simplification):
5 Series: 1920 x 1080 (< Standard 1080p 16:9 aspect ratio) or 1136 x 640
iPhone 6: 1334 x 750 (~ 70% of 1080p)
iPhone 6 Plus: 1920 x 1080
AppleTV: 1920 x 1080
iPad: 1200 x 900 or 1600 x 1200 (4:3 aspect ratio)
I suggest you capture the material for the App Previews with an iPhone 6 Plus (real device or simulator if that works for you) and then scale it down for the best quality. If you don't have an iPhone 6 Plus, you can use an iPhone 6, but you will lose quality.
Summary: You only need 2 different App Previews - with regards to resolutions - if you are only supporting iPhones. (3 if you are supporting iPads.)
-25033424 0This is how I solved the issue..
Overide onKeyDown()
method in your activity.
@Override public boolean onKeyDown(int keyCode, KeyEvent event) { // if one of the volume keys were pressed if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) { // change the seek bar progress indicator position decreaseSeekbarValue(); } else if(keyCode == KeyEvent.KEYCODE_VOLUME_UP) { // change the seek bar progress indicator position increaseSeekbarValue(); } // propagate the key event return super.onKeyDown(keyCode, event); }
-12087383 0 How to stream videos from any url in android application? I want to use media player to play videos from any url. I found that, youtube video can be played using rtsp url, but no other videos, like vimeo video, can be played in app. Is there any method to do it?
-2016288 0In theory, you cannot protect anything in memory completely. Some group out there managed to read the memory contents 4 hours after the computer was turned off. Even without going to such lengths, a debugger and a breakpoint at just the right time will do the trick.
Practically though, just don't hold the plaintext in memory for longer than absolutely necessary. A determined enough attacker will get to it, but oh well.
-17027113 0 Having trouble using cURL's PUT in PHPI am having trouble doing cURL PUT in PHP for a REST API. It says 401 Unauthorized and I am quite new to php so I didn't know what to do please help me.
<?php $url = "https://app.linkemperor.com/api/v2/vendors/blasts/6949235.json"; $data = '{"blasts": {"links" : "http://doblajemexicano.com.mx/sitio/index.php?title=Keyword_Elite_,_The_Ferrari_Of_Search_phrases_Study http://fi.caravanwiki.com/index.php/Keyword_Elite_,_The_Ferrari_Of_Keywords_and_phrases_Research"}}'; $content = json_encode($data); $oneMB = 1024 * 1024; $fh = fopen('php://temp/maxmemory:$oneMB', 'r+'); fwrite($fh, $content); rewind($fh); $curl = curl_init($url); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_USERPWD, "<api key>:x"); curl_setopt($curl, CURLOPT_INFILE, $fh); curl_setopt($curl, CURLOPT_INFILESIZE, strlen($content)); curl_setopt($curl, CURLOPT_PUT, true); curl_setopt($curl, CURLOPT_TIMEOUT, 10); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); $json_response = curl_exec($curl); $status = curl_getinfo($curl, CURLINFO_HTTP_CODE); if ( $status != 201 ) { die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl)); } curl_close($curl); $response = json_decode($json_response, true); ?>
-7259367 0 You simply need to mark the zip file as Embedded Resource
under Build Action
. http://msdn.microsoft.com/en-us/library/0c6xyb66.aspx
You need to have installed the AdventureWorksDW2012 database to do this tutorial. You are trying to read from the table [dbo].[DimCurrency]
which does not exist. Refer to the requirements here.
Update:
You can create the [dbo].[DimCurrency] table with the following SQL, this should get rid of your error (though the table will obviously be empty):
USE AdventureWorks2012 CREATE TABLE [dbo].[DimCurrency] ( [CurrencyAlternateKey] nchar(3) NOT NULL, [CurrencyKey] int NOT NULL, [CurrencyName] nvarchar(50) NOT NULL );
-8345868 0 Let us ask the question another way. How can we best give users a way to select multiple related items in jquery mobile. Select dropdowns present their own UX failings to begin with in that they require work on the part of the user to see what the options even are. Mobile devices only compound the issue with their differing implementations of the control.
Instead, try this using grouped checkboxes. http://jquerymobile.com/demos/1.0/docs/forms/checkboxes/
You will have more control over how the information is displayed and users will find it easier to see all the options at once.
-22179755 0I had never use Google App Engine, but several times AWS systems, and sure, as AWS EC2 could be used as Linux Server Instance, I recommend you that provider. And coz' it seems that you use PHP, they have strong API for this langage. Have fun with AWS.
-18208963 0yes, Indeed it is a iOS 6.0 feature.
I have installed Poppler Utils
for windows in addition to https://github.com/mgufrone/pdf-to-html
It works perfectly and it converts PDF files
to HTML
, by making a single HTML file contains 2 iframes, one for pages navigation
and the other for the actual text
.
The problem is when the HTML
files are generated, the linking for iframe src
gives a false linking.
For Example:
Test.html
Pages.html
Page_1.html
All these files exist in the same folder named "Output".
Test.html
contains 2 iframes
linking to Pages.html
and Page_1.html
Here's the problem in Test.html
:
<frameset cols="100,*"> <frame name="links" src="output/Pages.html"/> <frame name="contents" src="output/Pages_1.html"/> </frameset>
Should be:
<frameset cols="100,*"> <frame name="links" src="Pages.html"/> <frame name="contents" src="Pages_1.html"/> </frameset>
PDF.php
<?php namespace Gufy\PdfToHtml; class Pdf { protected $file, $info; // protected $info_bin = '/usr/bin/pdfinfo'; public function __construct($file, $options=array()) { $this->file = $file; $class = $this; array_walk($options, function($item, $key) use($class){ $class->$key = $item; }); return $this; } public function getInfo() { if($this->info == null) $this->info($this->file); return $this->info; } protected function info() { $content = shell_exec($this->bin().' '.$this->file); // print_r($info); $options = explode("\n", $content); $info = array(); foreach($options as &$item) { if(!empty($item)) { list($key, $value) = explode(":", $item); $info[str_replace(array(" "),array("_"),strtolower($key))] = trim($value); } } // print_r($info); $this->info = $info; return $this; // return $content; } public function html() { if($this->info == null) $this->info($this->file); return new Html($this->file); } public function getPages() { if($this->info == null) $this->info($this->file); return $this->info['pages']; } public function bin() { return Config::get('pdfinfo.bin', '/usr/bin/pdfinfo'); } }
Base.php
<?php namespace Gufy\PdfToHtml; class Base { private $options=array( 'singlePage'=>false, 'imageJpeg'=>false, 'ignoreImages'=>false, 'zoom'=>1.5, 'noFrames'=>true, ); public $outputDir; private $bin="/usr/bin/pdftohtml"; private $file; public function __construct($pdfFile='', $options=array()) { if(empty($pdfFile)) return $this; $pdf = $this; if(!empty($options)) array_walk($options, function($value, $key) use($pdf){ $pdf->setOptions($key, $value); }); return $this->open($pdfFile); } public function open($pdfFile) { $this->file = $pdfFile; $this->setOutputDirectory(dirname($pdfFile)); return $this; } public function html() { $this->generate(); $file_output = $this->outputDir."/".preg_replace("/\.pdf$/","",basename($this->file)).".html"; $content = file_get_contents($file_output); unlink($file_output); return $content; } /** * generating html files using pdftohtml software. * @return $this current object */ public function generate(){ $output = $this->outputDir."/".preg_replace("/\.pdf$/","",basename($this->file)).".html"; $options = $this->generateOptions(); $command = $this->bin()." ".$options." ".$this->file." ".$output; $result = exec($command); return $this; } /** * generate options based on the preserved options * @return string options that will be passed on running the command */ public function generateOptions() { $generated = array(); array_walk($this->options, function($value, $key) use(&$generated){ $result = ""; switch($key) { case "singlePage": $result = $value?"-c":"-s"; break; case "imageJpeg": $result = "-fmt ".($value?"jpg":"png"); break; case "zoom": $result = "-zoom ".$value; break; case "ignoreImages": $result = $value?"-i":""; break; case 'noFrames': $result = $value?'-noframes':''; break; } $generated[] = $result; }); return implode(" ", $generated); } /** * change value of preserved configuration * @param string $key key of option you want to change * @param mixed $value value of option you want to change * @return $this current object */ public function setOptions($key, $value) { if(isset($this->options[$key])) $this->options[$key] = $value; return $this; } /** * open pdf file that will be converted. make sure it is exists * @param string $pdfFile path to pdf file * @return $this current object */ public function setOutputDirectory($dir) { $this->outputDir=$dir; return $this; } /** * clear the whole files that has been generated by pdftohtml. Make sure directory ONLY contain generated files from pdftohtml * because it remove the whole contents under preserved output directory * @return $this current object */ public function clearOutputDirectory() { $files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($this->outputDir, \FilesystemIterator::SKIP_DOTS)); foreach($files as $file) { $path = (string)$file; $basename = basename($path); if($basename != '..') { if(is_file($path) && file_exists($path)) unlink($path); elseif(is_dir($path) && file_exists($path)) rmdir($path); } } return $this; } public function bin() { return Config::get('pdftohtml.bin', '/usr/bin/pdftohtml'); } }
-40169813 0 How can I pass a string from a C# DLL into an unmanaged language (e.g. C++)? I've had quite a lot of luck interoperating between Fortran (don't ask! :-) and C# using Robert Giesecke's wonderful "Unmanaged Exports" library. However, one of the things I haven't been able to achieve yet is sending a string from C# to Fortran. The worst of it is that I get no indication of what's wrong. My Fortran application just crashes. I've posted this problem to the most popular Fortran forum I know (here), and so far it has generated a lot of discussion but I'm no closer to solving the problem. I'm thinking now that if I can solve it in C/C++, perhaps I can take that solution over to Fortran more easily.
From all the research I've done, it would seem to me that something like the following should work:
using RGiesecke.DllExport; using System.Runtime.InteropServices; namespace CSharpDll { public class Structures { [StructLayout(LayoutKind.Sequential)] public struct MyStruct { [MarshalAs(UnmanagedType.LPStr)] public string Title; public int SourceNode; public int EndNode; } [DllExport("GetStruct", CallingConvention = CallingConvention.Cdecl)] public static MyStruct GetStruct() { var result = new MyStruct(); result.Title = "This is the title"; result.SourceNode = 123; result.EndNode = 321; return result; } } }
Unfortunately, my C/C++ is even rustier than my Fortan. I have no idea how to make this work on that side. Can someone help me write an extremely simple console app in C/C++ that will call the above "GetStruct" method and get the structure including the string?
Note 1: I've tried pretty much every permutation of "UnmanagedType" as well as both "string" and "char[]" with no luck, so whereas I may not have that right in this example, please don't suggest one of those unless you can show that it works. :-)
Note 2: The vast majority of threads I've found around this topic send strings the other way (i.e. from an unmanaged DLL to a managed application rather than from an unmanaged application to a managed DLL). I'm not interested in those, since I have that working like a charm. :-)
-21067044 0It might be possible to generate a token, and include it with the program. However, no matter what, you are facing two serious problems:
1) Anyone with access to your software can reverse engineer it, and build fake software to follow whatever clientside security you have.
2) All data is transmitted through plaintext. So, anyone who is able to read network traffic between your client and server can see the full transmission.
So, my suggestion would be to write server software that heavily restricts what queries are allowed, and only permit those queries that your client needs to be sent.
-40807802 0Your form is having wrong URL
new_collection_photo_path
It should be
collection_photos_path
import java.util._
overrides scala.collection.Iterator
(which available by default via type alias in scala
package object) with java.util.Iterator
. Just change your import to import java.util.Scanner
I am using Excel 2003. I see that I have the ability to save files in XML format as well as XLSX 2007 format. What this functionality provided by installing something extra like a Comparability Pack or is this base Excel 2003 functionality?
The documentation that I see for Excel and XML refers to Open XML and most of what I see is in regards to Office 2007 or greater.
Can I use "Open XML" to read the Xml format document that I saved in 2003? Is the XML format that I save it in really the same as the format that is used in office 2007?
From this MS Site:
Open XML is an open ECMA 376 standard and is also approved as the ISO/IEC 29500 standard that defines a set of XML schemas for representing spreadsheets, charts, presentations, and word processing documents. Microsoft Office Word 2007, Excel 2007, and PowerPoint 2007 all use Open XML as the default file format.
Does this mean that this library can be used to read an Excel 2003 file that I saved as XML? The presumption here is that the XML format used is really 2007 level due to the incompatibility pack.
-38578707 0 Powershell: Output Variables passed from Manage EngineI'm having some issues with making some changes to an existing working script I have, but I have run into an issue with some variables that are being passed from my Manage Engine Software.
In order to better understand what the issue is i'm attempting to devise a simple script to output the variables to a text file so I can see what Manage Engine is spitting out for certain variables. However the script seems to fail when attempting to execute.
Here is what I am using in an attempt to get to the bottom of this.
Command:
Param( [string]$Department ) $Filepath = "\\fileserver\filename.txt" $Department | out-file -filepath $filepath
Any help is greatly appreciated!
-34950199 0According to the Chrome Network inspector, yes, the file will still be downloaded.
Here's my test setup :
- index.php - css - main.css - light.css
My HTML :
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <link rel="stylesheet" href="css/main.css"> <link rel="stylesheet" href="css/light.css" media="screen and (min-width: 600px)"> </head> <body> <h1>Hello world</h1> </body> </html>
main.css
is empty and light.css
contains this :
body{background-color: blue;}
Regardless of the window size, this is what the Network inspector shows :
The background is only blue when the page is over 600px.
-23729988 0if exists ( select * from tempdb.dbo.sysobjects o where o.xtype in ('U') and o.id = object_id(N'tempdb..#tempTable') ) DROP TABLE #tempTable;
-16291826 0 Why Box2D body doesn't collide? I does some tests with Box2D and stuck with it. Here is my body-construct code:
var bodyDef:b2BodyDef = new b2BodyDef(); bodyDef.type = b2Body.b2_dynamicBody; bodyDef.fixedRotation = true; var center:Number = Consts.stageToB2(Consts.worldSize / 2); bodyDef.position.Set(center, center);
var body:b2Body = physicWorld.CreateBody(bodyDef); var shape:b2CircleShape = new b2CircleShape(Consts.stageToB2(w) * 0.5); // our monster is in circle shape. var fixtureDef:b2FixtureDef = new b2FixtureDef(); fixtureDef.shape = shape; body.CreateFixture(fixtureDef);
I created such two bodies, but they doesn't collide! the debugDraw also doesn't light up the bodies. but when I add an angular velocitiy for one of them:
body.SetAngularVelocity(Math.PI / 89);
They'll start collide. Could you explain What happens here?
-21979274 0 How to programmatically Submit Hive Queries using C# in HDInsight Emulator?I Installed single node HDInsight Emulator in Windows 8 system. I want to programmatically submit hive queries in HDInsight Emulator. Kindly suggest me some ways to submit Hive Queries using C# .
-34358903 0Mikhail answer is good! Note that there is some adjustments needed, that were performed with SPLIT and REGEXP_EXTRACT, as the JSON_EXTRACT functions don't handle arrays well enough.
An alternative, in case you want to work with a BigQuery JavaScript UDF:
SELECT userid, word, COUNT(*) c FROM ( SELECT * FROM js( // I wish you had given me a sample table instead when asking the question (SELECT * FROM (SELECT 123 AS id, '{"totalItems":2,"items":[{"word":"drink"},{"word":"food"}]}' AS items), (SELECT 456 AS id, '{"totalItems":3,"items":[{"word":"food"},{"word":"dog"},{"word":"drink"}]}' AS items), (SELECT 123 AS id, '{"totalItems":1,"items":[{"word":"drink"}]}' AS items) ), // Input columns. id, items, // Output schema. "[{name: 'word', type:'string'}, {name: 'userid', type:'integer'}]", // The function. "function(r, emit) { x=JSON.parse(r.items) x.items.forEach(function(entry) { emit({word:entry.word, userid:r.id}); }); }" ) ) GROUP BY 1,2
-29587362 0 Wow,so excited,I sovled this all by my self,what i do wrong here is that the request header i sent is not included in the nginx config add_header 'Access-Control-Allow-Headers'
complete nginx config:
http { include mime.types; default_type application/octet-stream; access_log /tmp/nginx.access.log; sendfile on; upstream realservers{ #server 192.168.239.140:8080; #server 192.168.239.138:8000; server 192.168.239.147:8080; } server { listen 8888 default; server_name example.com; client_max_body_size 4G; keepalive_timeout 5; location / { add_header Access-Control-Allow-Origin *; add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'Access-Control-Allow-Orgin,XMLHttpRequest,Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Mx-ReqToken,X-Requested-With'; try_files $uri $uri/index.html $uri.html @proxy_to_app; } location @proxy_to_app{ add_header Access-Control-Allow-Origin *; add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'Access-Control-Allow-Orgin,XMLHttpRequest,Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Mx-ReqToken,X-Requested-With'; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; #proxy_set_header X-Real-IP $remote_addr; proxy_redirect off; proxy_pass http://realservers; } } }
because my request is :
core-ajax auto headers='{"Access-Control-Allow-Origin":"*","X-Requested-With": "XMLHttpRequest"}' url="http://192.168.239.149:8888/article/" handleAs="json" response="{{response}}"></core-ajax>
i didnt include the Access-Control-Allow-Origin
and XMLHttpRequest
header into the nginx config Access-Control-Allow-Headers
,so that is the problem.
I hope its useful to whom has the same problem!
-21782447 0Either use a manual running total OR a running-total field
, not both. By the way, a running-total field
only works in a footer
section.
A better approach:
{#sumKN} - field is {table.KN}; summarize for all records; reset after change in group {#sumSKS} - field is {table.SKS}; summarize for all records; reset after change in group // place in `footer` section //{@ratio} // optional // EvaluateAfter({#sumKN}); // EvaluateAfter({#sumSKS}); {#sumKN} / {#sumSKS}
-13057192 0 I'm not sure this is your case or not, but there are some issues regarding with .ts file encoding.
Unfortunately TypeScript cannot compile UTF-8 with signature. You might choose another save option by "FILE"-->"Advanced Save Options"--> Select "UTF-8 without signature".
Check current issue. http://typescript.codeplex.com/workitem/85
Thanks
-13968909 0You need to add recursion depth to your recursive method, to be able to limit what is printed:
long getDirSize(File dir, int depth, int printDepth)
Then you need recursion call like this:
size += this.getDirSize(file, depth+1, printDepth);
And if you meant you want to print only sizes at maxdepth, then you need to add test like
if (depth == printDepth) { // or depth <= printDepth maybe // ...do printing only for these }
It might make sense to wrap the whole thing in a class, so you could make printDepth a member variable, and the recursive method private, something like:
class DirSizePrinter { int printDepth; File root; public DirSizePrinter(int printDepth, File root) { this.printDepth = printDepth; this.root = root; } public long printSize() { return printSizeRecursive(0); } private long printSizeRecursive(int depth) { // ... code from question with depth added, and using printDepth and root } }
Usage:
new DirSizePrinter(3, "C:/temp").printSize();
Or some variation of this, depending on all the requirements you have.
-34898446 0 ElasticSearch Security and PortsI have setup an elastic-search cluster with two data nodes , one master node and one client node with KIBANA.
I was running it with iptables disabled on each node (CC 6). Now i need to enable iptables and i want to know which of the ports (9200 , 9300) , i need to open on each node and in which direction (incoming or outgoing). The discovery is using uni-cast.
I would also like to know on which node i should place authentication , i.e just the client node ?
Cluster: mycluster data-node1 data-node2 master-node1 client-node1
Thanks.
-16042019 0Thank you. I downloaded the jaxb-impl.jar since the the jaxb-api.jar is already included in Java 6 API. Just in case someone else needs a linux script to replace the wrong imports, as mentioned by Wouter.
Navigate to your project path and adjust com.abc.generated
and abc.xsd
.
#!/bin/sh xjc -d src/ -p com.abc.generated -Xlocator abc.xsd FILES=$(find src/ -type f -name *.java) for f in $FILES do sed -i 's/\(.*import com.sun.xml.internal.bind.Locatable;.*\)/import com.sun.xml.bind.Locatable;/g' $f sed -i 's/\(.*import com.sun.xml.internal.bind.annotation.XmlLocation;.*\)/import com.sun.xml.bind.annotation.XmlLocation;/g' $f done
-14694736 0 Github like dynamic routes What would be the best way to implement routes like github uses?
Ex:
github.com/about github.com/37signals github.com/javan
I'm guessing /about is a real controller, but the second and third probably load a user controller. What is the best way to do this?
-40092878 0 .apk file is not downloaded with codeigniter ('download') helperI am working on codeigniter project . in that project i made a webview app (.apk). i upload the a.apk file in upload folder of the project but i am unable to get the .apk when i click on download button . my code is
public function downloadapp() { $this->load->helper('download'); $data = file_get_contents(base_url()."uploads/apk/hc.apk"); $name = 'hc.apk'; force_download($name, $data); }
when i add some other file like(.jpg , .png ) then the doenload code is working fine .. but only .apk file is not downloaded . please help me . and thanks in advance :)
-25087978 0Use replace insted of replaceAll. Read API.
String input = "ab(,cd(,"; System.out.println(input.replace("(,", "("));
-17926318 0 Declare some variable within a switch and use it externally.
You can't. Variables defined inside the scope would only be visible within that scope.
You have to declare your variable outside the switch
statement and then you will be able to use it outside.
I see that you are using var
(Implicitly typed variable) and you can't declare it outside of your switch
statement, (since that needs to be assigned), You should see: Declaring an implicitly typed variable inside conditional scope and using it outside and the answer from Eric Lippert
I'm using Spring/Hibernate and this is the first time I have a Java model object with about 1500 properties (I work at a research center and there is a data collection form that is just this long) and I'm getting the following error during application startup:
INFO 12/11 18:43:16 org.hibernate.connection.ConnectionProviderFactory - Initializing connection provider: org.springframework.orm.hibernate3.LocalDataSourceConnectionProvider INFO 12/11 18:43:16 org.hibernate.cfg.SettingsFactory - RDBMS: MySQL, version: 5.5.27 INFO 12/11 18:43:16 org.hibernate.cfg.SettingsFactory - JDBC driver: MySQL Connector Java, version: mysql-connector-java-5.1.27 ( Revision: alexander.soklakov@oracle.com-20131021093118-gtm1bh1vb450xipt ) INFO 12/11 18:43:16 org.hibernate.dialect.Dialect - Using dialect: org.hibernate.dialect.MySQLDialect INFO 12/11 18:43:16 org.hibernate.transaction.TransactionFactoryFactory - Using default transaction strategy (direct JDBC transactions) INFO 12/11 18:43:16 org.hibernate.transaction.TransactionManagerLookupFactory - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended) INFO 12/11 18:43:16 org.hibernate.cfg.SettingsFactory - Automatic flush during beforeCompletion(): disabled INFO 12/11 18:43:16 org.hibernate.cfg.SettingsFactory - Automatic session close at end of transaction: disabled INFO 12/11 18:43:16 org.hibernate.cfg.SettingsFactory - JDBC batch size: 15 INFO 12/11 18:43:16 org.hibernate.cfg.SettingsFactory - JDBC batch updates for versioned data: disabled INFO 12/11 18:43:16 org.hibernate.cfg.SettingsFactory - Scrollable result sets: enabled INFO 12/11 18:43:16 org.hibernate.cfg.SettingsFactory - JDBC3 getGeneratedKeys(): enabled INFO 12/11 18:43:16 org.hibernate.cfg.SettingsFactory - Connection release mode: on_close INFO 12/11 18:43:16 org.hibernate.cfg.SettingsFactory - Maximum outer join fetch depth: 2 INFO 12/11 18:43:16 org.hibernate.cfg.SettingsFactory - Default batch fetch size: 1 INFO 12/11 18:43:16 org.hibernate.cfg.SettingsFactory - Generate SQL with comments: disabled INFO 12/11 18:43:16 org.hibernate.cfg.SettingsFactory - Order SQL updates by primary key: disabled INFO 12/11 18:43:16 org.hibernate.cfg.SettingsFactory - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory INFO 12/11 18:43:16 org.hibernate.hql.ast.ASTQueryTranslatorFactory - Using ASTQueryTranslatorFactory INFO 12/11 18:43:16 org.hibernate.cfg.SettingsFactory - Query language substitutions: {} INFO 12/11 18:43:16 org.hibernate.cfg.SettingsFactory - JPA-QL strict compliance: disabled INFO 12/11 18:43:16 org.hibernate.cfg.SettingsFactory - Second-level cache: enabled INFO 12/11 18:43:16 org.hibernate.cfg.SettingsFactory - Query cache: disabled INFO 12/11 18:43:16 org.hibernate.cfg.SettingsFactory - Cache provider: org.hibernate.cache.NoCacheProvider INFO 12/11 18:43:16 org.hibernate.cfg.SettingsFactory - Optimize cache for minimal puts: disabled INFO 12/11 18:43:16 org.hibernate.cfg.SettingsFactory - Structured second-level cache entries: disabled INFO 12/11 18:43:16 org.hibernate.cfg.SettingsFactory - Statistics: disabled INFO 12/11 18:43:16 org.hibernate.cfg.SettingsFactory - Deleted entity synthetic identifier rollback: disabled INFO 12/11 18:43:16 org.hibernate.cfg.SettingsFactory - Default entity-mode: pojo INFO 12/11 18:43:16 org.hibernate.cfg.SettingsFactory - Named query checking : enabled INFO 12/11 18:43:16 org.hibernate.impl.SessionFactoryImpl - building session factory ERROR 12/11 18:43:18 edu.ucsf.lava.core.dao.hibernate.LavaDaoHibernateImpl - Unable to load bean 'lavaDao' from application contextorg.springframework.beans.factory.BeanCreationException: Error creating bean with name 'lavaDao' defined in ServletContext resource [/WEB-INF/context/core/core-dao.xml]: Cannot resolve reference to bean 'transactionManager' while setting bean property 'transactionManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager' defined in ServletContext resource [/WEB-INF/context/local/pedi/pedi-env-tomcat6.xml]: Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/context/core/core-dao.xml]: Invocation of init method failed; nested exception is net.sf.cglib.core.CodeGenerationException: java.lang.reflect.InvocationTargetException-->null
I know that MySQL InnoDB tables have a 1000 column limit, so I split the model object into two tables, with table 1 having about 960 columns and table 2 having the rest. It appears to be a problem with the number of properties because when I reduce the properties down to below 1000 the application starts up fine, but when I add more properties I get the above error. Since hibernate doesn't have a specific limit on number of properties, could the problem be with JDBC? Is there a JDBC property that I can set to allow for large number of columns? Is the problem elsewhere? I've also tinkered around with MySQL my.cnf settings to no avail.
Thanks for any advice/help.
-34622504 0I'm confused by your question but I think you want the picture slide effect?
If so, I would recommend using the bootstrap Carousel, should give you what you need.
EDIT:
For the section number 4 just use the CSS scroll effects.
-11885566 0For attaching an EventListener on every link, and retrieving the href on click without jQuery, I would probably do something like this:
function trackClick(event) { alert(this.href); } window.onload = function() { var links = document.getElementsByTagName('a'); for (var i = 0; i < links.length; i++) { links[i].addEventListener('click', trackClick, false); }; }
-38801135 0 how to get the start value and end value of a div after dragging hi i have a which is draggable my requirement is 1. iwant the start value and end value of the div after dragging in a text box 2.now its is only drag in right side only i want it dragg also from left side of the div i use some code here but it is not perfect becouse the value is not displaying and the dragging from left is not working midiletable is my parrentdiv
$(function () { var container = $('.middletablediv'), base = null, handle = $('.handle'), isResizing = false, screenarea = screen.width; handle.on('mousedown', function (e) { base = $(this).closest(".scalebar"); isResizing = true; lastDownX = e.clientX; offset = $(this).offset(); xPos = offset.left; }); $(document).on('mousemove', function (e) { // we don't want to do anything if we aren't resizing. if (!isResizing) return; p = parseInt(e.clientX - base.offset().left), // l = parseInt(p * (3 / 11)); base.css('width', p); k = parseInt(xPos - base.offset().left); $("#startvalue").value(k) $("#stopvalue").value(p) }).on('mouseup', function (e) { // stop resizing isResizing = false; }); });
.handle{ position: absolute; top:1px; right: 0; width: 10px; height: 5px; cursor: w-resize; } .middletablediv{ float:left; width:35%; } .scalebar{ margin-top: 13px; height: 7px; position: relative; width:20px; background-color: green; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="middletablediv"> <div id="newvalue1" class="scalebar"> <div class="handle" style="left:0"></div> <div class="handle"></div> </div> </div> <input id="startvalue" type="text">startvalue</input> <input id="stopvalue" type="text" />stopvalue</input>
how i solve this issue
-34442373 0If you want to sort by the first number, the approach is:
var desire = ranges.sort(function(a,b){return parseInt(a)-parseInt(b)});
Explanation: parseInt(a)
just removes everything after the non-number, i.e. -
and returns the number.
If you also want to make it sort by the first number properly if you have ranges starting with the same numbers (i.e. 3-5
and 3-7
):
var desire = ranges.sort(function(a,b){ return (c=parseInt(a)-parseInt(b))?c:a.split('-')[1]-b.split('-')[1] });
Explanation: works as the first one until the first numbers are equal; then it checks for the second numbers (thanks Michael Geary for idea!)
If you want to sort by the result of equation, go for
var desire = ranges.sort(function(a,b){return eval(a)-eval(b)});
Explanation: eval(a)
just evaluates the expression and passes the result.
Also, as mentioned by h2ooooooo, you can specify the radix to avoid unpredictable behavior (i.e. parseInt(a, 10)
).
I am having the same issue. But I was able to compile the Boost.Locale with referring here . So basically what I did was:
bjam --with-locale -sICU_PATH=C:\icu stage link=static,shared
It found ICU and was able to create static
and shared
files. Hope this helps.
I want to loop through a dynamic object, match the value, if item matched, jump out of the loop...
Let say have an object:{a:false:b:true,c:false}
I want to do something like (with loadash),
_.fowOwn({a:1,b:2}, function (value, key) { console.log(key); if(value); break; });
So this should log (a & b)
. How can I break
when the item is matched ?
Thanks for any help.
-20214496 0 My new anchor tag is not working in .tpl fileI am trying to modify a template which consists of .tpl
files instead of .html
or .php
. There are some anchor tags like this:
<a href="{$vurl}?p=about" class="someclass">About Us</a>
but if I try to point to a different page in anchor tag like this:
<a href="{$vurl}?p=newAboutUs" class="someclass">About Us</a>
it is not working. I have already created "newAboutUs.tpl" and copied "about.tpl" content and pasted to "newAboutUs.tpl".
But when I click the "About Us" button, nothing is happening.
If I put everything back and try to click the button it is working again.
-37008966 0This should precisely answer your need.
It uses very powerful R feature called computing on the language (or meta programming) well described in official R Language Definition manual. This is an exceptional feature of R language and should not be forgotten IMO.
library(data.table) DT1 = data.table(x=c("c", "a", "b", "a", "b"), a=1:5) DT2 = data.table(x=c("d", "c", "b"), b=6:8) jj = as.call(c( list(as.name(".")), list(sum = quote(a+b)), lapply(unique(c(names(DT1), names(DT2))), as.name) )) print(jj) #.(sum = a + b, x, a, b) DT1[DT2, eval(jj), on="x"] # sum x a b #1: NA d NA 6 #2: 8 c 1 7 #3: 11 b 3 8 #4: 13 b 5 8
-20239267 0 At last, I was able to find what I was looking for. Phew!
$_REQUEST['Body']
retrieves the body of the sms message and I can do whatever I like with that.
Twilio rocks!
-16047731 0I just ran this code in a brand new Rails app with Delayed::Job installed (modified from what you provided):
class List attr_accessor :id end @list = List.new @list.id = 123 class ImportContact def initialize(list_id, csv_text) @list_id = list_id @csv_text = csv_text end def perform puts @list_id puts @csv_text.length end end csv_text = IO.read('test_2000_import_contacts.csv', :encoding => 'UTF-8').gsub(" ", "") csv_text = csv_text.gsub("\n\n", "\n") Delayed::Job.enqueue ImportContact.new(@list.id, csv_text), :queue => "import-list-#{@list.id}"
When I ran bundle exec rake jobs:work
, everything went through correctly, which would lead me to believe that there is a problem with the way YAML is encoding or decoding the file you are importing.
In particular, I would run
yaml = Delayed::Job.find(121).handler File.open('job-121.yml', 'w') { |f| f.write(yaml) }
And check through the file around line 6709 column 4
.
However, this might be about the time to suggest that you store your files in something like S3 and pass a URL to the ImportContact
worker rather than the entire CSV text. This will alleviate the current problem you are running into and help you avoid bloating your database with huge text columns.
Where is the "Store" menu in the Visual Studio 11 Beta? I just downloaded and installed the Ultimate version and there's no "Store" menu like I see in all the video tutorials.
-4153251 0Personally I'd suggest that you use an IOCP based design, but then I would say that as I have an IOCP based framework that I've used for years to develop high performance servers for clients.
I recently put together some of my reasons for prefering IOCP to the other models available on windows and they're available here on my blog here.
Often 'complexity' is cited as a reason to avoid IOCP, but, to be honest, if you're doing anything other than 'thread per connection' the code will be reasonably complex anyway. I have a free set of C++ code with example servers that you could take a look at, it does all the IOCP work for you and the server examples are a good starting point for your own code. You can get it from here.
Alternatively I also have a free (for non commercial use) pluggable server platform which might interest you. With WASP you simply write a dll with some specific entry points and I do all of the networking stuff for you... See here for the download and here for the tutorial.
Whichever model you decide on THE single most important thing, IMHO, is to start doing your performance and load testing from DAY 0. This way you KNOW how many concurrent connections you can support on your target hardware and you can quickly spot the inappropriate design decisions that cause this to drop. It's easy to squander the concurrency of your server. See here for more info.
Since Jay mentioned ENet... I've found that our IOCP based ENet server works well with the standard Enet client code. But remember, ENet is designed to be a peer to peer protocol and so there are some challenges when you start trying to use it on a server. With the standard ENet code you essentially have a single threaded network pump and that just can't compare to the scalability you get from IOCP. I ended up rewriting the ENet protocol handling code from scratch to work with async I/O and IOCP and that's a non trivial amount of work. I'm currently doing a new version of this code which uses the latest ENet protocol as a base and hopefully this will be available early in 2011 with complete perf comparisons to the standard ENet code used in large number of concurrent connection server situations.
-1874361 0try investigating this in steps first
SELECT * FROM Appts WHERE Appts.dr_id = 101
if that returns 2 rows the data is ok in your appts table
then add
SELECT a.patient_id ,p.* FROM Appts A LEFT JOIN Patients p ON Appts.patient_id = p.patients_user_id WHERE Appts.dr_id = 101
if you see null values returned in p.* part, then there is something wrong with your join condition, you may be joining on a wrong field. or the patient record for corresponding patient_id is missing in the Patients table
-39016420 0Use a logic OR to combine your streams into only one stream:
public static void main(String[] args) { Stream<String> stream = Stream.of("abc", "aef", "bcd", "bef", "crf"); stream.filter(s -> s.startsWith("a") || s.startsWith("b")).forEach(System.out::println); }
-10200603 0 That's a UIActionSheet
. To make the picture tap sensitive, you can attach a UIGestureRecognizer
to it.
I want to make a menu like this in wpf
I wrote this code:
<MenuItem Header="Menu 4" MouseEnter="mousecom" Background="DarkGreen"> <MenuItem.ContextMenu> <ContextMenu> <MenuItem Header="submenu 1"/> <MenuItem Header="submenu 2"/> </ContextMenu> </MenuItem.ContextMenu> </MenuItem>
and mousecom
is:
private void mousecom(object sender, MouseEventArgs e) { while (IsMouseOver) { (sender as Button).ContextMenu.IsEnabled = true; (sender as Button).ContextMenu.PlacementTarget = (sender as Button); (sender as Button).ContextMenu.Placement = System.Windows.Controls.Primitives.PlacementMode.Right; (sender as Button).ContextMenu.IsOpen = true; } }
I mean I wanna have a MenuItem and by coming mouse on it another menu opens including some other MenuItems.
Why it doesn't work?
how can I do that? (please pay attention to the picture)
-31929334 0I wrote a simple method below to check if there is a trailing hashtag/pound sign/number sign that returns a boolean.
import java.util.regex.Matcher; import java.util.regex.Pattern; public boolean hasHashTag(String url) { int index = url.lastIndexOf("#"); if(index == -1) { return false; } else { Pattern p = Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE); Matcher m = p.matcher(url.substring(index+1)); System.out.println(url.substring(index+1) + " "+ (index + 1)); return !m.find(); } }
You can now use this method to filter out the duplicates.
if(hasHashTag(URLHERE)) { //don't add to urls to search } else { //add url to search }
-35203419 0 Style one word from a sentence Hello I have This sentence:
"Starbucks open-hours are from 7-17. Please choose another time!"
I want to make the numbers "7-17" bold and red so that users can see it easier.
This whole sentence is stored in a @Umbraco.GetDictionaryValue:
@Umbraco.GetDictionaryValue("BookingStep1_ClosedPickup") which then in view shows the sentence above.
How can I target the numbers only?
<div class="coffees"> <div class="message"> {{if (!data.location.matchHoursPickup) { }} {{if (data.location.closedPickup) { }} @Umbraco.GetDictionaryValue("BookingStep1_ClosedPickup") {{ }else{ }} {{= data.closedPickupMsg }} {{ } }} {{ }else{ }} {{ if (data.location.closedDelivery){ }} @Umbraco.GetDictionaryValue("BookingStep1_ClosedDelivery") {{ }else{ }} {{= data.closedDeliveryMsg }} {{ } }} {{ } }} </div> </div>
-9750498 0 preg_match_all('/\[(.*?)\]/', $string, $out); foreach ($out[1] as $k => $v) { eval("\$result = $v;"); $string = str_replace($out[0][$k], $result, $string); }
This code is highly dangerous if the strings are user inputs because it allows any arbitrary code to be executed
-10258429 0I have set up a simulation here and comments will describe the steps.
First I generate some data: a series of tuples each containing a string and two random numbers representing score A and B.
Next I divide the ranges of A and B into five equally spaced bins, each representing the minimum and maximum for a cell.
Then I serially query the data set to extract the strings in each cell.
There are a hundred ways of optimizing this, based on the actual data structure and storage you are using.
from random import random # Generate data and keep record of scores data = [] a_list = [] b_list = [] for i in range(50): a = int(random()*500)+1 b = int(random()*500)+1 rec = { 's' : 's%s' % i, 'a' : a, 'b' : b } a_list.append(a) b_list.append(b) data.append(rec) # divide A and B ranges into five bins def make_bins(f_list): f_min = min(f_list) f_max = max(f_list) f_step_size = (f_max - f_min) / 5.0 f_steps = [ (f_min + i * f_step_size, f_min + (i+1) * f_step_size) for i in range(5) ] # adjust top bin to be just larger than maximum top = f_steps[4] f_steps[4] = ( top[0], f_max+1 ) return f_steps a_steps = make_bins(a_list) b_steps = make_bins(b_list) # collect the strings that fit into any of the bins # thus all the strings in cell[4,3] of your matrix # would fit these conditions: # string would have a Score A that is # greater than or equal to the first element in a_steps[3] # AND less than the second element in a_steps[3] # AND it would have a Score B that is # greater than or equal to the first element in b_steps[2] # AND less than the second element in a_steps[2] # NOTE: there is a need to adjust the pointers due to # the way you have numbered the cells of your matrix def query_matrix(ptr_a, ptr_b): ptr_a -= 1 from_a = a_steps[ptr_a][0] to_a = a_steps[ptr_a][1] ptr_b -= 1 from_b = b_steps[ptr_b][0] to_b = b_steps[ptr_b][1] results = [] for rec in data: s = rec['s'] a = rec['a'] b = rec['b'] if (a >= from_a and a < to_a and b >= from_b and b < to_b): results.append(s) return results # Print out the results for a visual check total = 0 for i in range(5): for j in range(5): print '=' * 80 print 'Cell: ', i+1, j+1, ' contains: ', hits = query_matrix(i+1,j+1) total += len(hits) print hits print '=' * 80 print 'Total number of strings found: ', total
-24993812 0 How can I write diagonal text in PHP I want to import some timestamps from a table and I want to write them diagonal under the graph. How can I do that?
here is my code, but not for the import data.
header("Content-type: image/png"); $img = imagecreate(100, 75); $bg = imagecolorallocate($img, 255, 255, 0); $black = imagecolorallocate($img, 0, 0, 0); $roles = array('anoniem', 'ingelogd', 'leerling', 'docent', 'rector'); $left = 0; foreach ($roles as $role) { imagestring ($img, 2, 0, $left, $role, $black); $left+= 15; } $img2 = imagerotate($img, 45, $bg); imagedestroy($img); imagepng($img2);
-5000562 0 You'd use contextual binding and/or .Named()
. Fortunately the relevant docs have yet to be updated to Ninject V2 syntax (but watch this space on the wiki...) have lots of examples of different mechanisms now.
On a very basic level, you use <xsl:apply-templates>
when you want to let the processor handle nodes automatically, and you use <xsl:call-template/>
when you want finer control over the processing. So if you have:
<foo> <boo>World</boo> <bar>Hello</bar> </foo>
And you have the following XSLT:
<xsl:template match="foo"> <xsl:apply-templates/> </xsl:template> <xsl:template match="bar"> <xsl:value-of select="."/> </xsl:template> <xsl:template match="boo"> <xsl:value-of select="."/> </xsl:template>
You will get the result WorldHello
. Essentially, you've said "handle bar and boo this way" and then you've let the XSLT processor handle these nodes as it comes across them. In most cases, this is how you should do things in XSLT.
Sometimes, though, you want to do something fancier. In that case, you can create a special template that doesn't match any particular node. For example:
<xsl:template name="print-hello-world"> <xsl:value-of select="concat( bar, ' ' , boo )" /> </xsl:template>
And you can then call this template while you're processing <foo>
rather than automatically processing foo
's child nodes:
<xsl:template match="foo"> <xsl:call-template name="print-hello-world"/> </xsl:template>
In this particular artificial example, you now get "Hello World" because you've overriden the default processing to do your own thing.
Hope that helps.
-8915778 0For 8 and 16 bit it's pretty obvious, you can track every possibility every iteration.
When you get to 32 and 64 bit integers, you don't really have the memory to track every possibility.
Here's a few natural suggestions that are likely outside the bounds of your constraints.
I don't really understand why you can't sort the array. RadixSort is O(n) and once sorted it would be one more pass to get accurate distinctiveness and top X information. In reality it would be 6 passes all together for 32bit if you used a 1 byte radix (1 pass for counting + 1 * 4 passes for each byte + 1 pass for getting values).
In the same cusp as above, why not just use SQL. You could create a stored procedure that takes the array in as a table valued parameter and return the number of distinct values and the top x values in one go. This stored procedure could also be called in parallel.
-- number of distinct SELECT COUNT(DISTINCT(n)) FROM @tmp -- top x SELECT TOP 10 n, COUNT(n) FROM @tmp GROUP BY n ORDER BY COUNT(n) DESC
-37026074 0 We can use python regular expression search module to get it done in efficient way.
import re matchobj = re.search(r"xyz",given_text) if matchobj: print "Found" else: print "Not Found"
-37828617 0 Drag and Drop not working, if application lies in specific directory I implemented a drag and drop functionality in an Qt application (In case you want to see some code, see below). I thought everything is working fine until a user told me that it is not working for him.
Usually you see this icon, if
dragEnterEvent()
does not call event->acceptProposedAction()
, then you see this icon. And if the issue occurs you see an icon similar to this
(It's not exactly that icon, but I am not able to capture it, as windows removes the mouse icon in screenshots).
We could find out that on some computers (not for me sadly, so debugging that is quite hard) it depends on the setup. In particular the installation path: If the application lies in one specific directory (or one of its subdirectories) the described error occurs. If we move the whole application directory somewhere else and execute it from there, everything works fine.
Adding some debug output showed that the dragEnterEvent() does not fire in the broken setup.
What could be the reason? How can I debug that issue?
We had some suspicions but nothing that realy makes sense. But I want to share them anyway:
Code snippet:
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), /* more here */ { /* more here */ setAcceptDrops(true); /* more here */ } void MainWindow::dragEnterEvent(QDragEnterEvent* event) { const QMimeData* mimeData = event->mimeData(); if (mimeData->hasUrls()) { QString fileName = mimeData->urls().at(0).toLocalFile(); QFileInfo file(fileName); if(isSupportedFileType(file.completeSuffix())) { event->acceptProposedAction(); } } } void MainWindow::dropEvent(QDropEvent *event) { const QMimeData* mimeData = event->mimeData(); if (mimeData->hasUrls()) { QList<QUrl> urlList = mimeData->urls(); if(openFiles(urlList)) { event->acceptProposedAction(); } } }
-29296179 0 I was using the default HTTP server in org.restlet.jar wich seems to produce strange results. Since I switch to Jetty everything works as expected (average response time is 50-70 ms)
-14051119 0Here's one way using awk
:
awk -F "[{}]" '{ for(i=1;i<=NF;i++) if ($i == "ctr") print $(i+1) }' file
Or if your version of grep
supports Perl-like regex:
grep -oP "(?<=ctr{)[^}]+" file
Results:
StaffLine
-4273975 0 Have a look at this question, it is essentially asking the same thing - the principle does not change between DataGridView
and ListBox
. Short answer: it's possible, but convoluted.
First, I should say that I also recommend Will Buck's WIP branch answer, since they are easy to create and destroy, and they are lightweight.
Anyways, what you are asking is possible.
You can create a set of patches from a set of commits, copy them to the USB and then apply them in your home.
All of these steps can be done with: git format-patch and git am.
git format-patch
will generate a list of patch files from the commits you specify.
git am
will apply specified patch files on top of your HEAD
.
The progit book has more information on how to work with these commands.
-1664621 0Use snprintf()
to find out how many characters you need:
#include <float.h> /* DBL_DIG */ #include <stdio.h> #include <stdlib.h> int main(void) { double x = rand() / (double)RAND_MAX; char find_len[1]; int need_len; char *buf; need_len = snprintf(find_len, 1, "%.*g", DBL_DIG, x); buf = malloc(need_len + 1); if (buf) { int used = sprintf(buf, "%.*g", DBL_DIG, x); printf("need: %d; buf:[%s]; used:%d\n", need_len, buf, used); free(buf); } return 0; }
You need a C99 compiler for snprintf()
.
snprintf()
was defined by the C99 standard. A C89 implementation is not required to have snprintf()
defined, and if it has as an extension, it is not required to "work" as described by the C99 Standard.
I have written this simple service for doing subrequest via HTTPBuilder, to get instance of class representing obtained page for further use:
package cmspage import groovyx.net.http.HTTPBuilder import static groovyx.net.http.Method.GET import static groovyx.net.http.ContentType.HTML class CmsPageService { static transactional = false final String SUBREQUEST_HOST = "www.mydomainforsubrequest.com" CmsPage getCmsPageInstance(Object request) { String host = request.getServerName() String url = request.getRequestURI() HashMap queryMap = this.queryStringToMap(request.getQueryString()) return this.subRequest(host, url, queryMap) } CmsPage getCmsPageInstance(String host, String url, String queryString = null) { HashMap queryMap = queryStringToMap(queryString) return this.subRequest(host, url, queryMap) } private CmsPage subRequest(String host, String url, HashMap queryMap = null) { CmsPage cmsPageInstance = new CmsPage() HTTPBuilder http = new HTTPBuilder() http.request("http://" + SUBREQUEST_HOST, GET, HTML) { req -> uri.path = url uri.query = queryMap headers.'X-Original-Host' = 'www.mydomain.com' response.success = { resp, html -> cmsPageInstance.responseStatusCode = resp.status if (resp.status < 400) { cmsPageInstance.html = html } } response.failure = { resp -> cmsPageInstance.responseStatusCode = resp.status return null } } return cmsPageInstance } private HashMap queryStringToMap(String queryString) { if (queryString) { queryString = queryString.replace("?", "") String[] splitToParameters = queryString.split("&") HashMap queryMap = new HashMap() splitToParameters.each { String[] split = it.split("=") for (int i = 0; i < split.length; i += 2) { queryMap.put(split[i], split[i + 1]) } } return queryMap } else return null } }
Now I need to write unit test for this service. I would like to use some simple html document to test it instead of testing some "live" site. But I do not know how? Can anybody help me?
-29052508 0 Sending email Intent with EXTRA_STREAM crashes with GMailI'm trying to send an email from my app with attachment. When the chooser pops up, if I tap on GMail, GMail crashes; if I tap on the default email client of my device, it works perfectly. The attachment is a jpeg taken from the external sd.
Here the code:
filelocation = gv.getPath(); Intent emailIntent = new Intent(Intent.ACTION_SEND); // set the type to 'email' emailIntent.setType("image/jpeg"); String to[] = {"myemailaddress@gmail.com"}; emailIntent.putExtra(Intent.EXTRA_EMAIL, to); // the attachment emailIntent.putExtra(Intent.EXTRA_STREAM, filelocation); // the mail subject emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject"); emailIntent.putExtra(Intent.EXTRA_TEXT, "Body"); emailIntent.setType("message/rfc822"); startActivity(Intent.createChooser(emailIntent, "Send email using:"));
Here the logcat:
03-14 19:03:26.081 27428-27428/com.android.myapp W/Bundle﹕ Key android.intent.extra.STREAM expected Parcelable but value was a java.lang.String. The default value <null> was returned. 03-14 19:03:26.111 27428-27428/com.android.myapp W/Bundle﹕ Attempt to cast generated internal exception: java.lang.ClassCastException: java.lang.String cannot be cast to android.os.Parcelable at android.os.Bundle.getParcelable(Bundle.java:1171) at android.content.Intent.getParcelableExtra(Intent.java:4493) at android.content.Intent.migrateExtraStreamToClipData(Intent.java:7032) at android.content.Intent.migrateExtraStreamToClipData(Intent.java:7017) at android.app.Instrumentation.execStartActivity(Instrumentation.java:1548) at android.app.Activity.startActivityForResult(Activity.java:3409) at android.app.Activity.startActivityForResult(Activity.java:3370) at android.support.v4.app.FragmentActivity.startActivityFromFragment(FragmentActivity.java:826) at android.support.v4.app.Fragment.startActivity(Fragment.java:896) at com.android.myapp.steps.Passo3$2.onClick(Passo3.java:100) at android.view.View.performClick(View.java:4107) at android.view.View$PerformClick.run(View.java:17160) at android.os.Handler.handleCallback(Handler.java:615) at android.os.Handler.dispatchMessage(Handler.java:92) at android.os.Looper.loop(Looper.java:155) at android.app.ActivityThread.main(ActivityThread.java:5536) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:511) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1074) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:841) at dalvik.system.NativeStart.main(Native Method)
Any suggestion? Every help will be greatly appreciated! :)
-25425052 0The site http://research.microsoft.com/en-us/um/people/zliu/ActionRecoRsrc/ tells you exactly how they're organised. They also provide some C++ example loaders.
"The format of the skeleton file is as follows. The first integer is the number of frames. The second integer is the number of joints which is always 20. For each frame, the first integer is the number of rows. This integer is 40 when there is exactly one skeleton being detected in this frame. It is zero when no skeleton is detected. It is 80 when two skeletons are detected (in that case which is rare, we simply use the first skeleton in our experiments). For most of the frames, the number of rows is 40. Each joint corresponds to two rows. The first row is its real world coordinates (x,y,z) and the second row is its screen coordinates plus depth (u, v, depth) where u and v are normalized to be within [0,1]. For each row, the integer at the end is supposed to be the confidence value, but it is not useful."
Hope this helps.
-11966889 0How about that?
int lastPlayer = match.currentPlayer > 1 ? match.currentPlayer - 1 : match.numberOfPlayers;
-4164004 0 How should my "App IDs" section look like? I know there are many other questions out there, but I can't seem to find exactly what I want.
Let's say that I'm having 5 apps right now:
Should I just have a generic App ID, like ABCDE12345.* with which I can sign apps like App4 and App5 (and all the new ones in the future, that don't need IAP etc), then ABCD123456.myCompany.App3 for App3 and then ABC1234567.myCompany.myApp.* for App1 and App2?
Does this sound the right way, or I get it totally wrong? Or, in different words, how does your App IDs look like? :)
Thanks for any insight!
-32258170 0In the future, you could run your spec suite with the -p
flag, this will add profiling to your output and show you which specs run the slowest.
From rspec --help
:
-p, --[no-]profile [COUNT] Enable profiling of examples and list the slowest examples (default: 10).
-37102304 0 Thats because your Tag
is Null
(or as it's called in VB Nothing
). So before you check the length of the Tag, you need to make sure it's not Nothing
. e.g with:
If Control.Tag Is Nothing Then ...
-36075045 1 How to edit the PRO -FORMA button in the account.invoice model? I 'm doing a function that executes when the PRO -FORMA press the button account.invoice model.
I tried but I have not found a default function of this button to edit it. So I created a function does not work.
Does anyone know where I could edit the function of this button or create a function ?
At the view, the button is as follows:
`<button name="invoice_proforma2" states="draft" string="PRO-FORMA" groups="account.group_proforma_invoices"/`>
And this is the function of the button , but does not work . This in account.invoice.py file :
@api.multi def invoice_proforma2(self): for invoice in self: invoice.x_id_proforma = self.env['ir.sequence'].next_by_code('account.invoice.x_id_proforma')
I would appreciate some help to understand why this does not work . Thank you.
-17095731 0And additionally in Qt5 you can set QTimer's precision: Qt::TimerType
-4493128 0I think it is because clr virtual machine uses cpu directly without code opcode translation. It may be optimization for clr application or may be windows mobile/window phone 7 started on INTEL proccessor. Android platform based on linux and theoretically you can start android on virtual machine in i686 environment. In this case virtual machines such as vmware could execute some opcodes direcly. But this option will be allowed only if you write on the Java. Because the Java interpret their byte-code or precompile it before execution. see: http://www.taranfx.com/how-to-run-google-android-in-virtualbox-vmware-on-netbooks
-2477195 0 LaTeX indentation (formatting) in Emacswhat is the correct way to do indentation of a LaTeX document in Emacs (AucTex)?
For example when I have a list:
\begin{itemize} \item orem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam enim urna, mattis eu aliquet eget, condimentum id nibh. In hac habitasse platea dictumst. \item orem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam enim urna, mattis eu aliquet eget, condimentum id nibh. In hac habitasse platea dictumst. \end{itemize}
and would like to ended up with:
\begin{itemize} \item orem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam enim urna, mattis eu aliquet eget, condimentum id nibh. In hac habitasse platea dictumst. \item orem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam enim urna, mattis eu aliquet eget, condimentum id nibh. In hac habitasse platea dictumst. \end{itemize}
I tried indent-region
but it doesn't do anything and the LaTeX-fill-*
produces weird results like:
\begin{itemize} \item orem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam enim urna, mattis eu aliquet eget, condimentum id nibh. In hac habitasse platea dictumst. \item orem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam enim urna, mattis eu aliquet eget, condimentum id nibh. In hac habitasse platea dictumst. \end{itemize}
Thanks!
-12334907 0I agree with guillaume31 that there is no need to introduce a domain object "UsersPerPermission" to support a single use case.
There are two ways you can implement your use case using existing domain classes "User", "Role" and "Permission".
Solution one:
Assume you have: Permission --> Role --> User
Arrow denotes navigability. A Permission has association to a list of Roles and a Role has association to a list of Users.
I would add a method GetPermittedUsers() : List<User>
to the Permission class, which is trivial to implement.
Th UI logic will invoke GetPermissions() of PermissionRepository then call GetPermittedUsers() on each Permission.
I assume that you use a ORM framework like hibernate(Nhibernate) and defines the many-to-many relationships correctly. If you defines eager loading for Role and User from Permission, the ORM will generate a query that joins Permission, Role and User tables together and load everything in one go. If you defines lazy loading for Role and User, you will load a list of Permissions in one query when you call PermissionRepository, and then load all associated Roles and Users in another query. Everything is load from database with up to three queries maximum. This is called a 1+n problem which most ORMs handle properly.
Solution two:
Assume you have: User --> Role --> Permission
Arrow denotes navigability. A User has a list of Roles. A role has a list of Permission.
I'd add getUsersByPermissions(List<long> permissionIds) : List<Users>
to the UserRepository, and add getPermissions() : List<Permission>
to the User class.
The implementation of the UserRepository need to join the User, Role and Permission tables together in a single query and load everything in one go. Again, most ORMs will handle it correctly.
Once you have a list of Users, you can create a method to build a Map<Permission, List<User>>
quite easily.
To be honest, I muck like the solution one. I avoid to write a complicate method to convert a List of Users to to a map of Permission and Users, hence I don't need to worry about where to put this method. However solution one may create cyclic relationship between User, Role and Permission classes if you already have navigability in another direction. Some people don't like cyclic relationship. I think the cyclic relationship is acceptable even necessary sometime if you user cases demand it.
-2361481 0Use generic web handler. i.e. ashx. These are even faster than MVC actions.
-19062739 0 TinyMCE 4 not showing toolbar icons in IE9 (any mode)TinyMCE has this easy to use code, but I cannot see the toolbar icons in IE9 (the imgs don't load it seems).
<html> <head><!-- CDN hosted by Cachefly --> <script src="//tinymce.cachefly.net/4.0/tinymce.min.js"></script> <script> tinymce.init({selector:'textarea'});</script> </head> <body> <textarea>Your content here.</textarea> </body> </html>
I've seen this similar post (tinymce icons in internet explorer), but the advice made no difference for me.
I've tried putting the browser in different modes, nothing worked. The only time I saw it work in IE was inside the EditPlus embedded browser, but I don't know exactly what that is.
Works nicely in Chrome.
EDIT- does work in IE when the file is loaded directly, eg. C:\inetpub\wwwroot\tiny.html
Thanks.
-39009139 0 Pass Input stream over HTTP in mule using HTTP connectorI have a requirement to pass the input stream over HTTP. I am reading the file using the File connector in mule and passing the input stream to the HTTP connector. The file size is going to be huge ranging from 250 mb to ~ 10 gb. I am trying with a 700 mb file and HTTP connector runs out of memory. I think the connector is loading everything into memory. Why is it not passing it as the stream. Let me know what is the best way to do this.
-20890556 0Build with the static runtime libraries rather than the DLL versions.
Go to Properties, C/C++, Code Generation, Runtime Library and select /MTd or /MT rather than the /MDd and /MD options.
-38621273 1 Dropzone doesn't redirect after upload to Flask appI'm writing a resource to upload files to a Flask app using Dropzone. After files are uploaded the app should redirect to the hello world page. This is not happening and the app is stuck on the view that uploaded the files. I'm using jQuery 3.1.0 and Dropzone from master.
from flask import Flask, request, flash, redirect, url_for render_template) from validator import Validator ALLOWED_EXTENSIONS = set(['csv', 'xlsx', 'xls']) def allowed_file(filename): return (filename != '') and ('.' in filename) and \ (filename.split('.')[-1] in ALLOWED_EXTENSIONS) def create_app(): app = Flask(__name__) app.secret_key = 'super secret key' return app app = create_app() @app.route('/') def index(): return render_template('index.html') @app.route('/world') def hello_world(): return render_template('hello_world.html') @app.route('/upload', methods=['POST']) def upload(): # check that a file with valid name was uploaded if 'file' not in request.files: flash('No file part') return redirect(request.url) file = request.files['file'] if not allowed_file(file.filename): flash('No selected file') return redirect(request.url) # import ipdb; ipdb.set_trace() validator = Validator(file) validated = validator.validate() if validated: flash('Success') else: flash('Invalid file') return redirect(url_for('hello_world')) if __name__ == '__main__': app.run(debug=True)
{% extends "base.html" %} {% block head %} <link href="/static/css/dropzone.css" rel="stylesheet"> <script src="/static/js/dropzone.js"></script> {% endblock %} {% block body %} <main> <section> <div id="dropzone"> <form action="upload" method="post" class="dropzone dz-clickable" id="demo-upload" multiple> <div class="dz-message"> Drop files here or click to upload. </div> </form> </div> </section> </main> {% endblock %}
-21120398 0 XAML Vertically align only top stackpanel I have a view that contains two stackpanels (main ones). The top one is a spinner and "One Moment Please..." that I need centered vertically. The bottom one appears when the top one disappears and I need it stretched so the content appears at the top of the window.
<ScrollViewer VerticalScrollBarVisibility="Auto"> <StackPanel HorizontalAlignment="Stretch" VerticalAlignment="Center"> <local:BusyIndicator VerticalAlignment="Center" HorizontalAlignment="Center" Width="50" Height="50" Visibility="{Binding Path=IsBusy, Converter={StaticResource booleanToVisibilityConverter}}"/> <TextBlock VerticalAlignment="Center" HorizontalAlignment="Center" Text="One Moment Please" Visibility="{Binding Path=IsBusy, Converter={StaticResource booleanToVisibilityConverter}}"/> <StackPanel HorizontalAlignment="Center" Visibility="{Binding Path=HasError, Converter={StaticResource booleanToVisibilityConverter}}"> <TextBlock Visibility="{Binding Path=HasError, Converter={StaticResource booleanToVisibilityConverter}}" Text="{Binding Path=ErrorMessage}" VerticalAlignment="Center" HorizontalAlignment="Center" FontSize="12" TextWrapping="Wrap"/> </StackPanel> <StackPanel VerticalAlignment="Stretch" Orientation="Vertical" Visibility="{Binding Path=IsBusy, Converter={StaticResource inverseBooleanToVisibilityConverter}}"> </Stackpanel> </ScrollViewer>
The issue that keeps happening is that the bottom stackpanel is vertically centered and the content does not move to the top of the window.
I apologize but I am not able to show the actual view (NDA). What I am trying to do (Right Image), what is happening (Left Image). NOTE: Only the text or the spinner show up at one time. I am not trying to align the two, just make the spinner center vertically when the text is not displayed.
Basically I have a WCF hosted in multiple Windows Services (before anyone asks IIS cannot be used for multiple and very valid reasons). I have a control application that allows the Windows Services to be stop/started/restarted in special orders (with several differing parameters) etc but I need some way of knowing what address each windows service is hosting i.e. a function that either
or better still
Any ideas, code or thoughts on this folks?
Thanks in advance for taking the time,
Brian
-38430119 0Try this:
SELECT * FROM table_name WHERE date_time + INTERVAL 90 DAY <= NOW()
-26251058 0 Place an index on the date field, optionaly including the ID field if you need sorting or extra lookup base on the ID field. That is what an INDEX is for, to speed up lookup, sorting etc. Take a look at this article for more explanation: SQL Server Index Design Guide (technet.microsoft.com).
-38569468 0Use event.stopPropagation method of Event
. There is a mistake in your second code snippet where you do not pass event
to the anonymous function. Fixed code:
<div onclick="(function(e) { e.preventDefault(); e.stopPropagation(); })(event)">
If you are wanting to use 1
then you would just need to establish a this.props.enabled === 1
variable somewehre to hold the true and false value.
Personally I would have enabled be a boolean value of true
or false
as it adds unnecessary complexity to make it a number.
<span className={this.props.enabled === 1 ? "Active" : 'Disabled'}></span>
-18149136 0 emacs does not uses fonts from /usr/share/fonts Can't win in emacs font battle under Debian Linux+fluxbox.
Should be mentioned that I have absolutely no expirience in fontconfig, so mb I am missing something obvious.
I am trying to use some system fonts from /usr/share/fonts like DejaVu under emacs but no luck.
I tried:
1. Mentioned on many resources commands like
(set-default-font "DejaVu Sans Mono-12")
returns "Font not available" for almost any fontname I tried.
2.
Shift+Mouse-Left-Click->Change Text Font ->
gives very little list of available fonts with two or three and different sizes.
3. I tried:
ln -s /usr/share/fonts ~/.fonts
and nothing
4. tried using xset method for(found such method on archlinux wiki and blindly tested):
cd /usr/share/fonts/truetype/ttf-dejavu sudo mkfontdir xset +fp /usr/share/fonts/truetype/ttf-dejavu xset fp rehash
nothing
5. I even straced emacs for any acces to directories with font name:
2>&1 strace -f emacs-24.3.1 > ./t.txt
but
grep -i font ./t.txt
gives only:
[pid 18809] writev(3, [{"b\1\6\0\17\0\1\0", 8}, {"XFree86-Bigfont", 15}, {"\0", 1}], 3) = 24
and nothing about directories like ~/.fonts or /usr/share/fonts
At the same time:
% fc-list|grep -c deja 42
How does it work?:( Mb i dont understand some main idea?
UPDATE: I've used opensoop -v to monitor what path uses emacs on my laptop (under os x) to get fonts but this has nothing with linux paths ofc:(
Can someone under the linux trace emacs for opening fonts to give a hint what paths I should configure.
2>&1 strace -f emacs |grep -i font
will be enough i think
-18517317 0Run "Clean" followed by "Rebuild" using Visual Studio. This fixed the problem for me.
-20470614 0A very useful operator here is <|>
from the Alternative
class in Control.Applicative
. For Maybe
, it works like this:
Just a <|> _ = Just a Nothing <|> Just a = Just a Nothing <|> Nothing = Nothing
We can also take advantage of the fact that x || x == x
is always true. This lets us write the following:
orMaybe a b = liftA2 (||) (a <|> b) (b <|> a) <|> Just False
If both a
and b
are Just x
, the liftA2 (||)
results in Just (a || b)
. If one of them is Nothing
, the (a <|> b)
and (b <|> a)
turn into either both a
or both b
, resulting in Just (a || a)
or Just (b || b)
. Finally, if both are Nothing
, we get liftA2 (||) Nothing Nothing
which leads to Nothing
. The final <|> Just False
then turns the whole expression into Just False
.
Now, I think this is a fun exercise to work through. But would I actually use this code? No! For Maybe
, Nothing
usually signifies failure and propagates; since you're using some very non-standard behavior, it's better to be explicit and pattern-match all the cases instead.
Note: liftA2
comes from Control.Applicative
. It's just like liftM
but for applicatives; I used it for consistency with <|>
. You could have used fmap
as well.
my problem is simple. Im using RichFaces 4.3.2 final and making programatically dynamic panelMenu. I managed to do that and use setOnClick("menuGroupAction('"+labelOfGroup+"')") to each UIPanelMenuGroup and UIPanelMenuItem. labelOfGroup varies depending on items from DB. menuGroupAction is a4j:jsAction used as:
<h:form> <a4j:jsFunction name="menuGroupAction" actionListener="#{leftMenu.updateCurrent}" render=":contentForm:test" > <a4j:param name="param1" /> </a4j:jsFunction> </h:form>
Problem is when i click on the TOP submenu param1
is changing as expected, but when i try to click on any inner submenu onclick is fired BUT with param1
of its top menu, even though the inner submenu has onclick="menuGroupAction('itslabel')". Any idea why is it happening? Im checking which parametter was posted with
String param1 = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("param1");
Another thing, when clicked on UIMenuItem in any submenu there are actually TWO calls of menuGroupAction, one with param of Top menu and another with correct param of menuItem. Thanks for response and sorry for bad english.
UPDATE
heres how i use rich:panelMenu on page
<h:form> <rich:panelMenu binding="#{leftMenu.menuCategories}" groupMode="ajax" itemMode="ajax" bubbleSelection="false" ></rich:panelMenu> </h:form>
heres getter for panelMenu model menuCategories
/** * @return the menuCategories */ public UIPanelMenu getMenuCategories() { if(menuCategories == null){ menuCategories = menuService.createCategoriesUIPanelMenu(); } return menuCategories; }
and heres how i create UIPanelMenu
public UIPanelMenu createCategoriesUIPanelMenu(){ List<Category> allTopCategories = catOper.getAllTopCategories(); int menulevel = 1; sortByOrderOfCategories(allTopCategories); UIPanelMenu categories = new UIPanelMenu(); categories.setTopGroupClass("button"); for (Category category : allTopCategories) { UIPanelMenuGroup topMenuCategory = new UIPanelMenuGroup(); topMenuCategory.setLabel(category.getName()); topMenuCategory.setOnclick("menuGroupAction('"+category.getName()+"')"); rekursiveCategoriesMenuGroupSetter(topMenuCategory,category,menulevel); categories.getChildren().add(topMenuCategory); } return categories; } private UIPanelMenuGroup rekursiveCategoriesMenuGroupSetter(UIPanelMenuGroup parent, Category category, int menuLevel){ int level = menuLevel+1; List<Category> allTopCategories = (List<Category>) category.getCategoryCollection(); sortByOrderOfCategories(allTopCategories); for (Category child : allTopCategories) { if(!child.getCategoryCollection().isEmpty()){ UIPanelMenuGroup subGroup = new UIPanelMenuGroup(); subGroup.setLabel(child.getName()); subGroup.setLeftIconClass("menuLevel"+level); subGroup.setOnclick("menuGroupAction('"+child.getName()+"')"); parent.getChildren().add(subGroup); rekursiveCategoriesMenuGroupSetter(subGroup,child,level); } else{ UIPanelMenuItem item = new UIPanelMenuItem(); item.setLabel(child.getName()); item.setLeftIconClass("menuLevel"+level); item.setOnclick("menuGroupAction('"+child.getName()+"')"); parent.getChildren().add(item); } } return parent; }
UPDATE
Strange i tried it on clean page and come to some interesting news. When theres set default groupMode aka 'client' that when clicked on some inner group there are TWO calls of that action one with top submenu param and one with correct param of innersubmenu (same with server), which is a little step forward i suppose in comparison to calling ONLY with top submenu.
-14590461 0I'm a little confused to what you would like, would you like the PDO code to both update and delete items from your DB? If so I use this, I'm also new to PDO. Also try not to use ' around table/field names.
/** Code to update */ $query = "UPDATE tblNameRes SET name ='$name' WHERE id = :id"; $stmt = $db->prepare($query); $stmt->BindValue(':id', $id, PDO::PARAM_INT); $stmt->execute(); /** Code to delete */ $query = "DELETE FROM tblNameRes WHERE id = :id"; $stmt = $db->prepare($query); $stmt->BindValue(':id', $id, PDO::PARAM_INT); $query->execute();
Let me know if this helps, or is not what you wanted. I'm new here so I can't post 'comments'.
-38038098 0 rmarkdown html page loaded with warning messageI have created simple rmarkdown - flexboard html page, using MASS/painters dataset, preview looks fine, but as soon as view in browser, the html page loads with warning, with below below errors.
Please note I have used rpivottable and DT to present painters data. Any guidance would be helpful.
title: "Untitled" output: flexdashboard::flex_dashboard: orientation: columns vertical_layout: fill --- ```{r setup, include=FALSE} library(flexdashboard)
``` Column {data-width=650}
### Chart A ```{r} ``` Column {data-width=350}
### Chart B ```{r} ``` ### Chart C ```{r} ```
Webpage error details
User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; chromeframe/15.0.874.121; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; MS-RTC LM 8; InfoPath.3; .NET CLR 1.1.4322) Timestamp: Thu, 23 Jun 2016 10:58:22 UTC
Message: '$' is undefined Line: 833 Char: 5 Code: 0
Message: Object expected Line: 2562 Char: 1 Code: 0
Message: Object expected Line: 2599 Char: 1 Code: 0
I am using nodejs to write an image upload service. Paying clients will be able to send an image file to my endpoint that I have set up on my server. However, when every request comes in, I need to confirm that it is actually a paying client making the request. I thought about having the client give me their domain name and I would just check the referer header. However, someone could easily spoof the referer header and use my service without paying. How do SaaS developers face this technical problem? Is it possible to fix this without requiring my clients to have some server side code?
-11734787 0From the documentation:
You can also explicitly control the exact type of Map that will be instantiated and populated via the use of the 'map-class' attribute on the element.
So, for example, you can take DefaultedMap
from commons-collections
and try to use it as map-class
. Or you can implement your own Map
and use it.
Not within a list comprehension AFAIK.
You could certainly do it with a traditional for loop and the multiprocessing/threading modules.
-16837126 0 Exception caused by installed fontI want to ask this because I am a novice programmer, and quite frankly, I dont like weird errors popping up when they feel like it, and then seemingly solving themselves for no apparent reason, so I hope you can help me understand what is going on.
I am using "Cambria" as font for my Windows Forms app. I believe it comes preinstalled in w7 machines, but not in XP, and since I wanted to run the program on XP boxes as well, I went ahead and added the font files in the "Fonts folder" of my setup project. Before I did this, it was reverting back to Sans-Serif, making the interface really ugly (because of stretching and such, not that I dont like the font).
So, everything seemed to work fine and I was very happy, thinking my program was done. Just recently I had to come back to it to make some ammends, and...
A wild System.Reflection.TargetInvocationException
appeared!
And that was on program startup. I was perplexed. I hadn´t touched a line of the first form. Why was it failing to load now? I tested it before, and everything was ok... This happened only on XP, and I´m testing on a XP virtual machine, Home version, so debugging is kind of weird to set up.
I look at the stack from the system log. The error comes from InitializeComponent()
??? My perplexity level increased. I definitely did not touch that. Lets try and catch it to see what it has to say (since I cant get the debugger to work on the machine)... I catch it and the InternalException.Message
is:
The font "Cambria" does not support style "Regular"
I still don't know why does this error happen. But at least I now have a lead to follow. I check the fonts folder to see if the fonts are there, and I see that the cambria "regular" is slightly different... since it is "Cambria.ttc" while the others are "Cambria Bold.ttf". The other fonts are also .ttf. Can this be the problem?
So, I decide to run the program again and copy the text from the inner exception to goolge it up. And... it runs. I didn't touch a font. I just opened the fonts folder to see if the font was there, closed it, ran the application, and it worked.
What am I missing here? How can I make sure it doesn't happen again?
-19903937 0Use :
target="_blank"
in your a
tag.
If you want to follow jquery then use :
$('#imagelink').click(function() { var loc = $(this).attr("href"); window.open(loc, '_blank'); });
-38237580 0 Your problem is in this line:
for i in user_list: i.write(user_list, '\n')
Change it to this:
for i in user_list: wr.write(i, '\n')
EDIT: And remove user_list
parameter from all of your functions because it is a global variable and you can access it from within your any function. This may also be a reason why your list not getting saved.
You are likely using the wrong username to login:
ubuntu
ec2-user
root
or admin
To login, you need to adjust your ssh command:
ssh -l USERNAME_HERE -i .ssh/yourkey.pem public-ec2-host
HTH
-32398604 0Add a global boolean, for instance:
private bool isDragAndDrop;
Set it to false when loading the form. When the dragAndDrop event is fired you should set isDragAndDrop = true
.
When the Click event is fired you check if(!isDragAndDrop)
This will or will not execute the code inside the click event based on the value on the isDragAndDrop -variable.
Before leaving the click event you the set isDragAndDrop = false
Let's say that you have branches A
, B
, and develop
in your local git repository. In order to have develop
contain all commits except the large-scale deleting commit, do the following:
git checkout develop git rebase -i A
You will then get a screen that gives you a list of all your commits since the head of branch A
. Delete the line with the commit you don't want, and then save the file (usually the interface is in vi
, so entering :wq
will save and quit. Check out vi
documentation for more details). Once you've done that, the develop
branch will now have all the commits except the big deletion. Don't worry, though, because B
will still have the delete commit, and you can always go back to it by checking out branch B
if you want.
Caveats: you may end up with some conflict or other as a result of doing these operations. Also, there is no guarantee that you code will actually work; git is a text tool, not a "code" tool per-se.
-38761122 0You had a syntax error at this line:
result += "\" + movie.title + "\"-";
It should be fixed with:
result += '"' + movie.title + '"- ';
In JavaScript both double and single quotes can be used, in your case you want to print out double quotes ("
), you can "wrap" them in with a single quote ex: '"'
.
Interesting discussion on when to use double/single quotes can be found here.
var movies = [{ title: "Avengers", hasWatched: true, rating: 5 }, { title: "SpiderMan", hasWatched: false, rating: 4 }, { title: "LightsOut", hasWatched: true, rating: 6 }] // Print it out console.log(movies); // Print out all of them movies.forEach(function(movie) { var result = "You have "; if (movie.hasWatched) { result += "watched "; } else { result += "not seen "; } result += '"' + movie.title + '"- '; result += movie.rating + " stars"; console.log(result); });
Syntex error in closing of if block syntex.
1 <% if current_user.admin? && !current_user?(user) %> 2 <li><%= link_to "Admin", users_path %></li> 3 </end>
Error at line 3, replace line 3 ie </end> with <% end %>
I have a problem with C# class library and WCF Service Application. I built a class library with two classes Graph and Vertice. And they have few public methods inside. Then I created and published(IIS 7) a simple WCF Application, which uses this class library. Code:
public class GraphsService : IGraphsService { public Graph getGraph(int val) { return new Graph(val); } }
Of course publish process went fine, and I have an access to this WCF. And now the problem:
When I created an Client Application(Web) and added service reference to this project, I can access the method getGraph(int val) but it returns class which doesn't have any of the methods I implemented in class library. Code for client:
protected void Page_Load(object sender, EventArgs e) { GraphsServiceClient gc = new GraphsServiceClient(); Graph g = gc.getGraph(5); lblGraph.Text = g.ToString(); }
That line returns me
GraphsClient.GraphService.Graph
But I want it to return my overriden method ToString(which is implemented in class library). How can I make it works?'
My Graph class from Class Library(removed few methods:
public class Graph { protected List<Vertice> _vertices; public Graph() { this._vertices = new List<Vertice>(); } public Graph(int startValue) { this._vertices = new List<Vertice>(); this._vertices.Add(new Vertice(startValue)); } public List<Vertice> Vertices { get { return this._vertices; } } public Vertice getFirstVertice() { if (this._vertices.Count != 0) return this._vertices.First(); throw new GraphException("Graaph doesn't have any vertices in it!"); } public Vertice findVertice(int value) { foreach (Vertice v in this._vertices) { if (v.value == value) return v; } return null; } public Graph addVertice(Vertice v, bool undirected = true) { if (this._vertices.Contains(v)) throw new GraphException("There is already this vertice in graph!"); foreach (int val in v.Neighbours) { Vertice tmp = this.findVertice(val); if (tmp != null) { if (undirected) tmp.addNeighbour(v.value); } else throw new GraphException("There isn't a vertice " + val + " in graph so it can't be in neighbours list!"); } this._vertices.Add(v); return this; } public int[,] getAdjacencyMatrix() { int[,] adMatrix = new int[this._vertices.Count + 1, this._vertices.Count + 1]; Array.Clear(adMatrix, 0, adMatrix.Length); int l = 1; foreach (Vertice v in this._vertices) { adMatrix[0, l] = v.value; adMatrix[l, 0] = v.value; l++; } for (int i = 1; i < this._vertices.Count + 1; i++) { for (int j = 1; j < this._vertices.Count + 1; j++) { int val1 = adMatrix[i, 0]; int val2 = adMatrix[0, j]; Vertice v = this.findVertice(val1); if (v.hasNeighbour(val2)) adMatrix[i, j] = v.countNeighbours(val2); } } return adMatrix; } public string getAdjacencyMatrixAsString() { string ret = ""; int[,] adM = this.getAdjacencyMatrix(); for (int i = 0; i < Math.Sqrt((double)adM.Length); i++) { for (int j = 0; j < Math.Sqrt((double)adM.Length); j++) { if (i != 0 || j != 0) ret += adM[i, j] + "\t"; else ret += "\t"; } ret += "\n"; } return ret; } public override string ToString() { string ret = ""; foreach (Vertice v in this._vertices) { ret += "Vertice: " + v.value + " neighbours: "; foreach (int val in v.Neighbours) { ret += val + ", "; } ret = ret.Remove(ret.Length - 2); ret += "\n"; } ret = ret.Remove(ret.Length - 1); return ret; } }
-35750152 0 I am getting a resource not found error when building a project using the xamarin IDE When the project is built the following output file in abc_screen_toolbar.xml contains the error
<android.support.v7.widget.ActionBarContainer android:id="@+id/action_bar_container" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" style="?attr/actionBarStyle" android:touchscreenBlocksFocus="true" android:gravity="top">
also currently my project does not use any touch screen features.
Screenshot of the output file :
You probably need to add this:
textBox3.Text = itextBox3.ToString();
Did you debug your code? What are the problems.
What is the point of empty event handlers?
-29060056 0You can use jQuery for that. 1. Download jQuery: http://jquery.com/download/ 2. Include the script you downloaded into your webpage:
<script src='/path/to/downloaded/jquery'></script>
HTML code
<a id='#mylink' data-id='123>My link</a>
Javascript code
<script> $('#mylink').on('click', function() { $.get('different.php', {'id': $(this).attr('data-id')}, function(resonse) { // response variable contains your JSON from different.php script, so write here you JavaScript code that uses it }); }); </script>
Hope it helps.
-6490894 0use java's reflection mechanism
public void someFunction() {
this.getClass().getName();// returns name of class
}
so this way you don't need to pass any arguments
-24836212 0Select them using limit
and offset
:
SELECT * FROM table ORDER BY cpc DESC LIMIT 1 OFFSET 0;
Then:
LIMIT 1 OFFSET 1 LIMIT 1 OFFSET 2
and so on.
-3345917 0 Why can't I access my class through COM?I have a class library that I have written in C#.net. I want to register it with COM on my 64 bit windows machine so that I can create instances of it using CreateObject() in scripts (javascript, vbscript, whatever). So I created a setup project. I set the Target Platform of the setup project to x64. The class library project's Target platform is set for AnyCPU. I have created an Custom Action for the installer that does the registrtion of the driver manually and it looks like this...
RegistrationServices regsrv = new RegistrationServices(); if (!regsrv.RegisterAssembly(this.GetType().Assembly, AssemblyRegistrationFlags.SetCodeBase)) { throw new InstallException("Failed To Register driver for COM Interop"); }
I can attach the debugger to this process when it runs and know for certain that this registration occurs successfully.
For some reason, when I try to create an object of the class using CreateObject() it gives me an error saying "Could not create object named ...". However, if I run the script using the cscript.exe in the SysWOW64 folder (the 32bit folder) the object is created successfully and the rest of my script runs fine. So it appears as though the class is being successfully registered for 32bit but not for 64, OR that my project has a 32 bit dependancy and the 64bit Cscript host process can not create it because of that dependency. My class library does reference one other project that I wrote but it is also set to build for ANY CPU. So it should be good for 32 and 64 bit processes.
Does anyone have any suggestions on how I should track down this 32bit dependency?
-2548176 0Do you mean frequency or pitch ? If it's just a pure sinusoid and you want the frequency then you can just measure the time between zero crossings (crude) or use an FFT to get the power spectrum and then find the peak (more complex, more reliable).
-7705539 0It might be tricky to implement the same type of interface, but you could have your ListView
respond to the contents of a TextBox
by handling the TextBox
's TextChanged
event and filtering the list based on the contents. If you put the list in a DataTable
then filtering will be easy and you can repopulate your ListView
each time the filter changes.
Of course this depends on how many items are in your list.
-28949136 1 Checking native dependency library is installed in Python setup.pyI have a python application that requires a specific C library to be installed on the machine to build properly (usually installed via sudo yum install xxx
or sudo apt-get install xxx
).
Is there a way to verify that those packages are already installed from within setuptools and if not, prompt the user to install them?
-10053153 0 Exceptions in J2MEI am developing an mobile application using j2me.In that i am using kxml parser.In my application i have to call an url to get the data.When i am calling that url sometimes it showing:
java.lang.IllegalStateException: update of non-existent node Exception.
My sample code is:
InputStreamReader isr=null; InputStream rssStream=null; InputStream is = null; HttpConnection conn=null; try { conn = (HttpConnection)Connector.open(rssUrl); rssStream = conn.openInputStream();---------->I think exception is shown here. isr = new InputStreamReader( rssStream ); parser.setInput(isr); parser.nextTag();
-15290776 0 Image map doesn't work in Internet Explorer I really tried everything but it just doesn't work.
Code is
<html> <head> <title>Map test</title> </head> <body> <img usemap="#map1" src="/assets/templates/design01/header2.jpg" alt="SaveMe Header" /> <map name="map1"> <a href="/sitemap" shape="rect" coords="600,115,670,135" title="Sitemap"></a> <a href="/contact" shape="rect" coords="680,115,750,135" title="Contact"></a> </map> </body>
-17646349 0 You've definitely hit across an interesting problem with WinPcap. Its protocol driver (NPF) expects to be able to open an adapter whenever it wants. When paired with Wireshark, it will do this frequently — it's typical to see NPF open and close the same adapter dozens of times just while the Wireshark GUI is loading. It's even possible to see NPF have multiple bindings to the same adapter simultaneously.
The rough equivalent of this in NDIS 6.x is the NdisReEnumerateProtocolBindings
function. What this does is queue up a workitem to call into your protocol' ProtocolBindAdapterEx
handler for each adapter that is marked as bound in the registry, but isn't currently bound in NDIS. (I.e., for each adapter that INetCfg finds a bindpath to that does not already have an open handle.)
However, due to the large impedance between NPF's API and how NDIS regards binding, you'll need to tackle a few issues:
Multiple simultaneous bindings to the same adapter. (This is a rarely-used feature; NPF is one of two protocols that I know use this, so it's not really discussed much in the MSDN documentation.) The only way to get multiple simultaneous bindings in NDIS 6.x is to call NdisOpenAdapterEx
twice within the same ProtocolBindAdapterEx
call. That's going to be challenging, because NPF's model is to open a new binding whenever an API call comes in from usermode; it doesn't know in advance how many handles will need to be opened.
If another bind request comes in, you can attempt to close all previous handles to that adapter (transparently to the NPF API[!]), call NdisReEnumerateProtocolBindings
, then open N+1 handles in your upcoming ProtocolBindAdpaterEx
handler. But this is brittle.
You can also try and merge all API calls to the same adapter. If a second bind request comes in, just route it to the pre-existing binding to that adapter. This might be difficult, depending on how NPF's internals work. (I'm not allowed to read NPF source code; I can't say.)
Finally, the cheesy solution is to just allocate two (or three) binding handles always, and keep the extras cached in case Wireshark needs them. This is cheap to implement, but still a bit fragile, since you can't really know if Wireshark will want more handles than you pre-allocated.
Missing INetCfg
bindings. NDIS 5.x protocols are allowed to bind to an adapter even if the protocol isn't actually supposed to be bound (according to INetCfg
). Wireshark uses this to get itself bound to all sorts of random adapters, without worrying too much about whether INetCfg
agrees that NPF should be bound. Once you convert to NDIS 6.x, the rules are enforced strictly, and you'll need to make sure that your protocol's INF has a LowerRange
keyword for each type of adapter you want to bind over. (I.e., the NPF protocol should show up in the Adapter Properties dialog box.)
Asynchronous bindings. The NdisReEnumerateProtocolBindings
model is that you call it, and NDIS will make an attempt to bind your protocol to all bindable adapters. If the adapter isn't bindable for some reason (perhaps it's in a low-power state, or it's being surprise-removed), then NDIS will simply not call your protocol back. It's going to be tough to know exactly when to give up and return failure to the usermode NPF API, since you don't get a callback saying "you won't bind to this adapter". You may be able to use NetEventBindsComplete
, but frankly that's kind of a dodgy, ill-defined event and I'm not convinced it's bulletproof. I'd put in a timeout, then use the NetEvent as a hint to cut the timeout short.
Finally, I just wanted to note that, although you said that you wanted to minimize the amount of churn in WinPcap, you might want to consider repackaging its driver as an NDIS LWF. LWFs were designed for exactly this purpose, so they tend to fit better with NPF's needs. (In particular, LWFs can see native 802.11 traffic, can get more accurate data without going through the loopback hack, and are quite a bit simpler than protocols.)
-19496399 0 Mocha tests timeout if more than 4 tests are run at onceI've got a node.js + express web server that I'm testing with Mocha. I start the web server within the test harness, and also connect to a mongodb to look for output:
describe("Api", function() { before(function(done) { // start server using function exported from another js file // connect to mongo db }); after(function(done) { // shut down server // close mongo connection }); beforeEach(function(done) { // empty mongo collection }); describe("Events", function() { it("Test1", ...); it("Test2", ...); it("Test3", ...); it("Test4", ...); it("Test5", ...); }); });
If Mocha runs more than 4 tests at a time, it times out:
4 passing (2s) 1 failing 1) Api Test5: Error: timeout of 2000ms exceeded at null.<anonymous> (C:\Users\<username>\AppData\Roaming\npm\node_modules\moch\lib\runnable.js:165:14) at Timer.listOnTimeout [as ontimeout] (timers.js:110:15)
If I skip any one of the 5 tests, it passes successfully. The same problem occurs if I reorder the tests (it's always the last one that times out). Splitting the tests into groups also doesn't change things.
From poking at it, the request for the final test is being sent to the web server (using http module), but it's not being received by express. Some of the tests make one request, some more than one. It doesn't affect the outcome which ones I skip. I haven't been able to replicate this behaviour outside mocha.
What on earth is going on?
-39818738 1 Can we work offline using setuptools_scm_git_archive?I've added setuptools_scm_git_archive
like describe in the doc [1]::
setup(name='Mypkg', use_scm_version=True, setup_requires=['setuptools_scm', 'setuptools_scm_git_archive'], ...
When I'm online, on every python setup.py install
it download all the stuff, that work well::
$ python setup.py install ... Installed /home/luis/lab/sandbox/Mypkg/.eggs/setuptools_scm_git_archive-0-py2.7.egg Searching for setuptools_scm Reading https://pypi.python.org/simple/setuptools_scm/ Best match: setuptools-scm 1.11.1 Downloading https://pypi.python.org/packages/84/aa/c693b5d41da513fed3f0ee27f1bf02a303caa75bbdfa5c8cc233a1d778c4/setuptools_scm-1.11.1.tar.gz#md5=4d19b2bc9580016d991f665ac20e2e8f Processing setuptools_scm-1.11.1.tar.gz Writing /tmp/easy_install-F5YD2D/setuptools_scm-1.11.1/setup.cfg Running setuptools_scm-1.11.1/setup.py -q bdist_egg --dist-dir /tmp/easy_install-F5YD2D/setuptools_scm-1.11.1/egg-dist-tmp-Cixhzl Moving setuptools_scm-1.11.1-py2.7.egg to /home/luis/lab/sandbox/Mypkg/.eggs Installed /home/luis/lab/sandbox/Mypkg/.eggs/setuptools_scm-1.11.1-py2.7.egg running install running bdist_egg running egg_info ...
Offline I get this::
$ python setup.py install Download error on https://pypi.python.org/simple/setuptools_scm_git_archive/: [Errno -2] Name or service not known -- Some packages may not be found! Download error on https://pypi.python.org/simple/setuptools-scm-git-archive/: [Errno -2] Name or service not known -- Some packages may not be found! Couldn't find index page for 'setuptools_scm_git_archive' (maybe misspelled?) Download error on https://pypi.python.org/simple/: [Errno -2] Name or service not known -- Some packages may not be found! No local packages or download links found for setuptools_scm_git_archive Traceback (most recent call last): File "setup.py", line 149, in <module> scripts=scripts) File "/usr/lib/python2.7/distutils/core.py", line 111, in setup _setup_distribution = dist = klass(attrs) File "/home/luis/venv/local/lib/python2.7/site-packages/setuptools/dist.py", line 269, in __init__ self.fetch_build_eggs(attrs['setup_requires']) File "/home/luis/venv/local/lib/python2.7/site-packages/setuptools/dist.py", line 313, in fetch_build_eggs replace_conflicting=True, File "/home/luis/venv/local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 826, in resolve dist = best[req.key] = env.best_match(req, ws, installer) File "/home/luis/venv/local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 1092, in best_match return self.obtain(req, installer) File "/home/luis/venv/local/lib/python2.7/site-packages/pkg_resources/__init__.py", line 1104, in obtain return installer(requirement) File "/home/luis/venv/local/lib/python2.7/site-packages/setuptools/dist.py", line 380, in fetch_build_egg return cmd.easy_install(req) File "/home/luis/venv/local/lib/python2.7/site-packages/setuptools/command/easy_install.py", line 634, in easy_install raise DistutilsError(msg) distutils.errors.DistutilsError: Could not find suitable distribution for Requirement.parse('setuptools_scm_git_archive') $
Does that mean that we NEED to be online to use setuptools_scm_git_archive
?
[1] https://pypi.python.org/pypi/setuptools_scm_git_archive/0.1
-21978621 0 Debuging a decompression error with Zlib.jsI am trying to compress text server side in PHP using the gzdeflate
function and send that data to the clients browser which will then inflate it.
I did some research and found the imaya Zlib.js source on GitHub and attempted to use that. Unfortunately, I always get an "unsupported compression method" error when I try to inflate my data.
I've read the documents with no luck and I have search the web for more information.
I found these two links, but wasn't able get any positive results.
ZLIB Decompression - Client Side
Decompress gzip and zlib string in javascript
Questions:
1) Are there any tutorials on how to use these libraries available?
2) If not would anyone have any information as to why I would be getting the error message that I am?
Thanks for any help or information that you can provide.
-38457249 0You should handle output of process (both of stdout, stderr ). Because, these outputs will be redirected to the parent process through three streams (getOutputStream(), getInputStream(), getErrorStream() ). If not handled, it will block when child process produces output.
-19636735 0 grouping counted data by column nameSome native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock.
I have following table:
2.QuranPrayed
I just wanted to have all the siparas and there count as result.
Means expected result is as follows:
Sipara1 3 Sipara2 2 .. .. ..
Sipara1 is 3 because it has arrived 3 times in QuranPrayed.
I made following query:
select qm.sipara,COUNT(qp.Sipara) from QuranMaster qm,QuranPrayed qp where qp.sipara=qm.sipara group by qm.sipara
This query works perfectly right when QuranPrayed has values.
But when QuaranPrayed has no values, it does not shows me result.
My expectation is:
Sipara1 0 Sipara2 0 .. .. ..
Please help me.
-16117467 0checkout ensureIndex This will speed up your search
-2663012 0 I'm trying to make lots of the same object appear randomly on the screen subject to conditions and keep getting errors?A good friend recommended this site to me, it looks really useful! I'm a bit of a shameless noob at actionscript and after 3 days of tutorials and advice I've hit a brick wall.
I've managed to get a sensor attached to an arduino talking to flash using something called AS3glue. it works, when i set up a trace("leaf") for the contition that the sensor reads 0, i get a printout of the word "leaf". however i want the program to make a graphic appear on the screen when this condition is met, not just trace something.
I'm trying to get the program to generate a library object called "Enemy" on the screen at a random position each time the conditions are met. It's called enemy because I was following a game tutorial...actually it's a drawing of a leaf.
Here's the bit of the code which is causing me problems:
var army:Array; var enemy:Enemy;
function AvoiderGame() { army = new Array(); var newEnemy = new Enemy( 100, 100 ); army.push( newEnemy ); addChild( newEnemy ); }function timerEvent(event:Event):void {
if (a.getAnalogData(0) ==0 && a.getAnalogData(0) != this.lastposition){
trace("leaf"); var randomX:Number = (Math.random() * 200) + 100; var randomY:Number = (Math.random() * 150) + 50; var newEnemy = new Enemy( randomX, randomY); army.push( newEnemy ); addChild( newEnemy ); } else if (a.getAnalogData(0) == 0) { //don't trace anything } >else {
//don't trace anything } this.lastposition = a.getAnalogData(0); //afterwards, set the position to be the new lastposition and repeat.
}
I've imported "import flash.display.MovieClip;"
and the code for the Enemy class looks like this:
package { import flash.display.MovieClip; public class Enemy extends MovieClip { public function Enemy( startX:Number, startY:Number ) { x = startX; y = startY; } } }
Here's my error. I've tried googling, it seems like a pretty general error:
TypeError: Error #1009: Cannot access a property or method of a null object reference. at as3glue_program_fla::MainTimeline/timerEvent() at flash.utils::Timer/_timerDispatch() at flash.utils::Timer/tick()
I've made sure that the "Enemy" object is exported for AS3.
I'm going for something like this when it's programmed in AS2:
leafCounter = 0; //set the counter to 0 counter.swapDepths(1000); //puts the counter on top of pretty much anything, unless you make more than 1000 leaves! counter.textbox.text = 0; //shows "0" in the text box in the "counter" movie clip
this.onMouseDown = function() { //triggers when the mouse is clicked this.attachMovie("Leaf","Leaf"+leafCounter,leafCounter,{_x:Math.random()*Stage.width,_y:Math.random()*Stage.height,_rotation:Math.random()*360}); //adds a leaf to rthe stage with a random position and random rotation leafCounter++; //adds 1 to the leaf counter counter.textbox.text = leafCounter; //shows that number in the text box }
I'm sure it must be a simple error, I can get the logic working when it just traces something on the screen but i can't get it to generate an "enemy"
Any help or hints would be really useful! I know this is a bit of a ham-fisted job of altering existing code.
-27643689 0A String being immutable means you can't alter the string; it says nothing about replacing the contents of a String variable with a new string.
Your output has nothing to do with the mutability (or not) of Strings, as you never try to change a String. You do try to change an argument from within a function, but because Java passes everything by value, while str2
will in fact be "Hi"
inside of tell
, that assignment will have no effect on str1
(as you have seen).
I'm trying to create some custom reports using BIDS. My proof of concept is using the quote entity.
I have created a sub-report using the following FetchXML:
<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false"> <entity name="quotedetail"> <attribute name="productid" /> <attribute name="productdescription" /> <attribute name="priceperunit" /> <attribute name="quantity" /> <attribute name="extendedamount" /> <attribute name="quotedetailid" /> <attribute name="isproductoverridden" /> <order attribute="productid" descending="false" /> <link-entity name="quote" from="quoteid" to="quoteid" alias="aa"> <filter type="and"> <condition attribute="quotenumber" operator="eq" value="@quoteid" /> </filter> </link-entity> </entity> </fetch>
This worked when the quoteid parameter was supplied at runtime. I then created the main report with the following FetchXML:
<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false"> <entity name="quote" enableprefiltering="1" prefilterparametername="CRM_FilteredQuote"> <attribute name="name" /> <attribute name="totalamount" /> <attribute name="quoteid" /> <order attribute="name" descending="false" /> </entity> </fetch>
I get the prompt for quote id, which when I enter I get the following error:
An error occurred during local report processing. An error has occurred during report processing. Cannnot read the next data row for the dataset DataSet1. The XML passed to the platform is not well-formed XML. Invalid XML.
I have read numerous blogs and articles and tried lots of variations with filters and prefilters but I can get no further. Hopefully someone can see my error and point me in the right direction.
-28308674 0 Pseudo element takes up space in IE9I have a div that I want to behave like an text input field.
Here's the full source code example:
HTML:
<div contenteditable='true'></div>
CSS:
div:empty:before { content: 'Type here...'; color: #ccc; } div{ padding: 4px; border: 1px solid #ccc; }
See the fiddle in IE9.
In IE9, the problem is that the keyboard caret is displayed at the end.
In Chrome, the caret is at the beginning, which is correct.
It seems like the problem is that the pseudo :before element is taking up space in IE9. How can I make it take up no space like it does it Chrome (behave like a placeholder)?
-5000901 0 How do I get the URLs out of an HTML file?I need to get a long list of valid URLs for testing my DNS server. I found a web page that has a ton of links in it that would probably yield quite a lot of good links (http://www.cse.psu.edu/~groenvel/urls.html), and I figured that the easiest way to do this would be to download the HTML file and simply grep for the URLs. However, I can't get it to list out my results with only the link.
I know there are lots of ways to do this. I'm not picky how it's done.
Given the URL above, I want a list of all of the URLs (one per line) like this:
-20561915 0http://www.cse.psu.edu/~groenvel/
http://www.acard.com/
http://www.acer.com/
...
Seems you are using BDD driven approch, but you didnt specified what process you are using either Jbehave or Cucumber. I am assuming that you are using Jbehave. In Jbehave You can use @Alias Annotation like this
@When("a stock of symbol $symbol and a threshold of $threshold") // standalone @Alias("a stock of <symbol> and a <threshold>") // examples table public void aStock(@Named("symbol") String symbol, @Named("threshold") double threshold) { // ... }
you can refer This Link for more info.
please let me know if it works .
-21943894 0We can specify output attribute of the java task which will redirect your error and output streams to the file specified as the value of this attribute. Or
You can explore the echo task in Ant through which you will be able to print the messages on the console
More information can be found on :
https://ant.apache.org/manual/Tasks/exec.html. or
http://www.vogella.com/tutorials/ApacheAnt/article.html
-4526260 0You just need to add a parameter to the function you have:
function getBlock($filename){ require_once(YOURBASEPATH . DS . 'layouts' .DS . 'blocks'. DS . $filename .'.php'); }
-34795650 0 Powershell Substring 'Quirk' Seeing 'Exception calling "Substring" with "2" argument(s): "Length cannot be less than zero.' being thrown when running this bit of code inside a script:
$PrinterDriverName = $printer.DriverName $PrinterMake = $PrinterDriverName.Substring(0,$PrinterDriverName.IndexOf(" ")) $PrinterModel = $PrinterDriverName.Substring($PrinterDriverName.IndexOf(" ")).Trim()
Yet $PrinterMake and $PrinterModel are being populated. What I'm trying fathom out is when these two lines are ran selectively, no errors are returned. Can someone shed some light as to the substring errors are being produced when running this as part of the script please!? Thanks in advance ... Wayne
-19676950 0when you receive the post you should use
rowid[] instead of rowid
-37297733 0For me the accepted answer throwed an exception so what I did was this.
ArrayAdapter adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_item, Collections.emptyList()); spinner.setAdapter(adapter);
-146645 0 The .NET version of Lucene is what we've been using. It meets all of your criteria.
-7653921 0(1) It's fine to have this in one action method, you don't want to be creating new action methods if new roles are added.
(2) You can use e.g.
If User.IsInRole("CustomerSupport") { ... }
You might also want to consider locking down the action method so that only roles catered for inside the method are allowed access. Use the [Authorize] attribute to accomplish that. E.g.
[Authorize(Roles = "Retailer, Manufacturer, CustomerSupport")]
-38973489 1 £ Sign on python SQLAlchemy query I am trying to inject into a query, a string in the following way:
value = '£' query = """select * from table where condition = '{0}';""".format(value)
the problem is the result of this formatting is:
select * from table where condition = '\xc2\xa3';
Since I will use this query with sqlalchemy, I need the encoded characers to appear as the actual pund sign.
Any ideas on how I can makes this query look like this?:
select * from table where condition = '£';
I am using postgres 3.5 and python 2.7.6
Also if I try the following:
'\xc2\xa3'.decode('utf-8')
the result is:
-2305756 0u'\xa3'
Are we facing a situation of Dangling Pointer here? Why and how? Please explain.
It depends on the implementation of Student. If Student looks like this ...
class Student { public: char* m_name; Student(const char* name) { m_name = new char[strlen(name)+1]; strcpy(m_name,name); } ~Student() { delete[] m_name; } };
... then there's a problem: when you copy a Student then you have two pointers to the same m_name data, and when the two Student instances are deleted then the m_name data is deleted twice, which is illegal. To avoid that problem, Student need an explicit copy constructor, so that a copied Student has a pointer to different m_name data.
Alternatively if Student looks like this ...
class Student { public: std::string m_name; Student(const char* name) : m_name(name) { } };
... then there's no problem because the magic (i.e. an explicit copy constructor) is implemented inside the std::string class.
In summary, you need an explicit copy constructor (or explicitly no copy constructor, but in either case not just the default constructor) if the class contains a pointer which it allocates and deletes.
-28033024 0Your program runWithParameter.py
needs #!/usr/bin/env python
at the top of it. Then, in your shell, type chmod +x runWithParameter.py
. From there, you can simply type runWithParameter.py
and it will run.
Example:
foo.py
:
#!/usr/bin/env python print 'Hello World'
And depending on your $PATH
, you can type foo.py
to run it. Else, you will have to precede it with ./
bash-3.2$ chmod +x foo.py bash-3.2$ ./foo.py Hello World bash-3.2$
Or, if you are going to be running this function locally, you can define a function:
bash-3.2$ function foo.py(){ > ./foo.py > } bash-3.2$ foo.py Hello World bash-3.2$
-28226428 0 How do I make these 's work for Firefox instead of just Internet Explorer 6 This code only works for Internet Explorer 6, I don't know how to make it work for Firefox. I'm using hyperlinks that contain table rows to change the content on the page. However, on firefox the links become unclickable...
Here is the CSS:
#sidebar {display:block; top:116px; left:11px; width:150px; position:fixed;} .sidebarLink a:hover td { cursor:pointer; background-color:#f60; color:#fff; border: 1px solid #f60;;} .sidebarLink td{background-color:#fff; color:#f60; border: 1px solid #ccc;;} .sidebarLink {font-family: sans-serif; font-weight: bold; font-size: small;}
And the HTML:
<div id="sidebar"> <table style="table-layout: fixed; word-wrap: break-word border-collapse: collapse;" class="sidebarLink" cellpadding="5" cellspacing="4" width="150"> <a href="index.php?test=table1"> <tr align="middle"> <td>Link 1</td> </tr> </a> <a href="index.php?test=table2"> <tr width="90" align="middle"> <td>Link 2</td> </tr> </a> </table> </div>
I could turn this into a form with buttons and style the buttons to look like I have the table right now. The problem is that causes a performance issue with the table itself and the onHover feature so it would be great if someone knows a way to make this function in firefox.
-17637455 0 Send a USSD code to a designated stand alone USSD serverIs is possible to send a USSD code to a stand alone USSD server (A non-mobile carrier server) from Android device?
Specifically the scenario is:
A calls B
B has an app that can identify incoming calls
B send (through the app) USSD code to a USSD server that includes A caller ID
The server sends an email to A.
I have an executable file - process.exe - which takes a single file path and does something with that file (no outputs). process.exe isn't capable of accepting wildcard paths e.g. process.exe c:\project\*.ext
What I want to do is select all files of a particular extension in my project (*.xmlt) and pass each one of these files into the process.exe as part of my AfterBuild
step.
I have a tag cloud on product listing pages on my site that goes to a tag results page which displays products that contain that chosen tag. I want to put a header at the top of that results page that says something like "Products Tagged As: (insert tag name here)"
Any advice? I can't seem to access the system variable that displays the currently chosen tag name. The page URL contains the tagID variable, if that helps:
Product-Features.aspx?tagid=36
I am using Portal Engine Kentico development, by the way. Thanks.
-13545991 0 widget_text widget doesn't work with shortcodesHi all I am having a big issue with the shortcodes not working in text_widget. I have added the appropriate codes
add_filter( 'widget_text', 'shortcode_unautop'); add_filter( 'widget_text', 'do_shortcode');
I am still unsuccessful, is there any troubleshoot techniques I can used or be advised to solve this issue myself?
Also the shortcodes work perfectly in the_content and the_excerpt.
add_filter('the_content', 'do_shortcode'); add_filter('the_excerpt', 'do_shortcode');
-19285906 0 Data binding example extjs sencha I've a grid example that i want to make it look like this url below
http://docs.sencha.com/extjs/4.2.2/#!/example/grid/binding.html
The grid code is :
var grid_modal = Ext.create('Ext.grid.Panel', { width: '100%', height: 450, frame: true, loadMask: true, collapsible: false, title: 'Detail data', store: list_data, columns: [ { header: 'Number', width: 130, sortable: true, dataIndex: 'doc_no', xtype: 'templatecolumn', tpl: '{doc_no}<br/>{pp_id}' }, { header: 'Date.', width: 100, sortable: true, dataIndex: 'pp_date', xtype: 'datecolumn', format:'d-m-Y' }, { header: 'Vendor', width: 160, sortable: true, dataIndex: 'org_order', xtype: 'templatecolumn', tpl: '{org_order}' }], dockedItems: [{ xtype: 'pagingtoolbar', store: list_data, dock: 'bottom', displayInfo: true },{ xtype: 'toolbar', dock: 'top', items: [ { xtype: 'button', cls: 'contactBtn', scale: 'small', text: 'Add', handler: function(){ window.location = './pp/detail/' } },'->','Periode :', set_startdate('sdatepp',start), 's.d', set_enddate('edatepp',end), '-', { xtype : 'textfield', name : 'find_pp', id : 'find_pp', emptyText: 'Keywords' , listeners: { specialkey: function(field, e){ if (e.getKey() == e.ENTER) { onFindPP('find_pp','sdatepp','edatepp') } } } }] }], });
I don't understand how to add data binding to below grid that i make. so it makes look like same as the example on extjs doc. please help me find out how to make the data grid binding. thank you for your attention and help.
-30211717 0I do it this way :
// create your requests $requests[] = $client->createRequest('GET', '/endpoint', ['config' => ['order_id' => 123]]); ... // in your success callback get $id = $event->getRequest()->getConfig()['order_id']
-37363237 0 You should have playing = false;
somewhere in game over method or somewhere else. As I see you haven't such line of code. I ask a question. Where did you change playing to false so that You expect to get
If(!playing)
Condition instead of
If(playing)
You press the key. Game begins. Now you reach
If(playing)
Then the ball get to boundaries and the code reach
if ( ballX > width || ballX < 0 ) { gameover = true; } // if the ball reaches one of the bounderies it will be game over
In this situation. Playing var and gameover var both are true. Right? And under
If(playing)
You have score() method.so even when gameover is true the score method still is performed.
You can set playing to false under:
if ( ballX > width || ballX < 0 ) { gameover = true; Playing =false ; }
Or you can modify the score method like this:
void score () { if (playing && !gameover) { fill(255); textSize(45); textAlign(CENTER); text(scorecounter, width/2,height/4); // keeps the score on the display while playing }
-18089258 0 Django: ImproperlyConfigured: The storage backend of the staticfiles finder doesn't have a valid location I was using Django and the static files cannot load, the error is:
ImproperlyConfigured: The storage backend of the staticfiles finder <class 'django.contrib.staticfiles.finders.DefaultStorageFinder'> doesn't have a valid location.
Here is the views.py:
def results(request): metaUrl = "" if not request.method == 'POST': print "Not Post!" else: metaUrl = request.POST['urls'] cmodel = InfoController() (firstList, wordList, sizeList) = cmodel.controller(metaUrl) print "I am at result" return render( request, 'infoRetriever/results.html', { 'firstList': firstList, 'wordList': wordList, 'sizeList': sizeList})
It's weird that when I was using
return render_to_response('infoRetriever/results.html', { 'firstList': firstList, 'wordList': wordList, 'sizeList': sizeList}, context_instance=RequestContext(request))
to replace the last sentence in the views.py, the static files loads OK, but other problems would occur. Could anyone help me? Thank you very much.
-37421926 0 Randomising database for insertEvening all, I've recently been reading the following blog post about sharding at Pinterest and I think there's some great stuff in there https://engineering.pinterest.com/blog/sharding-pinterest-how-we-scaled-our-mysql-fleet
What I'm unsure on though, is how best to decide where a brand new user should be inserted.
So for those that don't know or have bothered to read the above article, Pinterest have a number of shards, each with a number of databases on. They generate IDs for objects based on a 64 bit shifting that determines a shard, the type of object (user,pin etc..) to determine a table and the local auto-increment id for the object in question. Now they try to put pins etc. on the same database as the 'board' they are on. But for a brand new object, what would be the best way of determining the 'shard' it lives on?
For users that sign in via Facebook they use a modulus e.g
shard = md5(“1.2.3.4") % 4096 //4096 is the number of shards
But if I had a simple email/password registration form, do you think using a similar approach on email address would work for working out an initial shard? I'd assume it would have to be email in this case, otherwise they would have no way of knowing what database to validate the logging credentials against. Also I know that post is from 2015 so not too old and computing power moves quickly, but would there be a better option then using md5 here? I know the chance of a collision is minor - especially as we're just talking about hashing the email address here, but would it be worth using a different algorithm? I'm basically interested in the best way to determine a shard here and to work out how to get back to it (hence why I think it has to be email address)
Hope this all makes sense!
(p.s didn't take this with the Pinterest tag as it looks like that's just for api dev, but if someone thinks it might get better 'eyes' on the question then feel free to add it)
-5837895 0 Android InstallException: EOF Google MapsView "Hello Maps"Eclipse isn't pointing out any errors in my code. Got an exception when I tried to run the emulator. Here's all my code.
HelloGoogleMaps.java
package com.example.hellogooglemaps; import android.app.Activity; import android.os.Bundle; import com.google.android.maps.*; import android.widget.LinearLayout; import android.widget.ZoomControls; public class HelloGoogleMaps extends MapActivity { LinearLayout linearLayout; MapView mapView; ZoomControls mZoom; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } @Override protected boolean isRouteDisplayed() { return false; } }
main.xml file:
<?xml version="1.0" encoding="utf-8"?> <com.google.android.maps.MapView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/mapview" android:layout_width="fill_parent" android:layout_height="fill_parent" android:clickable="true" android:apiKey="my_api_key" //I have this in my program. Just not putting it in post.
/>
HelloGoogleMaps Manifest
<?xml version="1.0" encoding="utf-8"?>
<application android:icon="@drawable/icon" android:label="@string/app_name"> <uses-library android:name="com.google.android.maps" /> <activity android:name=".HelloGoogleMaps" android:label="@string/app_name" android:theme="@android:style/Theme.NoTitleBar"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application>
EDIT Debugging shows the following:
ERROR: the user data image is used by another emulator. aborting
EDIT 2 Console also gives this warning:
Warning once: This application, or a library it uses, is using NSQuickDrawView, which has been deprecated. Apps should cease use of QuickDraw and move to Quartz.
EDIT 3 It installs now but the app quits unexpectedly in the emulator.
-2352092 0Am I missing something here when I suggest: Just hide the toolbar (or specific button) in the view page? That's an painless CSS hook done in the view page or SharePoint Designer
-27449633 0 Suppressing TypeError exception in JavascriptTrying to retrieve values from undefined in Javascript throws a TypeError exception. I'm reading a book that says you can guard against that error with the && operator. However, it doesn't say why I would want to suppress the error. Can someone please explain why that would be useful?
-28370580 0well, i found an answer from internet,
<script type="text/javascript"> $(document).ready(function () { $("#<%=InsertBtn.ClientID %>").click(function (e) { var respond = confirm("Press ok if you confirm"); if (respond != true) { e.preventDefault(); } }); }); </script> <asp:Button ID="InsertBtn" runat="server" Text="Insert" OnClick="InsertBtn_Click" />
by using the preventDefault() to cancel the onclick default action
-21620172 0You can add the reference to these 2 SMO dll
using Microsoft.SqlServer.Management.Smo; using Microsoft.SqlServer.Management.Common;
and then run the command directly by reading all of sql.
string scriptToRun = File.ReadAllText("Filepath"); using (SqlConnection conn = new SqlConnection("Yourconnectionstring")) { Server server = new Server(new ServerConnection(conn)); server.ConnectionContext.ExecuteNonQuery(scriptToRun); }
-20591326 0 You're going to need to write a loop.
boolean success = true; for( int i = 0; i < running.length; ++i ) { if( running[i] == false ) { success = false; break; } } if( success == true ) { // Do stuff }
You shouldn't worry about taking up too many lines of code. Just worry about writing code that's easy to understand.
EDIT: The above runs the if statement if all of the items in the array are true. If you actually wanted to execute the code if any one item in the array is true, it would look more like this:
boolean success = false; for( int i = 0; i < running.length; ++i ) { if( running[i] == true ) { success = true; break; } } if( success == true ) { // Do stuff }
-1882297 0 I recommend just writing a stored procedure (or group of stored procedures) to encapsulate this logic, which would look something like this:
update Customer set isDeleted = 1 where CustomerId = @CustomerId /* Say the Address table has a foreign key to customer */ update Address set isDeleted = 1 where CustomerId = @CustomerId /* To delete related records that also have child data, write and call other procedures to handle the details */ exec DeleteProjectByCustomer(@CustomerId) /* ... etc ... */
Then call this procedure from customerRepository.Delete
within a transaction.
Can't you just use if (scanf ("%d", &n)==1)
or call strtol
?
Am using an APACHE DERBY database, and basing my database interactions on EntityManager, and i don't want to use JDBC class to build a query to change my tables' names (i just need to put a prefix to each new user to the application, but have the same structure of tables), such as :
//em stands for EntityManager object Query tableNamesQuery= em.createNamedQuery("RENAME TABLE SCHEMA.EMP_ACT TO EMPLOYEE_ACT"); em.executeUpdate(); // ... rest of the function's work // The command works from the database command prompt but i don't know how to use it in a program //Or as i know you can't change system tables data, but here's the code Query tableNamesQuery= em.createNamedQuery("UPDATE SYS.SYSTABLES SET TABLENAME='NEW_TABLE_NAME' WHERE TABLETYPE='T'"); em.executeUpdate(); // ... rest of the function's work
My questions are : - This syntax is correct ? - Will it work ? - Is there any other alternative ? - Should i just use the SYS.SYSTABLES and find all the tables that has 'T' as tabletype and alter their name their, will it change the access name ? Thanks in advance
-1915340 0Ok, I found how to make it. With a UILocalizedIndexedCollation, there is a sample in tableViewSuite.
I followed the source code, then it works perfectly.
-14265968 0 How to form 2 column table in css on wordpress pluginI'm trying to form a table with 2 columns on a form used by a WordPress plugin. So far I have tried to indent the right hand column using basic indents but the end result ends up where the column on the right isn't exactly vertically inline ( i'm assuming because the text labels are different size). I have tried using a type table but everything goes crazy.
i thought to use code like the following but cant seem to figure out where to put it:
<style type="text/css"> #wrap { width:600px; margin:0 auto; } #left_col { float:left; width:300px; } #right_col { float:right; width:300px; } </style> <div id="wrap"> <div id="left_col"> ... </div> <div id="right_col"> ... </div> </div>
The code i'm using for my form is as follows:
<?php /* If you would like to edit this file, copy it to your current theme's directory and edit it there. Theme My Login will always look in your theme's directory first, before using this default template. */ ?> <div class="login" id="theme-my-login<?php $template->the_instance(); ?>"> <?php $template->the_action_template_message( 'register' ); ?> <?php $template->the_errors(); ?> <form name="registerform" id="registerform<?php $template->the_instance(); ?>" action="<?php $template->the_action_url( 'register' ); ?>" method="post"> <p style="float:left; padding-right:10px;"><label for="user_firstname<?php $template->the_instance(); ?>"><?php _e( 'First Name:', 'theme-my-login' ) ?></label></p> <p></p><input type="text" name="user_firstname" id="user_firstname<?php $template->the_instance(); ?>" class="input" value="<?php $template->the_posted_value( 'user_firstname' ); ?>" size="20" /></p> <p style="float:left; padding-right:10px;"><label for="user_lastname<?php $template->the_instance(); ?>"><?php _e( 'Last Name:', 'theme-my-login' ) ?></label></p> <p></p><input type="text" name="user_lastname" id="user_lastname<?php $template->the_instance(); ?>" class="input" value="<?php $template->the_posted_value( 'user_lastname' ); ?>" size="20" /></p> <p style="float:left; padding-right:40px;"><label for="user_email<?php $template->the_instance(); ?>"><?php _e( 'E-mail:', 'theme-my-login' ) ?></label></p> <p></p><input type="text" name="user_email" id="user_email<?php $template->the_instance(); ?>" class="input" value="<?php $template->the_posted_value( 'user_email' ); ?>" size="20" /></p> <p style="float:left; padding-right:10px;"><label for="user_tel<?php $template->the_instance(); ?>"><?php _e( 'Telephone:', 'theme-my-login' ) ?></label></p> <p></p><input type="text" name="user_tel" id="user_tel<?php $template->the_instance(); ?>" class="input" value="<?php $template->the_posted_value( 'user_tel' ); ?>" size="20" /></p> <p style="float:left; padding-right:35px;"><label for="user_mobile<?php $template->the_instance(); ?>"><?php _e( 'Mobile:', 'theme-my-login' ) ?></label></p> <p></p><input type="text" name="user_mobile" id="user_mobile<?php $template->the_instance(); ?>" class="input" value="<?php $template->the_posted_value( 'user_mobile' ); ?>" size="20" /></p> <p style="float:left; padding-right:30px;"><label for="user_country<?php $template->the_instance(); ?>"><?php _e( 'Country:', 'theme-my-login' ) ?></label></p> <p></p><input type="text" name="user_country" id="user_country<?php $template->the_instance(); ?>" class="input" value="<?php $template->the_posted_value( 'user_country' ); ?>" size="20" /></p> <p style="float:left; padding-right:15px;"><label for="user_login<?php $template->the_instance(); ?>"><?php _e( 'Username:', 'theme-my-login' ) ?></label></p> <p></p><input type="text" name="user_login" id="user_login<?php $template->the_instance(); ?>" class="input" value="<?php $template->the_posted_value( 'username' ); ?>" size="20" /></p> <?php do_action( 'register_form' ); // Wordpress hook do_action_ref_array( 'tml_register_form', array( &$template ) ); //TML hook ?> <p id="reg_passmail<?php $template->the_instance(); ?>"><?php echo apply_filters( 'tml_register_passmail_template_message', __( 'A password will be e-mailed to you.', 'theme-my-login' ) ); ?></p> <p class="submit"> <input type="submit" name="wp-submit" id="wp-submit<?php $template->the_instance(); ?>" value="<?php _e( 'Register', 'theme-my-login' ); ?>" /> <input type="hidden" name="redirect_to" value="<?php $template->the_redirect_url( 'register' ); ?>" /> <input type="hidden" name="instance" value="<?php $template->the_instance(); ?>" /> </p> </form> <?php $template->the_action_links( array( 'register' => false ) ); ?> </div>
I can see that this is really a basic question but I have been trying for hours and keep coming up with all manner or crazy.
Can anyone point me in the right direction? Please...?
I have updated to the following code but is still not working:
<?php /* If you would like to edit this file, copy it to your current theme's directory and edit it there. Theme My Login will always look in your theme's directory first, before using this default template. */ ?> <div class="login" id="theme-my-login<?php $template->the_instance(); ?>"> <?php $template->the_action_template_message( 'register' ); ?> <?php $template->the_errors(); ?> <form name="registerform" id="registerform<?php $template->the_instance(); ?>" action="<?php $template->the_action_url( 'register' ); ?>" method="post"> <div id="regwrap"> <div id="regleft_col"> <p><label for="user_firstname<?php $template->the_instance(); ?>"><?php _e( 'First Name:', 'theme-my-login' ) ?></label></p> </div> <div id="regright_col"> <p></p><input type="text" name="user_firstname" id="user_firstname<?php $template->the_instance(); ?>" class="input" value="<?php $template->the_posted_value( 'user_firstname' ); ?>" size="20" /></p> </div> </div> <?php do_action( 'register_form' ); // Wordpress hook do_action_ref_array( 'tml_register_form', array( &$template ) ); //TML hook ?> <p id="reg_passmail<?php $template->the_instance(); ?>"><?php echo apply_filters( 'tml_register_passmail_template_message', __( 'A password will be e-mailed to you.', 'theme-my-login' ) ); ?></p> <p class="submit"> <input type="submit" name="wp-submit" id="wp-submit<?php $template->the_instance(); ?>" value="<?php _e( 'Register', 'theme-my-login' ); ?>" /> <input type="hidden" name="redirect_to" value="<?php $template->the_redirect_url( 'register' ); ?>" /> <input type="hidden" name="instance" value="<?php $template->the_instance(); ?>" /> </p> </form> <?php $template->the_action_links( array( 'register' => false ) ); ?> </div>
-3636834 0 MapWhy doesn't that work in java, but this does
Map<String, Map<String, Boolean>> myMap = new HashMap<String,Map<String,Boolean>>();
Just to clarify the below alteration of the nested HashMap shows a compiler error, whereas the above does not not; with a Map (not hashmap)
Map<String, Map<String, Boolean>> myMap = new HashMap<String,HashMap<String,Boolean>>();
-4623956 0 Seems like I have solved the problem of strange checkbox behavior. First, the problem was happening because as soon as the listview gets resized, it redraws itself, therefore getView() gets called again for all the visible list items. Since I am using a ViewHolder, and the view is getting reused, it seems like it causes the same checkbox to get reused again for some other list item. So therefore, when I was clicking one checkbox, some other checkbox was getting clicked instead. Since, this call to refresh the listview was only happening when the list was being resized, and list was getting resized only on marking a checkbox in list when no other checkbox was marked, this problem does not appear again after the first checkbox has been marked.
I solved the problem by creating a custom collection class to store the checked items, and before putting the item in this collection, I clone the clicked checkbox's tag and clicklistener over into a new checkbox and store that new checkbox now into the collection. This solved the strange behavior of checkboxes. This may not be the best solution to the problem, so if you know anything better than this, please share.
-36062437 0I want to split it, so that each html element be a separate string.
Here is an alternative answer using the split()
method only. (ie no delimiter needed). Note that with this solution, text with blank characters only are preserved.
String str = "<form action=''><span> First Name </span> <input type='text' id='fname' class='cls' size='40' required /> <span> [*]</span> <input type='submit' value='Submit' name='btn' /> <select name='slcEle' > <option value='opt'> Text</option> </select> <input type='radio' id='this'/> <button name='name' type='reset' value='val'> Text</button> <input type='range' min='0' max='100' name='grade'/> <button name='btnname' type='button'> Text</button>"; String[] separateStrings = str.split("(?<=>)|(?=</)"); int len = separateStrings.length; for (int i = 0; i < len; i++) { System.out.format("[%d] = %s\n", i, separateStrings[i]); }
[0] = <form action=''> [1] = <span> [2] = First Name [3] = </span> [4] = <input type='text' id='fname' class='cls' size='40' required /> [5] = <span> [6] = [*] [7] = </span> [8] = <input type='submit' value='Submit' name='btn' /> [9] = <select name='slcEle' > [10] = <option value='opt'> [11] = Text [12] = </option> [13] = [14] = </select> [15] = <input type='radio' id='this'/> [16] = <button name='name' type='reset' value='val'> [17] = Text [18] = </button> [19] = <input type='range' min='0' max='100' name='grade'/> [20] = <button name='btnname' type='button'> [21] = Text [22] = </button>
-34021012 0 In my test, if you have exactly as many variables as items in your return, then it works.
def algo(): return range(5) a5 = algo() # works b1,b2,b3,b4,b5 = algo() # works c1,c2,c3 = algo() # doesn't work d1,d2,d3,d4,d5,d6 = algo() # doesn't work.
-35369248 0 I'm with the same problem time ago, you need to give privileges to the users to connect to the localhost, is different localhost from apache to mysql permissions
Possibly a security precaution. You could try adding a new administrator account:
mysql> CREATE USER 'yorsh'@'localhost' IDENTIFIED BY 'some_pass'; mysql> GRANT ALL PRIVILEGES ON *.* TO 'yorsh'@'localhost' -> WITH GRANT OPTION; mysql> CREATE USER 'yorsh'@'%' IDENTIFIED BY 'some_pass'; mysql> GRANT ALL PRIVILEGES ON *.* TO 'yorsh'@'%' -> WITH GRANT OPTION; FLUSH PRIVILEGES;
-11816710 0 It sounds like you are trying to write some error handling code. The compiler does do a great job of watching for inappropriate casts, but if you're looking for a runtime exception:
short y = short.Parse("56789");
This will throw an OverflowException
.
-24303556 0OverflowException: Value was either too large or too small for an Int16.
Try
$('.entry-content p').html(function (i, html) { //the regex is not complete return html.replace(/(£(\d{1,3},)*\d+\.\d{2})/, '<span class="price">$1</span>') })
Demo: Fiddle
-27697901 0If I am to switch branches, it will automatically stash my working copy before switching to the new branch.
Nope! Git doesn't automatically stash local changes for you. Also, if you have uncommitted changes that conflict with the branch you're checking out, Git won't let you check out the branch in question. You'll need to either discard or stash them "manually" before checking out that other branch.
it appears pretty clear to me that [...] your working copy files are completely independent from your branches, as are stashes.
Yes, and there are good reasons for that. In particular, one use case for stashing is when you start doing changes while the "wrong" branch is checked out. You can then get out of trouble by
Say I am developing two features simultaneously in two different branches and want to constantly jump back and forth. Do I need to remember to stash my working copy files before every time I switch or is there a better approach to this?
Yes, stashing your changes before switching to another branch, then popping a previous stash, would be the normal workflow. If you switch branches often, that can indeed be tedious, but if you use Git from the command line, you can define aliases in order to abstract some of that complexity away.
I've never used SourceTree myself, but I can imagine how that stashing/checking out/popping can involve quite a lot of tedious mouse clicks. Apparently, though, SourceTree introduced a mechanism called "Custom Actions" that allow you to define your own commands, including Git commands. You might want to look into it...
-5786750 0I've seen this happen because of an img
tag with a blank src
attribute. Giving an img
, script
, link
or similar tag a src
or href
attribute =""
will resolve to the current page. So it will try to load the page a second time as it tried to load the asset. It could also be in a CSS url()
property or an AJAX call.
One easy way to tell is to temporarily put something like <base href="http://example.com" />
in your <head>
section. That will prefix any links on the page, which should prevent your local page from being called twice if it is that sort of problem.
I've also seen some browser extensions that query the page in a separate request. I've noticed this specifically with the Web Server Notifier and Web Technology Notifier extensions for Chrome. Try an "incognito" window or a separate browser and see if you get the same result.
-38904173 0I am not %100 sure why self.cleaned_data.get('repassword')
returns None
in that method, however clean_password
is not the right place for performing validations of fields that depend on each other.
According to docs, you should perform that kind of validation in clean()
function:
views.py
def register(self,request): form = RegisterForm() # Notice `()` at the end return render(request, 'authorization/register.html', {'form': form})
forms.py
... def clean(self): cleaned_data = super(RegisterForm, self).clean() password1 = cleaned_data.get('password') password2 = cleaned_data.get('repassword') if password1 and password1 != password2: raise forms.ValidationError("Passwords don't match")
Please note that you don't have to implement clean_password
and clean_repassword
.
(If you think you still have to implement clean_password
, you have to return password1
from it, not self.cleaned_data
.)
You also need to render form errors correctly as described in the docs.
Don't forget to add it in your template:
{{ form.non_field_errors }}
As for the second error, the problem is, every time the validation fails you are returning a new fresh RegisterForm
instance instead of the invalidated one.
You should change the line in create()
function:
return render(request, 'authorization/register.html', {'form': RegisterForm})
to this:
return render(request, 'authorization/register.html', {'form': form})
-5869064 0 You will need to use the ~/.ssh/config
to specifiy the port. check the following link for a working example
http://www.seanodonnell.com/code/?id=56
-40781393 0I was having an issue with the same error when converting an Int to a custom enum:
switch MyEnum(rawValue: 42) { case .error: // Enum case `.error` not found in type 'MyEnum?' break default: break }
The issue is that MyEnum(rawValue: 42)
returns an optional. Force unwrap it with !
to allow switching on the enum:
switch MyEnum(rawValue: 42)! { case .error: // no error! break default: break }
-32037068 0 How to make two sides edges with keeping scale mode Aspect fill? I am trying to make edges for the two sides in the scene by using this code
let leftEdge : SKNode = SKNode() leftEdge.physicsBody = SKPhysicsBody(edgeFromPoint: CGPointZero , toPoint:CGPointMake(0.0, self.frame.size.height + 100)) leftEdge.position = CGPointZero; leftEdge.physicsBody!.categoryBitMask = EdgeCategory; leftEdge.physicsBody!.collisionBitMask = BubblesCategory; self.addChild(leftEdge) // right edge let rightEdge : SKNode = SKNode() rightEdge.physicsBody = SKPhysicsBody(edgeFromPoint: CGPointZero , toPoint:CGPointMake(0.0, self.frame.size.height + 100)) rightEdge.position = CGPointMake(self.frame.size.width, 0.0); rightEdge.physicsBody!.categoryBitMask = EdgeCategory; rightEdge.physicsBody!.collisionBitMask = BubblesCategory; self.addChild(rightEdge)
It works fine if i use ResizeFill
scale mode but i want to make the mode AspectFill
so how i can make the edges with keeping the mode AspectFill
?
Given a template metaprogram (TMP), do C++ compilers produce build statistics that count the number of instantiated classes? Or is there any other way to automatically get this number? So for e.g. the obiquitous factorial
#include <iostream> template<int N> struct fact { enum { value = N * fact<N-1>::value }; }; template<> struct fact<1> { enum { value = 1 }; }; int main() { const int x = fact<3>::value; std::cout << x << "\n"; return 0; }
I would like to get back the number 3 (since fact<3>, fact<2>, and fact<1> are instantiated). This example if of course trivial, but whenever you start using e.g. Boost.MPL, compile times really explode, and I'd like to know how much of that is due to hidden class instantiations. My question is primarily for Visual C++, but answers for gcc would also be appreciated.
EDIT: my current very brittle approach for Visual C++ is adding the compile switch from one of Stephan T. Lavavej's videos /d1reportAllClassLayout and doing a grep + word count on the output file, but it (a) increases compile times enormously and (b) the regex is hard to get 100% correct.
-12273286 0Maybe you need to use exp_continue
like-
use Expect; ... ... foreach my $cmd (@cmd_array){ $exp->expect(3, [ qr/($|#)/ => sub { shift->send("$cmd\n"); exp_continue;}] ); }
Also, i think the statements inside sub{...}
runs only if pattern matches as per qr/($|#)/
. Also, I would think that after you type in an input or command you would generally press the return key to execute the command hence the $cmd\n
.
It is probably that you enter the value of letter
without quotes. It then treats the content of letter
as a function. Since it can't find the function, it throws a syntax error exception.
Try closing letter
in quotes ("letter")
You need to have a separate cards array for each movie. One way to do this is to make cards
a property of movie
.
In the HTML, we modify it to pass movie
to addCard()
. In this context, movie
is the current movie that the ng-repeat
is iterating over. Without this, the addCard()
function would not be aware of what movie it should be adding cards to. We also change the second ng-repeat
to use movie.cards
so that it knows to only look at the cards pertaining to that movie.
<div ng-repeat = "movie in movies" class="repeat"> <a ng-click="addCard(movie)" ui-sref=".container-big" >More info</a> <div ng-repeat="card in movie.cards" my-card="card"></div> </div>
In the JavaScript, we modify the addCard()
function so that it takes movie
as an argument. We also need to change it so that it creates a place to store the cards for that movie
$scope.addCard = function(movie) { // create movie.cards array if it does not exist if (!movie.cards) { movie.cards = []; } // add the card to the list of cards for this movie movie.cards.push(new Card()); };
-6139461 0 Why do want to have the value empty. You can describe during form. Such as:
<input type="text" name="firstname" values=<?php echo $firstname;?>
and on submit check as
$query = "Update table SET " if(isset($_POST['firstname']) && strlen($_POST['firstname'])>0){ $query.= "firstname = ".$_POST['variable']; }
-6632190 0 I just clear the @to field and return, so deliver aborts when it doesn't have anything there. (Or just return before setting @to).
-20684820 0Is onClick()
supposed to be an event handler for a button click? If so, the signature is wrong.
I believe you are looking for something like this. I have changed it from an ArrayList to a generic List. And initialized it with a collection initializer, and made it accessible from within your function. Please run the code below and let us know if you get exceptions.
List<string> MyList=new List<string>() {"Android", "Blackberry", "Hardcore"}; public void onClick(View view) { MyList.Add("testing"); adapter.notifyDataSetChanged(); }
-30879797 0 How to improve PreLoadMe script to support browsers with disabled JavaScript? Hi all, this script (by Niklaus Gerber) works, but there's one problem. Once I set it up, it starts from CSS styles by covering whole page with div. Then script comes to uncover fully loaded site, however, it also locks browsers with disabled JavaScript (infinite loading).
Can someone help me to unlock those users, by changing this script or suggest me something more friendly for also those folks? (it's not online yet).
The code is:
$(window).load(function() { $('#status').fadeOut();animation $('#preloader').delay(350)\.fadeOut('slow'); $('body').delay(350).css({'overflow':'visible'}); })
For the HTML:
<div id="preloader"> <div id="status"> </div> </div>
CSS:
body { overflow: scroll; } #preloader { position: fixed; top:0; left:0; right:0; bottom:0; background-color:#fff; z-index:99; } #status { width:200px; height:200px; position:absolute; left:50%; top:50%; background-image:url(../img/status.gif); background-repeat:no-repeat; background-position:center; margin:-100px 0 0 -100px; }
Thanks in advance for any sugestions.
-40086052 0 Linq query to get data from Database using group by clauseI am developing MVC4 application. I ended up with one complex scenario. I have following table in sql.
upld_Id Label Value Commited 1000 DocNumber 123 0 1000 ExpiryDate 01/01/2016 0 1000 Docnumber 456 1 1000 ExpiryDate 01/01/2018 1
I am supposed to get output in the below format.
upld_Id Label OldValue NewValue 1000 Docnumber 123 456 1000 ExpiryDate 01/01/2016 01/01/2018
I tried as below.
var logDetails = (from c in db.logTable join tbl in db.MetaTable on c.id equals tbl.id //GroupBy where (c.commited==false || c.commited==true) select new ClassName { //Get Values }).toList();
This is what i tried in LINQ. I am not sure how to apply LINQ here
var logDetails = (from c in db.ts_upldlog_content join tbl in db.ts_upld_doc on c.upld_docid equals tbl.upld_docid join doc in db.tm_doc_type on tbl.upld_doctypeid equals doc.doc_typeid where c.upld_docid==data group c by c.upld_contentlabel into grouping select new logdetails { updatedOn=c.updatedOn //Here Error contentLabel=grouping.Key, oldValue = grouping.FirstOrDefault(x => x.commited ==false).upld_contentvalue, newValue = grouping.FirstOrDefault(x => x.commited == true).upld_contentvalue, }).ToList();
Can someone tell me is this possible in LINQ? Thanks
-37722026 0In SQL Server 2016 it has its own link:
Just download it here: https://msdn.microsoft.com/en-us/library/mt238290.aspx
-14108638 0 How to disable foundation or bootstrap styling for a block of html code?I am using mailgun (although this question has nothing to do with mailgun) to parse the incoming email and mailgun will http post the parsed email to my server. When I received the post, I got the html code for the multi-part email. I want to display the html email to my user, I am using rails, so it's something like
<div> <%= raw(message.body_html) %> </div>
However, it looks different than it does when I view the same email in yahoo or hotmail (I know different email client will display the html email differently, but mine looks drastically different).
Here is how it looks on my self-built client:
And this is how it looks in yahoo for the same email:
I use Zurb Foundation as my styling framework. However, I think the email html comes with its own in-line styling, I look at the code it does look like it does, then it should look similar enough with other clients.
So what is the best practice to display html email assuming you get a block of html code and want to display it as is without letting other frameworks overwriting its style?
Further more, is it possible to disable Foundation (or twitter bootstrap for that matter) styling for a block of code, for example, something like
<div> <% disable_foundation_styling begin %> <%= raw(message.body_html) %> <% end %> </div>
Of course "disable_foundation_styling" is only my imagination.
Thanks in advance!
!!!!!!!!! Update 1/1/2013 !!!!!!!!!!!!!!!
As @Alex L. suggested, I tried but it doesn't quiet work as expected. The iframe renders everything in the view as before (see picture below), and that's understandable, since the iframe content is just the view of another controller, which in the case rails will include all the application layout templates as well. However, the toolbar is not my biggest concern, it's what's inside the iframe just looks exactly as before.
I suspect iframe may not be the way to do it. I look at the code of both gmail and yahoo, and they don't use iframe. Instead they use very deep nested to render the html email. The part of the html email have the same code for both yahoo and gmail, except that yahoo insert an id of its own for every single DOM element.
So now I suspect there is some foundation styling that affected how it looks.
I will update once I find out more.
-40300872 0 S3 static host redirect and strip slugIs it possible to create a static website redirect rule that redirects www.domain1.com/* --> www.domain2.com
without maintaining the slug ?
Something like this if wildcard was allowed:
<RoutingRules> <RoutingRule> <Condition> <KeyPrefixEquals>*</KeyPrefixEquals> </Condition> <Redirect> <HostName>www.domain2.com</HostName> <ReplaceKeyPrefixWith>/</ReplaceKeyPrefixWith> </Redirect> </RoutingRule> </RoutingRules>
-4860529 0 You should be able to setup the FILESTREAM provider
http://technet.microsoft.com/en-us/library/ee663474.aspx
-54971 0 Profiling visualization tools?I need to display profiling information pulled from a deeply embedded CPU, presenting it in a way which other developers on my team will be able to act upon. The profiling data is a snapshot of a cycle counter at the entry and exit of every function, so we have a call graph annotated with sub-microsecond timing accuracy. I'd prefer not to just dump out function names and timing like gprof, I'm looking for something easier to understand and act upon.
Has anyone worked with a particularly good profiling tool (on any platform), which made it easy to identify areas of the code to drill into? I'm looking for an inspirational example to follow for how to display the call graph, but if there is good tool with an input format I can massage my data to I'll use it. I could use Windows, Linux, or MacOS X to run the visualization tool.
A profiling article on IBM DeveloperWorks led me to GraphViz, with a profiling example on their site. Barring another suggestion here, I'll use GraphViz and mimic their profiling example.
-19578447 0Update
Use the split method of the String class to split the input string on the space character delimiter so you end up with a String array of words.
Then loop through that array using a modified for loop to print each item of the array.
import java.util.Scanner; public class Test { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter the sentence"); String sentence = in.nextLine(); showWords(sentence); } public static void showWords(String sentence) { String[] words = sentence.split(' '); for(String word : words) { System.out.println(word); } } }
-15256840 0 Using Visual Studio 2010 Without Using Solutions I find myself working for a group with a very large c++ code base that does not use Visual Studio accept as a compiler. We are using make files. I feel totally crippled without the visual studio advanced features such as intellisense, go to definition, and refactoring. Are there any good tricks out there to get Visual Studio 2010 to have these features without the projects and solutions? Or, baring that are there any good VI oriented alternatives?
Thanks
-17387993 0ConcurrentModificationExceptions are fail-fast. So they are on a best effort basis. Essentially not guaranteed to throw up immediately.
-19774733 0 Bundling and not bundling in production and test environments in ASP.NET MVCI am using the ASP.NET Bundling mechanism:
BundleTable.Bundles.Add(new ScriptBundle("~/Scripts/Master-js").Include( "~/Scripts/respond.min.js", "~/Scripts/jquery.form.js", "~/Scripts/jquery.MetaData.js", "~/Scripts/jquery.validate.js", "~/Scripts/bootstrap.js", "~/Scripts/jquery.viewport.js", "~/Scripts/jquery.cookie.js" ));
I want this to happen if the build is in release. If the build is in debug, I want the un-minified individual files to load so debugging would be easy.
The only way I have been able to do this is to write the following in my view:
<% if(HttpContext.Current.IsDebuggingEnabled) { Response.Write("<script type='text/javascript' src='../../Scripts/respond.min.js'></script>"); Response.Write("<script type='text/javascript' src='../../Scripts/jquery.form.js'></script>"); Response.Write("<script type='text/javascript' src='../../Scripts/jquery.MetaData.js'></script>"); Response.Write("<script type='text/javascript' src='../../Scripts/jquery.validate.js'></script>"); Response.Write("<script type='text/javascript' src='../../Scripts/bootstrap.js'></script>"); Response.Write("<script type='text/javascript' src='../../Scripts/jquery.viewport.js'></script>"); Response.Write("<script type='text/javascript' src='../../Scripts/jquery.cookie.js'></script>"); } else { Scripts.Render("~/Scripts/Master-js"); } %>
As you can see, I am repeating myself here. Is there a better way?
-31142599 0 Grails - remove from join table and delete the hasMany objectsI have the following domain classes:
class Shift { //etc }
and
class Schedule{ //etc static hasMany = [shifts:Shift] //etc }
Currently In a delete controller action I do a schedule.shifts.clear() and then a schedule.delete(). This deletes the schedule record itself and the associations in th ejoin table, but the shift objects are still in existence. How do I delete these also at the same time?
-1355546 0It's quite hard to tell which assembly is "most useful" unless you choose platform you want to use.
If you go for PC (intel, amd) start with x86 assembly. There is a common instruction set for different CPUs + some technology specific instructions like SSE. If you want to develop for Windows have a look at MASM, for Unix FASM would be a good choice.
-7414047 0try editing the log4j.properties file which can find at the WEB-INF/classes folder. For client side you need to add a log4j.properties file to a class patch and set the properties accordingly.
-26834099 0Not sure about the core thing. But I was able to use it after uninstalling hyper-v. You can do so in turn on/off Windows features.
-38759549 0 Listview Datapager - Index was out of range. Must be non-negative and less than the size of the collectionI am using Listview to display products list from database. OnPage Load products gets load properly but when I try to switch page using datapager pagination it gives this error
Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index at System.Collections.ArrayList.get_Item(Int32 index) at System.Web.UI.WebControls.DataKeyArray.get_Item(Int32 index) at shop.products_ItemDataBound(Object sender, ListViewItemEventArgs e)
Thing is if I use ItemDataBound then only I get this error. Else paginations works fine.
<asp:ListView ID="products" runat="server" DataKeyNames="ID" OnPagePropertiesChanging="OnPagePropertiesChanging"> <ItemTemplate> content </ItemTemplate> <LayoutTemplate> <div id="itemPlaceholderContainer" runat="server" style=""> <div runat="server" id="itemPlaceholder" /> </div> <div class="datapager"> <asp:DataPager ID="DataPager1" ClientIDMode="Static" runat="server" PageSize="12" PagedControlID="products" ViewStateMode="Enabled"> <Fields> <asp:NextPreviousPagerField ButtonType="Link" ShowFirstPageButton="false" ShowPreviousPageButton="False" ShowNextPageButton="false" ButtonCssClass="nextPre" /> <asp:NumericPagerField ButtonType="Link" ButtonCount="10" /> <asp:NextPreviousPagerField ButtonType="Link" ShowNextPageButton="true" ShowLastPageButton="false" ShowPreviousPageButton="false" ButtonCssClass="nextPre" /> </Fields> </asp:DataPager> <div class="clear"></div> </div> </LayoutTemplate> <EmptyDataTemplate> <strong>No Items Found....</strong> </EmptyDataTemplate> </asp:ListView>
Item DataBound
private void products_ItemDataBound(object sender, ListViewItemEventArgs e) { try { if (e.Item.ItemType == ListViewItemType.DataItem) { ListViewDataItem itm = (ListViewDataItem)e.Item; string productID = products.DataKeys(itm.DataItemIndex)("ID"); query = "SELECT stock_status FROM products WHERE ID = '" + productID + "'"; DataTable dt = this.GetData(query); if (dt.Rows.Count > 0) { ((Label)e.Item.FindControl("checkReadyStock")).Text = dt.Rows(0)("stock_status").ToString; if (((Label)e.Item.FindControl("checkReadyStock")).Text == "Ready Stock") { ((Image)e.Item.FindControl("readyStock")).Visible = true; } } } } catch (Exception ex) { Response.Write(ex); } }
DataPager
protected void OnPagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e) { (products.FindControl("DataPager1") as DataPager).SetPageProperties(e.StartRowIndex, e.MaximumRows, false); products.DataSource = ViewState("Data"); products.DataBind(); }
-18919882 0 I just spent a half a morning trying to figure this out myself. The answer lies in the "Override default catalog from connection" about halfway down the Project|Properties|JPA page. You must set this to the actual catalog that holds your schema, typically the server name. It defaults to the username you provide for the connection.
-33905632 0 background image too large and out of focusThis is my code
<style type="text/css"> body { background-size:cover; background-image:url('Orange.jpg'); background-repeat:no-repeat; background-attachment: fixed; background-size: 100% auto; } </style>
The background image is way too large, zoomed in, and out of focus Please help
Thanks, Duncan
-27004419 0 Get & store digits from stringI have a string of values like this:
=> "[\"3\", \"4\", \"60\", \"71\", \"49\", \"62\", \"9\", \"14\", \"17\", \"63\"]"
I want to put each value in an array so I can use each do. So something like this:
@numbers =>["72", "58", "49", "62", "9", "13", "17", "63"]
This is the code I want to use once the string is a usable array:
@numbers.each do |n| @answers << Answer.find(n) end
I have tried using split()
but the characters are not balanced on each side of the number. I also was trying to use a regex split(/\D/)
but I think I am just getting worse ideas.
The controller:
@scores = [] @each_answer = [] @score.answer_ids.split('/').each do |a| @each_answer << Answer.find(a).id end
Where @score.answer_ids
is:
=> "[\"3\", \"4\", \"60\", \"71\", \"49\", \"62\", \"9\", \"14\", \"17\", \"63\"]"
-20425329 0 I have not tried the Express version, but I found this answer, which may be helpful to you (though it is for an older version):
How to compile a 64-bit application using Visual C++ 2010 Express?
-17880270 0 sliding up down DIV on click with more categoriesI have very little understanding of javascripting so i would really appreciate it if someone helps me out
i would like this effect http://jsfiddle.net/dJS4g/ but instead of one link i would like to have 6 links that will show different content on click
javascript $(function() { $("a#toggle").click(function() { $("#contact").slideToggle(); return false; }); }); html <div id="contact"> Contact me! </div> <a href="#" id="toggle">Contact</a> css #contact { display: none; background: grey; color: #FFF; padding: 10px; }
**
FOUND WHAT I WAS LOOKING FOR HERE http://jsfiddle.net/jakecigar/XwN2L/2154/ THANK YOU EVERYONE FOR YOUR HELP
**
-6808035 0 Zend custom route not being recognized for controllerI'm creating a controller which will pull information of a painter from a database and display it: PainterController
. I have defined it like so:
<?php class PainterController extends Zend_Controller_Action { public function init() { //setup painter route $router = $this->getFrontController()->getRouter(); $router->addRoute( 'painter', new Zend_Controller_Router_Route( 'painter/:id', array( 'controller' => 'painter', 'action' => 'info' ) ) ); } public function indexAction() { //index } public function infoAction() { //info was requested for given ID } } ?>
As you can see, a route is setup to accept anything like domain.com/painter/12
where in this example the id 12 is passed to the infoAction.
Yet, when I visit such URL I the route is not being recognized, instead I get:
Message: Action "2" does not exist and was not trapped in __call() Stack trace: #0 /home/httpd/vhosts/xxx.com/subdomains/peter/httpdocs/library/Zend/Controller/Action.php(515): Zend_Controller_Action->__call('2Action', Array) #1 /home/httpd/vhosts/xxx.com/subdomains/peter/httpdocs/library/Zend/Controller/Dispatcher/Standard.php(295): Zend_Controller_Action->dispatch('2Action') #2 /home/httpd/vhosts/xxx.com/subdomains/peter/httpdocs/library/Zend/Controller/Front.php(954): Zend_Controller_Dispatcher_Standard->dispatch(Object(Zend_Controller_Request_Http), Object(Zend_Controller_Response_Http)) #3 /home/httpd/vhosts/xxx.com/subdomains/peter/httpdocs/library/Zend/Application/Bootstrap/Bootstrap.php(97): Zend_Controller_Front->dispatch() #4 /home/httpd/vhosts/xxx.com/subdomains/peter/httpdocs/library/Zend/Application.php(366): Zend_Application_Bootstrap_Bootstrap->run() #5 /home/httpd/vhosts/xxx.com/subdomains/peter/httpdocs/public/index.php(25): Zend_Application->run() #6 {main} Request Parameters: array ( 'controller' => 'painter', 'action' => '2', 'module' => 'default', )
Does anyone have a clue on why this would happen?
(FYI, I realize that the files are located in a public directory, this is due to a shared webhost constraint. The files are protected using .htaccess. This is unrelated to the question.)
Update: it appears that the above does work when defined in the bootstrap. However, I do not like to put a lot of logic in the bootstrap. Is it possible to define controller related routes inside the controller itself?
-20266532 0If you do something in sequence as you do in your code, then it is not a candidate for threading. Threads only help if something can be done in parallel, so in your case i.E. if you do not care in which order the numbers are printed.
-21249618 0Use the following steps:
go to window--Preferences--Android
then give your android sdk path
in my case:
like:/home/ravindmaurya/AndroidTa/adt-bundle-linux-x86_64-20130729/sdk
then press apply
-11398082 0You probably need to change the header:
Content-type: application/json
-10904074 0 Using:
> require(KernSmooth) Loading required package: KernSmooth KernSmooth 2.23 loaded Copyright M. P. Wand 1997-2009 > mod <- bkde(faithful$waiting) > str(mod) List of 2 $ x: num [1:401] 22.7 23 23.2 23.4 23.7 ... $ y: num [1:401] 3.46e-08 1.17e-07 1.40e-07 1.68e-07 2.00e-07 ...
is this not efficient enough?
> which(mod$y == max(mod$y)) [1] 245
density()
does something similar, but it returns 512 values of the density evaluate at 512 regular intervals of x
.
In both functions the number of points returned can be controlled. See argument gridsize
in bkde()
and n
in density()
. Of course, the precision of the approach does depend on the density of points at which the KDE is estimated so you won;t want to set this too low.
My gut tells me you may spend an awful lot more time thinking up and implementing a more efficient approach than you would spend just going with the above simple solution.
-33381859 0 Spring Roo JPA MS SQL Server Could not open JPA EntityManager org.hibernate.exception.GenericJDBCException: Could not open connectionI am trying to get codes using Spring Roo. I am following the tutorial: spring-roo-1.3.1.RC1/docs/html/beginning.html included at Roo docs. MS SQL Server TCP IP Enabled. The instance is running I try login using IP with MS SQL Management studio 127.0.0.1\sqlserverinstance working
#Updated at Tue Oct 27 15:43:39 ICT 2015 #Tue Oct 27 15:43:39 ICT 2015 PFS-015-PC\SQL2012 database.driverClassName=net.sourceforge.jtds.jdbc.Driver database.url=jdbc\:jtds\:sqlserver\://PFS-015-PC\SQL2012\:1433/restful database.username=sa database.password=sql2012
I try to Right Click project and RUN
This nightmare occured
cd C:\Users\mtoha\restful; "JAVA_HOME=C:\\Program Files\\Java\\jdk1.8.0_60" cmd /c "\"\"C:\\Program Files\\NetBeans 8.0.2\\java\\maven\\bin\\mvn.bat\" -Dmaven.ext.class.path=\"C:\\Program Files\\NetBeans 8.0.2\\java\\maven-nblib\\netbeans-eventspy.jar\" -Dfile.encoding=UTF-8 clean install\"" Scanning for projects... ------------------------------------------------------------------------ Building restful 0.1.0.BUILD-SNAPSHOT ------------------------------------------------------------------------ --- maven-clean-plugin:2.4.1:clean (default-clean) @ restful --- Deleting C:\Users\mtoha\restful\target --- aspectj-maven-plugin:1.4:compile (default) @ restful --- advice defined in org.springframework.mock.staticmock.AnnotationDrivenStaticEntityMockingControl has not been applied [Xlint:adviceDidNotMatch] advice defined in org.springframework.mock.staticmock.AbstractMethodMockingControl has not been applied [Xlint:adviceDidNotMatch] advice defined in org.springframework.scheduling.aspectj.AbstractAsyncExecutionAspect has not been applied [Xlint:adviceDidNotMatch] --- aspectj-maven-plugin:1.4:test-compile (default) @ restful --- this affected type is not exposed to the weaver: com.pfs.restful.domain.Faktur [Xlint:typeNotExposedToWeaver] this affected type is not exposed to the weaver: com.pfs.restful.domain.FakturItem [Xlint:typeNotExposedToWeaver] this affected type is not exposed to the weaver: com.pfs.restful.domain.Merchandise [Xlint:typeNotExposedToWeaver] this affected type is not exposed to the weaver: com.pfs.restful.domain.PfsUser [Xlint:typeNotExposedToWeaver] advice defined in org.springframework.orm.jpa.aspectj.JpaExceptionTranslatorAspect has not been applied [Xlint:adviceDidNotMatch] advice defined in org.springframework.mock.staticmock.AnnotationDrivenStaticEntityMockingControl has not been applied [Xlint:adviceDidNotMatch] advice defined in org.springframework.mock.staticmock.AbstractMethodMockingControl has not been applied [Xlint:adviceDidNotMatch] advice defined in org.springframework.mock.staticmock.AbstractMethodMockingControl has not been applied [Xlint:adviceDidNotMatch] advice defined in org.springframework.scheduling.aspectj.AbstractAsyncExecutionAspect has not been applied [Xlint:adviceDidNotMatch] --- maven-resources-plugin:2.6:resources (default-resources) @ restful --- Using 'UTF-8' encoding to copy filtered resources. Copying 4 resources --- maven-compiler-plugin:2.5.1:compile (default-compile) @ restful --- Nothing to compile - all classes are up to date --- maven-resources-plugin:2.6:testResources (default-testResources) @ restful --- Using 'UTF-8' encoding to copy filtered resources. skip non existing resourceDirectory C:\Users\mtoha\restful\src\test\resources --- maven-compiler-plugin:2.5.1:testCompile (default-testCompile) @ restful --- Nothing to compile - all classes are up to date --- maven-surefire-plugin:2.12:test (default-test) @ restful --- Surefire report directory: C:\Users\mtoha\restful\target\surefire-reports ------------------------------------------------------- T E S T S ------------------------------------------------------- Results : Tests in error: testFindAllFakturs(com.pfs.restful.domain.FakturIntegrationTest): Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Could not open connection testFlush(com.pfs.restful.domain.FakturIntegrationTest): Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Could not open connection testPersist(com.pfs.restful.domain.FakturIntegrationTest): Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Could not open connection testMarkerMethod(com.pfs.restful.domain.FakturIntegrationTest): Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Could not open connection testFindFaktur(com.pfs.restful.domain.FakturIntegrationTest): Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Could not open connection testMergeUpdate(com.pfs.restful.domain.FakturIntegrationTest): Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Could not open connection testFindFakturEntries(com.pfs.restful.domain.FakturIntegrationTest): Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Could not open connection testCountFakturs(com.pfs.restful.domain.FakturIntegrationTest): Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Could not open connection testRemove(com.pfs.restful.domain.FakturIntegrationTest): Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Could not open connection testFindAllFakturItems(com.pfs.restful.domain.FakturItemIntegrationTest): Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Could not open connection testFlush(com.pfs.restful.domain.FakturItemIntegrationTest): Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Could not open connection testPersist(com.pfs.restful.domain.FakturItemIntegrationTest): Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Could not open connection testMarkerMethod(com.pfs.restful.domain.FakturItemIntegrationTest): Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Could not open connection testMergeUpdate(com.pfs.restful.domain.FakturItemIntegrationTest): Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Could not open connection testFindFakturItemEntries(com.pfs.restful.domain.FakturItemIntegrationTest): Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Could not open connection testFindFakturItem(com.pfs.restful.domain.FakturItemIntegrationTest): Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Could not open connection testRemove(com.pfs.restful.domain.FakturItemIntegrationTest): Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Could not open connection testCountFakturItems(com.pfs.restful.domain.FakturItemIntegrationTest): Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Could not open connection testFlush(com.pfs.restful.domain.MerchandiseIntegrationTest): Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Could not open connection testPersist(com.pfs.restful.domain.MerchandiseIntegrationTest): Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Could not open connection testMarkerMethod(com.pfs.restful.domain.MerchandiseIntegrationTest): Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Could not open connection testCountMerchandises(com.pfs.restful.domain.MerchandiseIntegrationTest): Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Could not open connection testFindAllMerchandises(com.pfs.restful.domain.MerchandiseIntegrationTest): Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Could not open connection testMergeUpdate(com.pfs.restful.domain.MerchandiseIntegrationTest): Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Could not open connection testFindMerchandiseEntries(com.pfs.restful.domain.MerchandiseIntegrationTest): Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Could not open connection testRemove(com.pfs.restful.domain.MerchandiseIntegrationTest): Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Could not open connection testFindMerchandise(com.pfs.restful.domain.MerchandiseIntegrationTest): Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Could not open connection testCountPfsUsers(com.pfs.restful.domain.PfsUserIntegrationTest): Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Could not open connection testFindAllPfsUsers(com.pfs.restful.domain.PfsUserIntegrationTest): Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Could not open connection testFlush(com.pfs.restful.domain.PfsUserIntegrationTest): Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Could not open connection testPersist(com.pfs.restful.domain.PfsUserIntegrationTest): Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Could not open connection testMarkerMethod(com.pfs.restful.domain.PfsUserIntegrationTest): Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Could not open connection testFindPfsUser(com.pfs.restful.domain.PfsUserIntegrationTest): Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Could not open connection testMergeUpdate(com.pfs.restful.domain.PfsUserIntegrationTest): Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Could not open connection testFindPfsUserEntries(com.pfs.restful.domain.PfsUserIntegrationTest): Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Could not open connection testRemove(com.pfs.restful.domain.PfsUserIntegrationTest): Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Could not open connection Tests run: 36, Failures: 0, Errors: 36, Skipped: 0 ------------------------------------------------------------------------ BUILD FAILURE ------------------------------------------------------------------------ Total time: 8.153s Finished at: Wed Oct 28 08:58:43 ICT 2015 Final Memory: 14M/278M ------------------------------------------------------------------------ Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project restful: There are test failures. Please refer to C:\Users\mtoha\restful\target\surefire-reports for the individual test results. -> [Help 1] To see the full stack trace of the errors, re-run Maven with the -e switch. Re-run Maven using the -X switch to enable full debug logging. For more information about the errors and possible solutions, please read the following articles: [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
What I missed?
-20594537 0 About socket programming and REST designWe need to design a server that will serve a webpage to several clients but also query a remote database for these clients. One of the requirement for this project is that the whole system must be compliant with the REST architecture style. We need use Java as programming language but many questions arised while we were designing it.
We want to have a main thread that will get connections, as shown in this example:
// System.out.println("Starting a new web server using port " + port) try { ServerSocket reciever = new ServerSocket(port); while (true) { try { Socket s = reciever.accept(); Client c = new Client(s); } catch (IOException e) { System.err.println("New item creation failed."); IOUtil.close(reciever); } catch (InterruptedException e) { e.printStackTrace(); } } } catch (IOException e) { System.err.println("ServerSocket problem."); }
Then each connection will be created as a new thread (the Client object in the code) that will take care of reading ONE request. If the request is a GET, then the thread will serve the resource to the client. If it is a POST, then it will add the request to a buffer and let another thread handle the query to the database and also the answer back to the client. After handling this only request, the thread closes the socket and terminates.
Is the use of sockets violating the REST principle? In order to respect the REST architecture, do we need to destroy every Client object (thread & socket) after each HTTP message? Is there another way of client-server communication that does not use sockets?
-9785092 0 Redirect to a particular tab<ul class="tabs" style="background: "> <li><a href="javascript:tabSwitch('tab_1', 'content_1');" id="tab_1" class="active">Payment Gateway Basics</a></li> <li><a href="javascript:tabSwitch('tab_4', 'content_4');" id="tab_4" >Contact Us</a></li> </ul>
These are my tabs, once I submit a form in the "contact us" tab, it goes back to the first tab. Can anyone tell me how to stay in the same tab?
I'm using PHP server side switching, I'm using JavaScript.
(I used href
not onclick
in the listing. Stack Overflow doesn't allow to use more href
so I changed it into onclick
, before this post was edited).
jQuery.Deferred
objects provide a very elegant way to do this (I know you're not using jQuery 1.5: I'm just giving you a reason to upgrade ;-)
:
Assuming we have two scripts co-operating like the following:
// defines utilities var util = util || { loaded: $.Deferred() }; (function(){ $.extend(util, { msg: "Hello!" }); util.loaded.resolve(); })();
... and:
// uses them var util = util || { loaded: $.Deferred() }; util.loaded.then(function(){ alert(util.msg); });
... the alert will always fire after the first script has had a chance to define it's utilities no matter the order they load in. This has advantages over the setTimeout
and event based approaches in that it's easier to have multiple dependencies (using $.when
), doesn't use polling, and you don't have to worry about handling the order-of-loading explicitly.
The only thing that's kind of gross is that all of the modules have to include:
var util = util || { loaded: $.Deferred() };
... and $.extend()
it to make sure that they use the same deferred.
Pump the events manually with
Application.DoEvents();
-36178688 0 I resolved my issue. The problem was that I was using http://localhost:4200/ instead of http://127.0.0.1:4200/ and that's why I couldn't find django's cookie.
As soon as I found django's cookie, I just add an attribute to the header of the adapter.
My new adapter is shown below:
Ember Adapter:
import DS from 'ember-data'; export default DS.RESTAdapter.extend({ host: '/api', contentType: 'application/json', dataType: 'json', headers: { "X-CSRF-Token": 'django token', username: 'XXXX', password: 'XXXX' }, buildURL: function(modelName, id, snapshot, requestType, query) { var url = this._super(modelName, id, snapshot, requestType, query); return url + "/"; } });
-29447153 0 In your requirements, your explain that you want to allow a double click with a fast delay. But the e.getClickCount()==2
you use is not the solution for that because it's limited by your OS configuration. You can get it by looking the result of Toolkit.getDefaultToolkit().getDesktopProperty("awt.multiClickInterval")
A simple and good way to bypass the problem is that you handle yourself the delay between two clicks in the mouse listener. You could use a Timer where you can choose the interval max between your clicks and to handle by oneself the count.
The solution is rather simple. So since your code was testable, I modified it directly and i tested. It works for me. To summarize my modifications, I have added an boolean instance to count the current click count and have separated the double-click detection (technical) and the double click handling (logic) in two places. It's more readable. I have chosen 0.5 second as delay max authorized between two clicks. You can chose another value but if the value is too important (for example one second or more), it can give unexpected double clicks.
class CreateFrame extends JFrame { ... private boolean isAlreadyOneClick; ... addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (isAlreadyOneClick) { handleDoubleClick(e); isAlreadyOneClick = false; } else { isAlreadyOneClick = true; Timer t = new Timer("doubleclickTimer", false); t.schedule(new TimerTask() { @Override public void run() { isAlreadyOneClick = false; } }, 500); } } private void handleDoubleClick(MouseEvent e) { JTable table = (JTable) e.getSource(); Point p = e.getPoint(); int row = table.rowAtPoint(p); String type = getValueAt(row, 2).toString().toLowerCase(); if (type.contains("root") || type.contains("folder")) { File file = new File((path != null ? path + "/" + getValueAt(row, 1) : getValueAt(row, 1).toString())); if (file != null) repopulateFileFolderList(file); } else if (getValueAt(row, 1).toString().toLowerCase().contains("up one") && getValueAt(row, 2).toString().equals("")) { File file = path.getParentFile(); if (file != null) repopulateFileFolderList(file); else getTableRoot(); } else { System.out.println("Not a directory!"); } } }
-8822128 0 The problem is the where
clause - you are giving it an expression that will evaluate to a string expression, but the where
clause is used to specify conditions that must be satisfied to return records.
You need to rewrite the where
clause to specify records to be selected.
When you add new row in the table upon back button press, you can either add a new row in the table using
insertRowsAtIndexPaths:withRowAnimation:
or update your array (adding this extra row) with the help of which you show the rows and then reload the table view. Because when you reload your table view, its datasource methods will be called again and then you need to return updated number of sections, rows and cell's
-34759219 0Its old question , but may help someone.
You have to use Request.Form to get and call .Value to set the value.
HTML
<input runat="server" id="first_name_txt" type="text" placeholder="First Name" />
CODE BEHIND
//To get value: string myname=Request.Form["first_name_txt"]; // To set value: first_name_txt.Value="";
-22629566 0 rgba()
is a color value. You can only have a color value in the last background layer; specifying a color on any other layers makes the syntax invalid.1
If you need to overlay the background image with a semitransparent color, the only workaround for one element is to create an image of that color and overlay that instead. But since you're trying to apply a page background, you should be able to simply apply the color overlay to body
and the image to html
:
html { height: 100%; background: url(../img/background.png) repeat; } body { min-height: 100%; background: rgba(200, 54, 54, 0.5); }
Just keep in mind that body
needs to cover the entire area of html
as well, otherwise your color will only overlay part of the background image. The height
and min-height
styles above enforce this for height; for width, you will need to make sure body
does not have any side margins or a width that's less than 100%.
See this answer for a more extensive write-up on both approaches to html
and body
backgrounds.
1 It's understandably puzzling why colors are forbidden from any layer except the bottom one considering that color values with alpha channels exist and that you can still work around it with an image with the same alpha channels and the browser would still have to composite the background anyway. But that's just how it is, I guess. It doesn't look like this limitation is going to be addressed in Backgrounds level 4 either, so what do I know.
-35790251 0 how to extract word from rowI have a 46 MB csv file containing data. Essentially, I would like select only those rows that have particular word like "PRODUCT". There are 600 000 rows for this data. I have used grep()
to search for the string matching. Following are few lines of my data.
head(test) Item.Description UQC Year 1 PHARMACEUTICALS PRODUCTS.(MEDICINE) DOLEYKA SYRUP 100 ML NOS 2015 2 Multani mati hesh100gm x 160 (AyurvedicProducts) PAC 2015 3 Amla /Shikakai/ Aritha powder 100gm x 160 (Ayurvedic Products) PAC 2015 4 Godrej h.dye blk 40ml x 36 (Ayurvedic Products) PAC 2015 5 DR. COOLERS HERBAL LOZENGES.(2) DR. COOLERS HERBAL LOZENGES (MINT FLAVOUR) PAC 2015 6 Eno lemon/ regular 100gm x 48 (AyurvedicProducts) PAC 2015 Identifier RITC.Code 30049099 30049011 30049011 30049011 30049011 30049011
I have used test[grep("PRODUCT", rownames(test)), ]
. It gives me an error.
Based on this comment:
Trying .\SQLEXPRESS in SQL Server Management Studio Express throws an error that says that "This version of Microsoft SQL Server Management Studio Express can only be used to connect to SQL Server 2005 servers". So this is the problem, I think.
.\SQLEXPRESS
is the correct server name, but you have the wrong version of client tools (SQL Server Management Studio). To find out the version of SQL you are connecting to, there are a number of suggestions here: https://www.mssqltips.com/sqlservertip/1140/how-to-tell-what-sql-server-version-you-are-running/
But since you can't connect yet the easiest thing to do is go searching for sqlserver.exe
, right click, properties, version. If you have multiple version you need take note of the folder that it's in and check the SQLExpress one. You can also check in services.
Once you've worked out the version, download and install just the management tools for that version.
-33709697 0 "KeyValuePair is not defined" when invoking a method that requires that type as an argumentI receive the following error when attempting to invoke the function, "columnHasStreak" using REPL:
error FS0039: The type 'KeyValuePair' is not defined
I am attempting to run the following code using REPL:
module TicTacToe
open FsUnit open NUnit.Framework open System.Collections.Generic [<Test>] let ``some test to help me learn F#`` () = let columnHasStreak (column : list<KeyValuePair<int,bool>>) = column |> Seq.forall (fun cell -> cell.Value) let cells = [0..8] let connectCount = 3; let columns = [0..2]; let grid = [for cell in cells -> (cell, true)] |> Map.ofSeq let rowLocations = grid |> Seq.chunkBySize connectCount |> Seq.toList let columnLocations = [for i in columns -> rowLocations|> List.map (fun row -> row.[i])] let allColumnsHaveStreak = [for i in columns -> columnLocations.[i]] |> Seq.forall (fun column -> column |> columnHasStreak)
Can someone explain to me why I am receiving this error?
-26888430 0I think you are creating local variable of ChildBox Dialog so , even if you are assigning a value to its variable it will not work.
Rather create a pointer variable of ChildBox Dialog
void ParentDialog::OnInput() {
ChildBox *dlg; if (dlg->DoModal() == IDOK) { sampleCount = dlg->sampCnt; } dlg = NULL ;
}
-11552826 0 pass a textbox value to a label inside a grid view on a button click in asp.net 4 and C#I have 2 asp:panels. One asp:panel contains a textbox and button whose code is as follows
<asp:TextBox ID="tbGoal" runat="server" CssClass="textbox" Width="222px" Height="26px"></asp:TextBox><br /> <asp:Button ID="btnUpdate" runat="server" Text="Update Goal" CssClass="button" OnClick="btnUpdate_Click" /> /* **************************************************************************** * CODE BEHIND * ******************************************************************************** */ protected void btnUpdate_Click(object sender, EventArgs e) { // I am trying to pass the updated textbox value to a label which is inside a GridView // which is inside the second ASP:PANEL }
Can someone tell me if this is possible. Appreciate it
-40659704 0 Firefox ubuntu - unable to access video playerI installed firefox on ubuntu. I would like the selenium test to click on the play button in a video player. Unfortunately, the test fails everytime it tries to do so. I don't want to play the video on the linux box. I just want the test to click on the play button inside the video. How do I install flash player on ubuntu box so that firefox can load flash players correctly?
-39691454 0You should put the cardView as parent, and the LinearLayout inside.
-35382085 0If you want to obtain single row totals - let your outer query aggregate data too. With appropriate GROUP BY clause.
You have already grouped data per ID, Location, Class and Date - now group by higher granularity level. It is impossible to obtain avg_phone_contacts_perid
while you are requesting separate row per each id. Unless your desire is to see the same value of avg_phone_contacts_perid
in every row (for example to make a comparison) - this is possible to do by windows function AVG(...) OVER (...)
The View component must contain sufficient logic to display the interface to the user. Depending upon the framework used, there can be quite a bit of code in the View. The important thing is to ensure business logic lies in the Presenter.
Regarding your secondary query, all Presenter methods will be invoked on the EDT when the View calls them (in the case of Swing). Unless the action required by the Presenter is trivial, I would immediately kick off a background thread to complete the work. That thread will update the View when completed using SwingUtilities.invokeLater()
.
In fact, to avoid being tied to Swing, I tend to pass my own EventDispatcher
class to each Presenter. This is an interface with the same methods as SwingUtilities
. I can then substitute in a different class if necessary.
Side note: this can make unit-testing the Presenter with JUnit difficult, because the Presenter method (and the unit test) will complete before the background thread does. I tend to construct each Presenter with an Executor
that is responsible for running the background threads. Then, in a unit test environment, I pass in a special Executor
implementation that immediately executes the run()
method on the same thread. This ensures the unit tests are single-threaded. Example:
public class SingleThreadExecutor implements Executor { @Override public void execute(Runnable command) { command.run(); } }
-37029197 0 Exception while calling another screen in IOS I am new in IOS developing. In Main.storyoard
, I added a new viewcontroller
, assigned it to a new class LoginViewController
and provided a storyboard-ID loginview
. In the LoginViewController
class, after successful login I tried the following code to call the default viewcontroller having storyboard-ID webview
.
NSString *storyboardName = @"Main"; UIStoryboard *storyboard = [UIStoryboard storyboardWithName:storyboardName bundle: nil]; UIViewController * vc = [storyboard instantiateViewControllerWithIdentifier:@"webview"]; [self presentViewController:vc animated:YES completion:nil];
During debugging I got the following exception
2016-05-04 18:37:11.020 gcmexample[2690:86862] bool _WebTryThreadLock(bool), 0x7fa5d3f3d840: Tried to obtain the web lock from a thread other than the main thread or the web thread. This may be a result of calling to UIKit from a secondary thread. Crashing now... 1 0x11328d34b WebThreadLock 2 0x10e5547dd -[UIWebView _webViewCommonInitWithWebView:scalesPageToFit:] 3 0x10e555179 -[UIWebView initWithCoder:] 4 0x10e7b5822 UINibDecoderDecodeObjectForValue 5 0x10e7b5558 -[UINibDecoder decodeObjectForKey:] 6 0x10e5e1483 -[UIRuntimeConnection initWithCoder:] 7 0x10e7b5822 UINibDecoderDecodeObjectForValue 8
0x10e7b59e3 UINibDecoderDecodeObjectForValue 9 0x10e7b5558 -[UINibDecoder decodeObjectForKey:] 10 0x10e5e06c3 -[UINib instantiateWithOwner:options:] 11 0x10e3b9eea -[UIViewController _loadViewFromNibNamed:bundle:] 12 0x10e3ba816 -[UIViewController loadView] 13 0x10e3bab74 -[UIViewController loadViewIfRequired] 14 0x10e3bb2e7 -[UIViewController view] 15 0x10eb65f87 -[_UIFullscreenPresentationController _setPresentedViewController:] 16 0x10e38af62 -[UIPresentationController initWithPresentedViewController:presentingViewController:] 17 0x10e3cdc8c -[UIViewController _presentViewController:withAnimationController:completion:] 18 0x10e3d0f2c -[UIViewController _performCoordinatedPresentOrDismiss:animated:] 19 0x10e3d0a3b -[UIViewController presentViewController:animated:completion:] 20 0x10d065eed 34-[LoginViewController btnSign_in:]_block_invoke 21 0x10fd3f6b5 __75-[__NSURLSessionLocal taskForClass:request:uploadFile:bodyData:completion:]_block_invoke 22 0x10fd51a02 __49-[__NSCFLocalSessionTask _task_onqueue_didFinish]_block_invoke 23 0x10d1dc304 __NSBLOCKOPERATION_IS_CALLING_OUT_TO_A_BLOCK 24 0x10d118035 -[NSBlockOperation main] 25 0x10d0faf8a -[__NSOperationInternal _start:] 26 0x10d0fab9b __NSOQSchedule_f 27 0x11057f49b _dispatch_client_callout 28 0x1105658ec _dispatch_queue_drain 29 0x110564e0d _dispatch_queue_invoke 30 0x110567a56 _dispatch_root_queue_drain 31 0x1105674c5 _dispatch_worker_thread3
Does anyone know whats the error here? Please help.
-33547084 0Here is the code to remove the whole div
and the iframe
inside.
$(window).resize(function () { if ($(this).width() < 1280) { $("#video-container").remove(); } });
But since you trigger it on resize, what's when the window width increases again? If you just want to hide the iframe on lower resolutions and show it again when user resizes back to higher resolution, then I would recommend to use hide()
and show()
(or use the answer proposed by @Sergey Kopyrin)
Code sample
$(window).resize(function () { if ($(this).width() < 1280) { $("#video-container").hide(); } else{ $("#video-container").show(); } });
You can also specify a duration parameter inside those methods (e.g. $("#video-container").hide(500)
) so it will not be hidden abruptly.
I am initially seeking guidance to make sure I go in the right direction. From there I will come back with the code and ask for further assistance. I realize it isn't cool to say "hey I dont know what I am doing so I want you to do it for me."
So, here is my situation. I would say my php skills are amateur, and I am looking to increase them by working on projects for myself so I can learn through practice and application. I have created a webpage which contains a form that is used to update a XML file (I am playing around with flatfile DBs at the moment). All works well, the file is updated and the users is brought back to the page and the updated file is displayed. What I would like to do is allow the user to receive an update while they are browsing the website that the XML file has been updated, as well as alert them to the file update if they are returning to the website after having left.
My thoughts are that this would be done by using php session variables, one when they first access the website and another when the XML file is updated by a user. For the one when they access the site I thought a variable with a unique ID and timestamp as well as a timestamp of the files lastmodified value. I realize that this requires keeping storage of the session values since the value will have to be compared to something or else it will always appear as the most recent version, hence no changes.
Now that I think about it I guess you wouldn't need a session variable created on file update since the comparison will be based on the lastmodified value.
Just want to know if I am on the right track or completely off-base.
Any input is greatly appreciated.
-20978310 0Well try this lines, after you store each line in an array...
$csv = array(); $file = fopen('source.csv', 'r'); while (($result = fgetcsv($file,0,";")) !== false) { $csv[] = $result; } fclose($file); function content_to_columns($data){ foreach ($data as $line=>$value){ $data[$line]=explode(";",$value); } print_r[$data]; //comment when not needed. } content_to_columns($csv_file); //
then you can really get any value knowing the line and the columns number lets say your data is
A | B 10| 0 20|20
$csv[0][0] is 10
Doing operational math with it is like:
$csv[0][0]*=5; //multiplies by 5 the cell value
-2218824 0 The format sounds like a good solution.
Perhaps a (few) nice regular expression(s) to cut your input variable into groups.
I would try to use as many existing formats if you can:
http://blog.stevex.net/string-formatting-in-csharp/
re.sub does not perform the substitution in-place. It returns a new string with the result of the substitution. You are free to reassign to the original variable name if you like, of course.
So what you want is
page = re.sub("&", '', page)
-38617868 0 The commits are outputted by the git svn clone
command, preceded by an r. The last commit that is outputted is the problematic one.
The next example shows what the git svn clone
command outputs when begin procesing the Subversion revision 15
as the Git commit 373fb1...
:
r15 = 373fb1de430a6b1e89585425f276aae0058c3deb (refs/remotes/svn/trunk)
git svn clone
command using the -r
(revision) optionUse this method:
git svn clone -r 0:<problematic_revision - 1> <repo URL> git svn clone -r <problematic_revision - 1>:problematic_revision <repo URL> git svn clone -r <problematic_revision>:HEAD <repo URL>
Supposing the revision 15
as the problematic one, and the repo in /tmp/svn/repo/
, the solution would be:
git svn clone -r 0:14 file:///tmp/svn/repo/ git svn clone -r 14:15 file:///tmp/svn/repo/ git svn clone -r 15:HEAD file:///tmp/svn/repo/
-27064822 0 nested grid control not accessible ? Null values ? problems Asp.Net Code
<asp:GridView ID="gv_current_report" runat="server" CssClass="grid" BorderStyle="Solid" BorderColor="#336699" DataKeyNames="staff_id" AutoGenerateColumns="False" GridLines="None" OnRowDataBound="gv_current_report_RowDataBound"> <AlternatingRowStyle BackColor="#DCE4F9" /> <Columns> <asp:TemplateField> <ItemTemplate> <img alt="" style="cursor: pointer" src="images/plus.png" width="30" /> <asp:Panel ID="detail_grid" runat="server" Style="display: none"> <asp:GridView ID="gv_detail" runat="server" AutoGenerateColumns="false" CssClass="child-grid"> <Columns> <asp:BoundField ItemStyle-Width="150px" DataField="branch_name" HeaderText="Branch Name" /> <asp:BoundField ItemStyle-Width="150px" DataField="date_contacted" HeaderText="Contacted Date" /> <asp:BoundField ItemStyle-Width="150px" DataField="name" HeaderText="Staff Name" /> </Columns> </asp:GridView> </asp:Panel> </ItemTemplate> </asp:TemplateField>
C# Code
protected void gv_current_report_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { Int32 staff_id = Convert.ToInt32(gv_current_report.DataKeys[e.Row.RowIndex].Value); db = new ReportsDataContext(); gv_detail.DataSource = db.tracker_new_report_broker_status_change_current_detail(staff_id); gv_detail.DataBind(); } }
the problem is the panel and the grid view are not accessible in c#? If I create the controls in designer, its accessible but throwing an error
Object reference not set to an instance of an object
Found out the grid view control is NULL in run time.
( i.e.) gv_detail=Null
Anyone please shed some light. Any help will be much appreciated!!!
-6817303 0Don't do it.
It's very likely that your server will never become compromised, and that your application will be mostly secure, blah blah blah, that's not the point. It is possible for a server to become partially compromised (too many vectors of attack, what if the php json_encode
function became compromised on your server?).
The simple solution is not to trust anything sent by anyone. Modern browsers have native JSON parsers, and www.json.org provides a long list of JSON parsers for various different languages. The JS versions will fall back on the native implementation for speed.
What all this means is that there's no good reason to use eval
for JSON parsing.
I have a working sample on Github that supports inotify directory create/delete events. A small Watch class takes care of mapping wd (watch descriptors) to file/folder names. Here is a snippet showing how to handle inotify CREATE and DELETE events. The full sample is on Github.
if ( event->mask & IN_CREATE ) { current_dir = watch.get(event->wd); if ( event->mask & IN_ISDIR ) { new_dir = current_dir + "/" + event->name; wd = inotify_add_watch( fd, new_dir.c_str(), WATCH_FLAGS ); watch.insert( event->wd, event->name, wd ); total_dir_events++; printf( "New directory %s created.\n", new_dir.c_str() ); } else { total_file_events++; printf( "New file %s/%s created.\n", current_dir.c_str(), event->name ); } } else if ( event->mask & IN_DELETE ) { if ( event->mask & IN_ISDIR ) { new_dir = watch.erase( event->wd, event->name, &wd ); inotify_rm_watch( fd, wd ); total_dir_events--; printf( "Directory %s deleted.\n", new_dir.c_str() ); } else { current_dir = watch.get(event->wd); total_file_events--; printf( "File %s/%s deleted.\n", current_dir.c_str(), event->name ); } }
-11817824 0 document.getElementsByClassName('shiftTrRow') ^
returns a NodeList, i.e. an array of elements. You will need to loop over them and remove every of them on its own (but watch out, the collection is live and will shrink while you remove the elements).
Also, the getElementsByClassName
may return elements that are no rows of that table at all, resulting in the NOT FOUND
exception you receive.
However, the simplest way to remove rows from a table is its deleteRow
method:
var table = document.getElementById('resultsTable'); while (table.rows.length > 0) table.deleteRow(0);
-5474602 0 I had this problem and got around it by manually adding the Interop.ShDocVw.dll into the output directory.
-277622 0To store a photo in AD, you can use the jpegPhoto
attribute (see formal description in MSDN). Here is a way to do it using VBScript, and here's one to do it using VB.NET.
I'm not sure Outlook 2007 makes use of this value (my guess is - it does not), but it's worth a try. My guess is even that Outlook does not care about the jpegPhoto
if you put someone from the GAL to your personal address book. Anyway, this should be easy enough to test.
If all else fails, you are stuck with either making clear that it doesn't work or building a custom form that reads the value.
-32097560 0 Getting post ID within shortcode on page templateI am using a plugin called: InPost Gallery. I have added the shortcode to my page template so that I can show gallery on each page. Currently the shortcode has post_id="10" I need the post ID to change for each page to show images that below to each page, and to therefore use a code such as get_post_ID() however I'm currently unable to get this to work..
Here is the relevant shortcode-
<?php echo do_shortcode('[inpost_gallery thumb_width="100" thumb_height="100" post_id="10" thumb_margin_left="0" thumb_margin_bottom="0" thumb_border_radius="2" thumb_shadow="0 1px 4px rgba(0, 0, 0, 0.2)" js_play_delay="3000" id="" random="0" group="0" border="" type="yoxview" show_in_popup="0" album_cover="" album_cover_width="200" album_cover_height="200" popup_width="800" popup_max_height="600" popup_title="Gallery"][/inpost_gallery]'); ?>
Here is my template PHP which incorporates this shortcode-
<?php // album download start // if ( isset($_GET['download']) ) { // header('Content-type: application/mp3'); // header('Content-Disposition: attachment; filename='.basename($_GET['download'])); // readfile( $_GET['download'] ); // } // album download end get_header(); global $cs_transwitch,$prettyphoto_flag; $prettyphoto_flag = "true"; $cs_album = get_post_meta($post->ID, "cs_album", true); if ( $cs_album <> "" ) { $xmlObject = new SimpleXMLElement($cs_album); $cs_layout = $xmlObject->cs_layout; $cs_sidebar_left = $xmlObject->cs_sidebar_left; $cs_sidebar_right = $xmlObject->cs_sidebar_right; } if ( $cs_layout == "left" ) { $cs_layout = "two-thirds column right"; $show_sidebar = $cs_sidebar_left; } else if ( $cs_layout == "right" ) { $cs_layout = "two-thirds column left"; $show_sidebar = $cs_sidebar_right; } else $cs_layout = "sixteen columns left"; ?> <div id="container" class="container row"> <div role="main" class="<?php echo $cs_layout;?>" > <?php /* Run the loop to output the post. * If you want to overload this in a child theme then include a file * called loop-single.php and that will be used instead. */ //get_template_part( 'loop', 'single_cs_album' ); ?> <?php if ( have_posts() ): while ( have_posts() ) : the_post(); ?> <?php //showing meta start $cs_album = get_post_meta($post->ID, "cs_album", true); if ( $cs_album <> "" ) { $xmlObject = new SimpleXMLElement($cs_album); $cs_layout = $xmlObject->cs_layout; $cs_sidebar_left = $xmlObject->cs_sidebar_left; $cs_sidebar_right = $xmlObject->cs_sidebar_right; $album_release_date = $xmlObject->album_release_date; $album_social_share = $xmlObject->album_social_share; $album_buy_amazon = $xmlObject->album_buy_amazon; $album_buy_apple = $xmlObject->album_buy_apple; $album_buy_groov = $xmlObject->album_buy_groov; $album_buy_cloud = $xmlObject->album_buy_cloud; } //showing meta end ?> <div id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <h1 class="heading"><?php the_title(); ?></h1> <div class="in-sec"> <?php // getting featured image start $image_id = get_post_thumbnail_id ( $post->ID ); if ( $image_id <> "" ) { //$image_url = wp_get_attachment_image_src($image_id, array(208,208),true); $image_url = cs_attachment_image_src($image_id, 208, 208); $image_url = $image_url; //$image_url_full = wp_get_attachment_image_src($image_id, 'full',true); $image_url_full = cs_attachment_image_src($image_id, 0, 0); $image_url_full = $image_url_full; } else { $image_url = get_template_directory_uri()."/images/admin/no_image.jpg"; $image_url_full = get_template_directory_uri()."/images/admin/no_image.jpg"; } //$image_id = get_post_thumbnail_id ( $post->ID ); //$image_url = wp_get_attachment_image_src($image_id, array(208,198),true); //$image_url_full = wp_get_attachment_image_src($image_id, 'full',true); // getting featured image end ?> <div class="light-box album-tracks album-detail <?php if($image_id == "") echo "no-img-found";?> "> <div id="main-container"> <div id="leftcolumn"> <a rel="prettyPhoto" name="<?php the_title(); ?>" href="<?php echo $image_url_full?>" class="thumb" > <?php echo "<img src='".$image_url."' />";?> </a> <br> <br> <div id="inpostgallery"><?php echo do_shortcode('[inpost_gallery thumb_width="104" thumb_height="104" post_id="10" thumb_margin_left="0" thumb_margin_bottom="0" thumb_border_radius="2" thumb_shadow="0 1px 4px rgba(0, 0, 0, 0.2)" js_play_delay="3000" id="" random="0" group="0" border="" type="yoxview" show_in_popup="0" album_cover="" album_cover_width="200" album_cover_height="200" popup_width="800" popup_max_height="600" popup_title="Gallery"][/inpost_gallery]'); ?></div> </div> <div id="rightcolumn"> <div class="desc"> <p style="font-size:12px;"><span class="bold" style="text-transform:uppercase; color:#262626;"><?php _e('Categories', CSDOMAIN); ?> :</span> <?php /* translators: used between list items, there is a space after the comma */ $before_cat = " ".__( '',CSDOMAIN ); $categories_list = get_the_term_list ( get_the_id(), 'album-category', $before_cat, ', ', '' ); if ( $categories_list ): printf( __( '%1$s', CSDOMAIN ),$categories_list ); endif; '</p>'; ?> </p> <br> <h4><?php _e('Description', CSDOMAIN); ?></h4> <div class='txt rich_editor_text'> <?php the_content(); ?> </div> <div class="clear"></div> <?php edit_post_link( __( 'Edit', CSDOMAIN ), '<span class="edit-link">', '</span>' ); ?> </div></div> </div> <div class="clear"></div> </div> </div> <div class="in-sec"> <div class="album-opts"> <div class="share-album"> <?php $cs_social_share = get_option("cs_social_share"); if($cs_social_share != ''){ $xmlObject_album = new SimpleXMLElement($cs_social_share); if($album_social_share == 'Yes'){ social_share(); }?> <?php }?> </div> <?php if($album_buy_amazon != '' or $album_buy_apple != '' or $album_buy_groov != '' or $album_buy_cloud != ''){?> <div class="availble"> <h4><?php if($cs_transwitch =='on'){ _e('Buy This',CSDOMAIN); }else{ echo __CS('buy_now', 'Buy This'); }?></h4> <?php if ( $album_buy_amazon <> "" ) echo ' <a target="_blank" href="'.$album_buy_amazon.'" class="amazon-ind"> <span>';if($cs_transwitch =='on'){ _e('Amazon',CSDOMAIN); }else{ echo __CS('amazon', 'Amazon'); } echo '</span></a> '; if ( $album_buy_apple <> "") echo ' <a target="_blank" href="'.$album_buy_apple.'" class="apple-ind"> <span>'; if($cs_transwitch =='on'){ _e('Apple',CSDOMAIN); }else{ echo __CS('itunes', 'iTunes'); } echo '</span></a> '; if ( $album_buy_groov <> "") echo ' <a target="_blank" href="'.$album_buy_groov.'" class="grooveshark-ind"> <span>'; if($cs_transwitch =='on'){ _e('GrooveShark',CSDOMAIN); }else{ echo __CS('grooveshark', 'GrooveShark'); } echo '</span></a> '; if ( $album_buy_cloud <> "") echo ' <a target="_blank" href="'.$album_buy_cloud.'" class="soundcloud-ind"> <span>'; if($cs_transwitch =='on'){ _e('SoundCloud',CSDOMAIN); }else{ echo __CS('soundcloud', 'SoundCloud '); } echo '</span></a> '; ?> </div> <?php }?> <div class="clear"></div> </div> </div> <?php foreach ( $xmlObject as $track ){ if ( $track->getName() == "track" ) { ?> <div class="in-sec"> <?php enqueue_alubmtrack_format_resources(); ?> <div class="album-tracks light-box"> <?php $counter = 0; foreach ( $xmlObject as $track ){ $counter++; if ( $track->getName() == "track" ) { echo "<div class='track'>"; echo "<h5>"; echo $album_track_title = $track->album_track_title; echo "</h5>"; echo "<ul>"; if ($track->album_track_playable == "Yes") { echo ' <li> <div class="cp-container cp_container_'.$counter.'"> <ul class="cp-controls"> <li><a style="display: block;" href="#" class="cp-play" tabindex="1"> <span>'; if($cs_transwitch =='on'){ _e('Play',CSDOMAIN); }else{ echo __CS('play', 'Play'); } echo '</span></a></li> <li><a href="#" class="cp-pause" style="display: none;" tabindex="1"> <span>'; if($cs_transwitch =='on'){ _e('Pause',CSDOMAIN); }else{ echo __CS('pause', 'Pause'); } echo '</span></a></li> </ul> </div> <div style="width: 0px; height: 0px;" class="cp-jplayer jquery_jplayer_'.$counter.'"> <img style="width: 0px; height: 0px; display: none;" id="jp_poster_0"> <audio src="'.$track->album_track_mp3_url.'" preload="metadata" ></audio> </div> <script> jQuery(document).ready(function($){ var myCirclePlayer = new CirclePlayer(".jquery_jplayer_'.$counter.'", { mp3: "'.$track->album_track_mp3_url.'" }, { cssSelectorAncestor: ".cp_container_'.$counter.'", swfPath: "'.get_template_directory_uri().'/scripts/frontend/Jplayer.swf", wmode: "window", supplied: "mp3" }); }); </script> </li> '; } if ($track->album_track_downloadable == "Yes"){ echo '<li><a href="'.$track->album_track_mp3_url.'" class="download"> <span>'; if($cs_transwitch =='on'){ _e('Download',CSDOMAIN); }else{ echo __CS('download', 'Download'); } echo '</span></a></li>'; } if ($track->album_track_lyrics <> "") { echo '<li><a href="#lyrics'.$counter.'" rel="prettyPhoto[inline]" title="'.$album_track_title.'" class="lyrics"> <span>'; if($cs_transwitch =='on'){ _e('Lyrics',CSDOMAIN); }else{ echo __CS('lyrics', 'Lyrics'); } echo '</span></a></li>';} if ($track->album_track_buy_mp3 <> ""){ echo '<li><a href="'.$track->album_track_buy_mp3.'" class="buysong"> <span>'; if($cs_transwitch =='on'){ _e('Buy Song',CSDOMAIN); }else{ echo __CS('buy_now', 'Buy Song'); } echo '</span></a></li>';} echo "</ul>"; echo ' <div id="lyrics'.$counter.'" style="display:none;"> '.str_replace("\n","</br>",$track->album_track_lyrics).' </div> '; echo "</div>"; } } ?> <div class="clear"></div> </div> </div> <?php } } ?> <div class="clear"></div> <?php if ( get_the_author_meta( 'description' ) ) :?> <div class="in-sec" style="margin-top:20px;"> <div class="about-author"> <div class="avatars"> <?php echo get_avatar( get_the_author_meta( 'user_email' ), apply_filters( 'PixFill_author_bio_avatar_size', 53 ) ); ?> </div> <div class="desc"> <h5><a href="<?php echo get_author_posts_url( get_the_author_meta( 'ID' ) ); ?>"><?php _e('About', CSDOMAIN); ?> <?php echo get_the_author(); ?></a></h5> <p class="txt"> <?php the_author_meta( 'description' ); ?> </p> <div class="clear"></div> </div> <div class="clear"></div> </div> </div> <?php endif; ?> </div> <?php endwhile; endif; // end of the loop. ?> <?php comments_template( '', true ); ?> </div> <?php if( $cs_layout != "sixteen columns left" and isset($show_sidebar) ) { ?> <!--Sidebar Start--> <div class="one-third column left"> <?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar($show_sidebar) ) : ?> <?php endif; ?> </div> <!--Sidebar Ends--> <?php }?> <div class="clear"></div><!-- #content --> </div><!-- #container --> <div class="clear"></div> <?php get_footer(); ?>
-21887830 0 Build a generator of scale/object tuples, and take the max
of that. By putting the scale first, max
keys off that correctly.
locators = ((getAttr(locator+'.localScaleY'), locator) for locator in pm.ls('locator*')) yMaxValue, locator = max(locators)
A few outputs for reference:
>>> list(locators) # Result: [(1.0, nt.Transform(u'locator01')), (2.0, nt.Transform(u'locator02')), (3.0, nt.Transform(u'locator03')), (1.0, nt.Locator(u'locator0Shape1')), (2.0, nt.Locator(u'locator0Shape2')), (3.0, nt.Locator(u'locator0Shape3'))] # >>> yMaxValue # Result: 3.0 # >>> locator # Result: nt.Locator(u'locator0Shape3') #
-13903732 0 There are multiple issues that should be looked at:
@Async
, for instance. Then your transaction is not beholden to network connectivity or browser/HTTP timeouts.At the end of the day, ORMs will always be slower than base SQL. Consider swtiching over to base SQL, maybe concatenating SQL statements so that you have fewer database trips, or using a stored proc, passing bactches of data to the proc and have it run the inserts.
-16811250 0Before you do a git push
you have to do a git pull
. Other person's work has to be merged with your code first and then you can push your changes to the repository. git pull will keep your updated code as it is and only add/update code (meaning that git will merge code) from the last commit (other person's code).
In case where both of the developers have worked on the same piece of code then git will show conflicts which have to be resolved first.
-22928181 0Let's make an answer out of these good comments:
It looks to me like the code that works actually executes the block and the block's return result is the parameter passed to setRegion: where the second attempt passes the block itself as a parameter to setRegion:, which is of course expecting an MKCoordinateRegion as its parameter, not a block.
And (credit to MartinR), you can force evaluation of the block with an extra set of parentheses:
EDIT I'll get this right eventually
[self.mapView setRegion:^MKCoordinateRegion(void){ CLLocationCoordinate2D centerCoordinate = [Location sharedManager].coordinate; MKCoordinateSpan span = MKCoordinateSpanMake(0.01, 0.01); return MKCoordinateRegionMake(centerCoordinate, span); }()];
-22155056 0 You could also do this :
var sale = parseInt(url.split('/sales/')[1], 10); if (!isNaN(sale)) { // do something }
parseInt()
returns NaN
(Not A Number) in case of failure.
Here is a function :
function toSaleId(url) { var id = parseInt(url.split('/sales/')[1], 10); if (!isNaN(id)) return id; }
Usage examples :
var sale = toSaleId('/sale/1234'); // 1234 var sale = toSaleId('/sale/1234/anotherworld'); // 1234 var sale = toSaleId('/sale/anotherworld/1234'); // undefined
-4375833 0 how can I add a label after a select in the same table cell? I want to display some drop-lists in the web page, so I created table, table body, row and cell with document.createElement() method; then I create the select elements and add them to the cells with appendChild() method. The web page can display the drop-lists.
Then I want to add a sentence to give user a hint, like "This drop-list is for xxxx, and you can use it to xxx". I decide to use label to do it. So I create a label. But I don't want to add the label to a separate cell behind the drop-list. I want to add the label just after the drop-list. So I use appendChild() again to add the label and select in the same cell - Firstly append select, secondly append label. But the label is displayed BEFORE the select in the web page.
Then I tried to append the label to the select as a child node of the select. Then the label disappears. Only select is displayed.
I'm a very newbie about HTML/Javascript/DOM. Maybe my thought is wrong from the beginning. Is there anyone can give me a way to implement my requirement? I just want to add a sentence after a drop-list.
Thanks in advance.
======================================================
if (request.readyState == 4 && request.status == 200) { maindiv = document.getElementById("maintable"); optiondiv = getDivRef("optiondiv"); //create a table to hold the options. mytable = document.createElement("table"); mytablebody = document.createElement("tbody"); option_array = splitOptions(request.responseText.replace(/[\r\n]/g, ""), ';'); for (xindex = 0; xindex < option_array.length; xindex++) { _select = createSelect(_tmp_option_pair[0]); mycurrent_row = document.createElement("tr"); mycurrent_cel2 = document.createElement("td"); // for drop list mycurrent_cel3 = document.createElement("td"); // for hint try { for (yindex = 0; yindex < _tmp_option_list.length; yindex++) { _select.add(new Option(_tmp_option_list[yindex], yindex), null); } }catch (ex) { for (yindex = 0; yindex < _tmp_option_list.length; yindex++) { _select.add(new Option(_tmp_option_list[yindex], yindex)); } } _label2 = createLabel(_tmp_option_pair[0] + "_Label2"); _label2.setAttribute("for", _select.id); _label2.innerText = "test1"; //add obj to dom tree mycurrent_cel2.appendChild(_select); mycurrent_cel2.appendChild(_label2); mycurrent_row.appendChild(mycurrent_cel2); mycurrent_row.appendChild(mycurrent_cel3); mytablebody.appendChild(mycurrent_row); } }
The generated html code is
<td> <select is="GuestID"> <option>xxxxx</option> ..... </select> <label id="GuestID_Label2" for="GuestID">test1</label> </td>
The CSS code
label { font-weight: bold; text-align: right; width: 100px; display: block; float: left; clear: left; margin-right: 3px; cursor: pointer }
-12503664 0 Check for expired sessions on every Page_Init event. If there are too many pages to do this check, this is what I usually do:
Good luck.
-9466009 0Something like this (tested in Octave):
x = [1 3 7]; max(abs(x - [x(2:end) x(1)]))
-25375166 0 You should be able to define a custom sort function that sorts by any item in your object. The key bit is to convert the object to an array in the filter function.
Here's an example:
app.filter('orderByDayNumber', function() { return function(items, field, reverse) { var filtered = []; angular.forEach(items, function(item) { filtered.push(item); }); filtered.sort(function (a, b) { return (a[field] > b[field] ? 1 : -1); }); if(reverse) filtered.reverse(); return filtered; }; });
You would then call it like this:
<div ng-repeat="(key, val) in cal | orderByDayNumber: 'day' ">
Note, you shouldn't write val.day
as that is assumed.
Look at this great blog post here for more info.
EDIT: In fact, it looks like your structure is actually already an array, so while this technique will still work, it may not be necessary - it might have just been the way you were adding the parameter to orderBy that was causing issues.
-17441691 0 Fabrication::MisplacedFabricateError while using Fabrication Gem on Rails 2.3.16I am using Fabrication gem v-2.5.0 on Rails 2.3.16 but get the following errors when I run the unit test cases:
Below is the code snippet :
First case
Fabricate(:some_modal) Fabrication::MisplacedFabricateError: # from /Users/user_xyz/.rvm/gems/ree-1.8.7- 2011.03@project/gems/fabrication-2.5.0/lib/fabrication.rb:51:in `Fabricate' from (irb):3
Second case
Fabricate(:some_other_modal) SyntaxError: /Users/user_xyz/.rvm/gems/ree-1.8.7-2011.03@project/gems/fabrication-2.5.0/lib/fabrication/generator/active_record.rb:8: syntax error, unexpected ':', expecting ')' ...ttributes, without_protection: true)
Can someone please help me resolve these.
Modal Class :
class ErrorCode attr_accessor :mappings has_many :error_code_mappings end
Fabricator :
Fabricator(:error_code) do application_id 77 error_code_mappings(:count => 3) { |error_code, i| Fabricate.build(:error_code_mapping, :error_code => Fabricate.build(:error_code, :code => error_code.code + i))} end
Unit test file:
require 'test_helper' class ErrorCodeTest < ActiveSupport::TestCase context "ErrorCode" do setup do @error_code = Fabricate.build(:error_code) assert(@error_code.valid?) end should "have setter for mapping attribute" do assert_respond_to(@error_code, :mappings=) end end
-14813321 0 That is because the lat
and lng
are sub keys of each item in the array:
"geometry" : { "location" : { "lat" : -33.8698080, "lng" : 151.1971550 } }
Thus you must retreive the full path:
location.latitude = [[dico valueForKeyPath:@"geometry.location.lat"] doubleValue]; location.longitude = [[dico valueForKeyPath:@"geometry.location.lng"] doubleValue];
-8616981 0 Elegant and efficient way to put incoming serial data into structures Suppose we have incoming values representing table of known size like this:
- a b c x 06 07 08 y 10 11 12 z 14 15 16
but values are arriving from stream/iterator or another serial form, in up-to-down, left-to-right order:
- a b c x 06 07 08 y 10 11 12 z 14 15 16
Suppose that data arrives from some provider like newVal = provider.getNext()
and we can't go in reverse direction.
What is the most elegant and efficient (preffer object oriented) way to put incoming data in three structures:
top : 0=>a 1=>b 2=>c left: 0=>x 1=>y 2=>z data: 0,0=>06 1,0=>07 2,0=>08 0,1=>10 1,1=>11 2,1=>12 0,2=>10 1,2=>11 2,2=>12
Would it be better to use some switches/delegates or just buffer all data and extract parts wich we need in loops (assume that every value has the same type, let's say integer) ?
Assume that we don't need collect data in proper structure in real time (whole data can be buffered, but I look for efficient solution).
Real world data in this problem is a triple 'maps', each with size about 500x500 readed from .xls file in java poi extension if it matters.
-18072922 0What about using
if(ddlCountry.SelectedIndex != 0)
-7305324 0 This is very slow & incorrect way to create string from seq of characters. The main problem, that changes aren't propagated - ref creates new reference to existing string, but after it exits from function, reference is destroyed.
The correct way to do this is:
(apply str seq)
for example,
user=> (apply str [\1 \2 \3 \4]) "1234"
If you want to make it more effective, then you can use Java's StringBuilder to collect all data in string. (Strings in Java are also immutable)
-37745709 0X509EncodedKeySpec(key)
or PKCS8EncodedKeySpec(key)
constructors take private/public keys in encoded format. Unencoded key bytes can be converted this way:
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec("secp192r1"); ECPrivateKeySpec ecPrivateKeySpec = new ECPrivateKeySpec(new BigInteger(1, privateKeyBytes), spec); ECNamedCurveSpec params = new ECNamedCurveSpec("secp192r1", spec.getCurve(), spec.getG(), spec.getN()); java.security.spec.ECPoint w = new java.security.spec.ECPoint(new BigInteger(1, Arrays.copyOfRange(publicKeyBytes, 0, 24)), new BigInteger(1, Arrays.copyOfRange(publicKeyBytes, 24, 48))); PublicKey publicKey = factory.generatePublic(new java.security.spec.ECPublicKeySpec(w, params));
-27636828 0 How to make a light turn off at a certain time of day I'm currently making an exploration game and using a dynamic time of day changer for day and night. I wanted to know how to turn off the player's flashlight at noon of the day. The script for the TOD setting:
var slider: float; var slider2: float; var Hour: float; private var Tod: float; var sun: Light; var speed = 50; var NightFogColor: Color; var DuskFogColor: Color; var MorningFogColor: Color; var MiddayFogColor: Color; var NightAmbientLight: Color; var DuskAmbientLight: Color; var MorningAmbientLight: Color; var MiddayAmbientLight: Color; var NightTint: Color; var DuskTint: Color; var MorningTint: Color; var MiddayTint: Color; var SkyBoxMaterial1: Material; var SkyBoxMaterial2: Material; var SunNight: Color; var SunDay: Color; //THIS WAS ADDED IN TUTORIAL NUMBER 24. It allows for changing the color that reflects of a water object. //Uncheck IncludeWater if you are not interested in using this. var Water: GameObject; var IncludeWater = false; var WaterNight: Color; var WaterDay: Color; function OnGUI() { if (slider >= 1.0) { slider = 0; } slider = GUI.HorizontalSlider(Rect(20, 20, 200, 30), slider, 0, 1.0); Hour = slider * 24; Tod = slider2 * 24; sun.transform.localEulerAngles = Vector3((slider * 360) - 90, 0, 0); slider = slider + Time.deltaTime / speed; sun.color = Color.Lerp(SunNight, SunDay, slider * 2); //THIS WAS ADDED IN TUTORIAL NUMBER 24. It allows for changing the color that reflects of a water object. //Uncheck IncludeWater if you are not interested in using this. if (IncludeWater == true) { Water.renderer.material.SetColor("_horizonColor", Color.Lerp(WaterNight, WaterDay, slider2 * 2 - 0.2)); } if (slider < 0.5) { slider2 = slider; } if (slider > 0.5) { slider2 = (1 - slider); } sun.intensity = (slider2 - 0.2) * 1.7; if (Tod < 4) { //it is Night RenderSettings.skybox = SkyBoxMaterial1; RenderSettings.skybox.SetFloat("_Blend", 0); SkyBoxMaterial1.SetColor("_Tint", NightTint); RenderSettings.ambientLight = NightAmbientLight; RenderSettings.fogColor = NightFogColor; } if (Tod > 4 && Tod < 6) { RenderSettings.skybox = SkyBoxMaterial1; RenderSettings.skybox.SetFloat("_Blend", 0); RenderSettings.skybox.SetFloat("_Blend", (Tod / 2) - 2); SkyBoxMaterial1.SetColor("_Tint", Color.Lerp(NightTint, DuskTint, (Tod / 2) - 2)); RenderSettings.ambientLight = Color.Lerp(NightAmbientLight, DuskAmbientLight, (Tod / 2) - 2); RenderSettings.fogColor = Color.Lerp(NightFogColor, DuskFogColor, (Tod / 2) - 2); //it is Dusk } if (Tod > 6 && Tod < 8) { RenderSettings.skybox = SkyBoxMaterial2; RenderSettings.skybox.SetFloat("_Blend", 0); RenderSettings.skybox.SetFloat("_Blend", (Tod / 2) - 3); SkyBoxMaterial2.SetColor("_Tint", Color.Lerp(DuskTint, MorningTint, (Tod / 2) - 3)); RenderSettings.ambientLight = Color.Lerp(DuskAmbientLight, MorningAmbientLight, (Tod / 2) - 3); RenderSettings.fogColor = Color.Lerp(DuskFogColor, MorningFogColor, (Tod / 2) - 3); //it is Morning } if (Tod > 8 && Tod < 10) { RenderSettings.ambientLight = MiddayAmbientLight; RenderSettings.skybox = SkyBoxMaterial2; RenderSettings.skybox.SetFloat("_Blend", 1); SkyBoxMaterial2.SetColor("_Tint", Color.Lerp(MorningTint, MiddayTint, (Tod / 2) - 4)); RenderSettings.ambientLight = Color.Lerp(MorningAmbientLight, MiddayAmbientLight, (Tod / 2) - 4); RenderSettings.fogColor = Color.Lerp(MorningFogColor, MiddayFogColor, (Tod / 2) - 4); //it is getting Midday } }
Thank you!
-29380084 0 CSS SlideIn animation without setting heightI'm wanting to replicate the jQuery slideIn and slideOut, with CSS.
ul { background-color:yellow; transform-origin: top; transition: transform .5s; } .slider { transform: scaleY(0); }
The .slider
class will force the UL element to resize. However my method does not account for the height. I want the height to resize to 0 so the button in my example, would move up.
Here is a JSBIN: http://jsbin.com/zoqiciwicu/1/edit
Is this even possible through CSS? I do not have a set height to use.
-19893162 0Passing built-in types like int, char by pointer does not result in better performance results.
Using const keyword passing-by-value does not matter since original value won't be changed.
-18183933 0No, there should be no more issues than when upgrading to a new MySQL version.
See How can I upgrade from MySQL to MariaDB?
-33950981 0 Finding duplicate documentsI have some documents whose ids are randomly generated. The issue here is I need to find the duplicates amongst these documents. I have three fields which should not be identical for two documents. So how to check for duplicates based on multiple fields?
Sample documents
document 1 = { "process" : "business", "processId" : 5433321, "country" : "US" } document 2 = { "process" : "operations", "processId" : 334233, "country" : "UK" } document 3 = { "process" : "business", "processId" : 5433321, "country" : "US" }
Here as you can see, document 1 and document 3 are the same, but they are having different Ids in my database,so exist as separate documents. So on run I need to find the above as duplicates and if possible keep only one.
-36719260 0I recommend to read the Managing hierarchical data in mysql article.
Briefly,
CREATE TABLE category( category_id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(20) NOT NULL, parent INT DEFAULT NULL ); INSERT INTO category VALUES(1,'ELECTRONICS',NULL),(2,'TELEVISIONS',1),(3,'TUBE',2), (4,'LCD',2),(5,'PLASMA',2),(6,'PORTABLE ELECTRONICS',1),(7,'MP3 PLAYERS',1),(8,'FLASH',7), (9,'CD PLAYERS',6),(10,'2 WAY RADIOS',6); SELECT * FROM category ORDER BY category_id; +-------------+----------------------+--------+ | category_id | name | parent | +-------------+----------------------+--------+ | 1 | ELECTRONICS | NULL | | 2 | TELEVISIONS | 1 | | 3 | TUBE | 2 | | 4 | LCD | 2 | | 5 | PLASMA | 2 | | 6 | PORTABLE ELECTRONICS | 1 | | 7 | MP3 PLAYERS | 6 | | 8 | FLASH | 7 | | 9 | CD PLAYERS | 6 | | 10 | 2 WAY RADIOS | 6 | +-------------+----------------------+--------+
The query retrieve all your data:
SELECT t1.name AS lev1, t2.name as lev2, t3.name as lev3, t4.name as lev4 FROM category AS t1 LEFT JOIN category AS t2 ON t2.parent = t1.category_id LEFT JOIN category AS t3 ON t3.parent = t2.category_id WHERE t1.name = 'ELECTRONICS';
The retrieving only leaf names:
SELECT t1.name FROM category AS t1 LEFT JOIN category as t2 ON t1.category_id = t2.parent WHERE t2.category_id IS NULL;
The retrieving one path:
SELECT t1.name AS lev1, t2.name as lev2, t3.name as lev3, t4.name as lev4 FROM category AS t1 LEFT JOIN category AS t2 ON t2.parent = t1.category_id LEFT JOIN category AS t3 ON t3.parent = t2.category_id WHERE t1.name = 'ELECTRONICS' AND t3.name = 'FLASH';
-40706125 0 My navigate method doesn't work javafx I have program in javafx.
Its a note program and I have button switch to another scene but it doesn't work don't know why. When I click, I got a run time error, it was working well.
This is the main controller:
package notetakingapp; public class ListNotesUIController implements Initializable { @FXML private TableView<Note> tableView; @FXML private TableColumn<Note, String> titleColmun; @FXML private TableColumn<Note, String> descriptionColumn; @FXML private TextField searchNotes; @FXML private Label totalNotes; @Override public void initialize(URL url, ResourceBundle rb) { FilteredList<Note> filteredData = new FilteredList<>(data, n -> true); tableView.setItems(filteredData); totalNotes.setText("" + data.size() + " Notes"); titleColmun.setCellValueFactory(new PropertyValueFactory<>("title")); descriptionColumn.setCellValueFactory(new PropertyValueFactory<>("description")); searchNotes.setOnKeyReleased(e -> { filteredData.setPredicate(n -> { if (searchNotes.getText() == null || searchNotes.getText().isEmpty()) { return true; } return n.getTitle().contains(searchNotes.getText()) || n.getDescription().contains(searchNotes.getText()); }); }); } @FXML private void handleAddNewNoteAction(ActionEvent event) throws IOException { navigate(event, "AddEditUI.fxml"); totalNotes.setText("" + data.size() + " Notes"); } @FXML private void handleEditNotesAction(ActionEvent event) throws IOException { tempNote = tableView.getSelectionModel().getSelectedItem(); navigate(event, "AddEditUI.fxml"); } protected static ObservableList<Note> data = FXCollections.<Note>observableArrayList( new Note("Note 1", "Description of note 41"), new Note("Note 2", "Description of note 32"), new Note("Note 3", "Description of note 23"), new Note("Note 4", "Description of note 14")); protected static Note tempNote = null; protected void navigate(Event event, String FXMLDocName) throws IOException { Parent root = FXMLLoader.load(getClass().getResource(FXMLDocName)); Scene scene = new Scene(root); NoteTakingApp.appStage.setScene(scene); } @FXML private void handleDeleteAction(ActionEvent event) { int getIndex = tableView.getSelectionModel().getSelectedIndex(); data.remove(getIndex); totalNotes.setText("" + data.size() + " Notes"); } }
This is the controller what I want to go:
package notetakingapp; public class AddEditUIController implements Initializable { @FXML private TextField noteTitle; @FXML private TextArea noteDescription; @FXML private Label noteTitleLabel; @FXML private Label noteDescriptionLabel; @Override public void initialize(URL url, ResourceBundle rb) { noteTitle.setText(tempNote.getTitle()); noteDescription.setText(tempNote.getDescription()); } @FXML private void handleCancleAction(ActionEvent event) throws IOException { navigate(event, "ListNotesUI.fxml"); } @FXML private void handleSaveAction(ActionEvent event) throws IOException { if ((noteTitle.getText().trim().isEmpty()) && noteDescription.getText().trim().isEmpty()) { noteTitleLabel.setTextFill(Color.BLUE); noteTitleLabel.setText(" * Note Title: (Required)"); noteDescriptionLabel.setTextFill(Color.BLUE); noteDescriptionLabel.setText(" * Note Description: (Required)"); } else { data.add(new Note(noteTitle.getText(), noteDescription.getText())); navigate(event, "ListNotesUI.fxml"); } } protected void navigate(Event event, String FXMLDocName) throws IOException { Parent root = FXMLLoader.load(getClass().getResource(FXMLDocName)); Scene scene = new Scene(root); NoteTakingApp.appStage.setScene(scene); } @FXML private void handleBackToNotesAction(ActionEvent event) throws IOException { navigate(event, "ListNotesUI.fxml"); } @FXML private void handleClearAction(ActionEvent event) { noteTitle.setText(""); noteDescription.setText(""); } }
and this is my start method:
static Stage appStage = new Stage(); @Override public void start(Stage stage) throws Exception { appStage = stage; Parent root = FXMLLoader.load(getClass().getResource("ListNotesUI.fxml")); Scene scene = new Scene(root); appStage.setScene(scene); appStage.setResizable(false); appStage.setTitle("P'Note-Taking Application v1.0"); appStage.show(); }
-20365265 0 SQLite Error: Cannot delete WhereListIterator`1: it has no PK I'm trying to delete records from a database using SQLite/C# in Visual Studio 2012. Whenever I attempt to delete a record I get the following error:
SQLite Error: Cannot delete WhereListIterator`1: it has no PK
I am wanting to delete records using two different methods. Either delete using only the EID, which is the primary key, or delete records where the user provides everything but the EID.
if (EID_TextBox.Text != String.Empty) { if (Roster_Enrollment.Any(x => x.EID.Equals(Int32.Parse(EID_TextBox.Text)))) { App.DBConnection.Delete(Roster_Enrollment.Where(x => x.EID.Equals(Int32.Parse(EID_TextBox.Text)))); Message_TextBlock.Text = "Enrollment deleted."; } else { Message_TextBlock.Text = "Enrollment not found."; } } else if (Roster_Enrollment.Any(x => x.CourseNo.Equals(CourseNo_TextBox.Text) && x.SectionNo.Equals(SectionNo_TextBox.Text) && x.Tno.Equals(Tno_TextBox.Text))) { App.DBConnection.Delete(Roster_Enrollment.Where(x => x.CourseNo.Equals(CourseNo_TextBox.Text) && x.SectionNo.Equals(SectionNo_TextBox.Text) && x.Tno.Equals(Tno_TextBox.Text))); } else { Message_TextBlock.Text = "Enrollment not found."; }
-18317283 0 If you're trying to get rid of blank cells in sheet 'Belmont' column C, then this should work for you:
Sub tgr() Dim rngBlanks As Range With Sheets("Belmont").Range("C1", Sheets("Belmont").Cells(Rows.Count, "C").End(xlUp)) On Error Resume Next Set rngBlanks = .SpecialCells(xlCellTypeBlanks) On Error GoTo 0 If Not rngBlanks Is Nothing Then rngBlanks.EntireRow.Delete End With Set rngBlanks = Nothing End Sub
-7136921 1 How can I create a tuple where each of the members are compared by an expression? Well, here is the thing:
I have the following Haskell code, this one:
[ (a, b, c) | c <- [1..10], b <- [1..10], a <- [1..10], a ^ 2 + b ^ 2 == c ^ 2 ]
Which will returns
[(4,3,5),(3,4,5),(8,6,10),(6,8,10)]
For those who aren't familiar with this, I'll explain:
tuple
(a,b,c), where each of these "definitions" (a,b,c) receive a list (1 up to 10) and his members are compared by the a ^ 2 + b ^ 2 == c ^ 2 ?
expression (each member).How can I do the same (one line if possible) in Python/Ruby?
P.S.: they are compared in lexicographical order.
-26793974 0In the latest version of SymPy you will not obtain an integrated result unless you make the 'r' variable positive
>>> var('r',positive=1) r >>> integrate(sqrt(r**2 - x**2), (x, -r, r)) pi*r**2/2
Notice that you get the area of a half-circle, too. Compare to
>>> Circle((x,y),r).area pi*r**2
-21003773 0 Well SOAP uses XML as its data format. Not JSON. I would imagine that the issue is that you are getting XML back from the service and the "special characters" you're referring to are coming from that.
-18018267 0If this is SQL Server, use CONVERT:
SELECT CONVERT(varchar(10), DATEADD(Month,1,GETDATE()), 120)
If you need the day before that date, just use DATEADD
again:
SELECT CONVERT(varchar(10), DATEADD(Day, -1, DATEADD(Month,1,GETDATE())), 120)
-27305831 0 I know this is a late answer, but if you can always use sanitize-html It's written for node, but pretty sure you could run browserify against the library (or your code for that matter).
Note, it uses lodash, so if you are already using it, then you may want to adjust the package.
This example is more than you're looking for... I use this library in order to cleanup input code, converting to markdown for storage in the db from here, I re-hydrate via marked.
// convert/html-to-filtered-markdown.js 'use strict'; var sanitize = require('sanitize-html') //https://www.npmjs.org/package/sanitize-html ,toMarkdown = require('to-markdown').toMarkdown ; module.exports = function convertHtmlToFilteredMarkdown(input, options) { if (!input) return ''; options = options || {}; //basic cleanup, normalize line endings, normalize/reduce whitespace and extra line endings var response = (input || '').toString().trim() .replace(/(\r\n|\r|\n)/g, '\n') //normalize line endings .replace(/“/g, '"') //remove fancy quotes .replace(/”/g, '"') //remove fancy quotes .replace(/‘/g, '\'') //remove fancy quotes .replace(/’/g, '\'') //remove fancy quotes ; //sanitize html input response = sanitize(response, { //don't allow table elements allowedTags: [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'p', 'a', 'ul', 'ol', 'nl', 'li', 'b', 'i', 'strong', 'em', 'strike', 'code', 'hr', 'br', 'div', 'table', 'thead', 'caption', 'tbody', 'tr', 'th', 'td', 'pre' ], //make orderd lists transformTags: { 'ol': 'ul' } }).replace(/\r\n|\r|\n/g,'\n') //normalize line endings; if (!options.tables) { response = response.replace(/[\s\n]*\<(\/?)(table|thead|tbody|tr|th|td)\>[\s\n]*/g, '\n\n') //replace divs/tables blocks as paragraphs } //cleanup input further response = response .replace(/[\s\n]*\<(\/?)(div|p)\>[\s\n]*/g, '\n\n') //divs and p's to simple multi-line expressions .replace(/\>#/g, '\n\n#') //cleanup #'s' after closing tag, ex: <a>...</a>\n\n# will be reduced via sanitizer .replace(/\\s+\</,'<') //remove space before a tag open .replace(/\>\s+\n?/,'>\n') //remove space after a tag close .replace(/\&?nbsp\;?/g,' ') //revert nbsp to space .replace(/\<\h[12]/g,'<h3').replace(/\<\/\h[12]/g,'</h3') //reduce h1/h2 to h3 ; //convert response to markdown response = toMarkdown(response); //normalize line endings response = response .replace(/(?:^|\n)##?[\b\s]/g,'\n### ') //reduce h1 and h2 to h3 .replace(/(\r\n|\r|\n)/g, '\n') //normalize line endings .trim() return response + '\n'; }
-2902113 0 Configurable Values in Enum I often use this design in my code to maintain configurable values. Consider this code:
public enum Options { REGEX_STRING("Some Regex"), REGEX_PATTERN(Pattern.compile(REGEX_STRING.getString()), false), THREAD_COUNT(2), OPTIONS_PATH("options.config", false), DEBUG(true), ALWAYS_SAVE_OPTIONS(true), THREAD_WAIT_MILLIS(1000); Object value; boolean saveValue = true; private Options(Object value) { this.value = value; } private Options(Object value, boolean saveValue) { this.value = value; this.saveValue = saveValue; } public void setValue(Object value) { this.value = value; } public Object getValue() { return value; } public String getString() { return value.toString(); } public boolean getBoolean() { Boolean booleanValue = (value instanceof Boolean) ? (Boolean) value : null; if (value == null) { try { booleanValue = Boolean.valueOf(value.toString()); } catch (Throwable t) { } } // We want a NullPointerException here return booleanValue.booleanValue(); } public int getInteger() { Integer integerValue = (value instanceof Number) ? ((Number) value).intValue() : null; if (integerValue == null) { try { integerValue = Integer.valueOf(value.toString()); } catch (Throwable t) { } } return integerValue.intValue(); } public float getFloat() { Float floatValue = (value instanceof Number) ? ((Number) value).floatValue() : null; if (floatValue == null) { try { floatValue = Float.valueOf(value.toString()); } catch (Throwable t) { } } return floatValue.floatValue(); } public static void saveToFile(String path) throws IOException { FileWriter fw = new FileWriter(path); Properties properties = new Properties(); for (Options option : Options.values()) { if (option.saveValue) { properties.setProperty(option.name(), option.getString()); } } if (DEBUG.getBoolean()) { properties.list(System.out); } properties.store(fw, null); } public static void loadFromFile(String path) throws IOException { FileReader fr = new FileReader(path); Properties properties = new Properties(); properties.load(fr); if (DEBUG.getBoolean()) { properties.list(System.out); } Object value = null; for (Options option : Options.values()) { if (option.saveValue) { Class<?> clazz = option.value.getClass(); try { if (String.class.equals(clazz)) { value = properties.getProperty(option.name()); } else { value = clazz.getConstructor(String.class).newInstance(properties.getProperty(option.name())); } } catch (NoSuchMethodException ex) { Debug.log(ex); } catch (InstantiationException ex) { Debug.log(ex); } catch (IllegalAccessException ex) { Debug.log(ex); } catch (IllegalArgumentException ex) { Debug.log(ex); } catch (InvocationTargetException ex) { Debug.log(ex); } if (value != null) { option.setValue(value); } } } } }
This way, I can save and retrieve values from files easily. The problem is that I don't want to repeat this code everywhere. Like as we know, enums can't be extended; so wherever I use this, I have to put all these methods there. I want only to declare the values and that if they should be persisted. No method definitions each time; any ideas?
-19785234 0 GeoRedirection script not working properly
I am developing a country specific website, for which I thought to have a geo redirection installed at my php server. The basic approach is to record the incoming IP address in $_SERVER['REMOTE_ADDR']
and then use a geolocation database to convert that into country information. I did go with Maxmind geolocation service. The final script that I came through with some google power and experiment power was as follows
<?php getCountry($_SERVER['REMOTE_ADDR']); $ip=$_SERVER['REMOTE_ADDR']; function getCountry($ipAddress) { // get the country of the IP from the MAXMIND $country=""; // include functions include("geoip.inc.php"); // read GeoIP database $handle = geoip_open("GeoIP.dat", GEOIP_STANDARD); // map IP to country $country = geoip_country_name_by_addr($handle, $ipAddress); // close database handler geoip_close($handle); if ($country==""|| empty($country)) { $country="Unknown"; } return $country; } $country_code = geoip_country_code_by_addr($gi, "$ip"); // Country name is not used so commented // Get Country Name based on source IP //$country = geoip_country_name_by_addr($gi, "$ip"); geoip_close($gi); switch($country_code) { case "US": header("Location: http://site1.com "); break; case "CA": header("Location: http://site2.com "); break; case "GB": header("Location: http://site3.com "); break; default: header("Location: http://site.com "); } ?>
I downloaded the geoip.inc from https://www.maxmind.com/download/geoip/api/php-20120410/geoip.inc
and GeoIP.dat from http://dev.maxmind.com/geoip/legacy/geolite/
BUT Something somewhere IS going wrong. The code doesn't execute, with a few errors each time. Have tried a lot many permutations of silly mistakes, but nothing worked. Calling the URL brings up the file geoip.inc's code on the URL.
Tried to find any similar questions on SO, but couldn't. A detailed help would be appreciated. Thanks in advance.
-264310 0IBM has CELM. Check out this link: http://www.research.ibm.com/journal/rd/513/labbi.pdf
-5610550 0Search the Sqlalchemy documentation for enabling the logging of the generatef d SQL statements and Sql responses. This will usually give you all related information for further debugging.
-20758140 0Why not use a vector
of Player
object pointers?
std::vector<Player*> vec;
Then, when you want to allocate a new player, do:
vec.push_back(new Player);
Here, the problem with your code may be that there is a chance of any Player
stored in an array getting over written. But, using vector, you can use const iterators
and hence, make sure that they are not getting changed when you don't want them to.
Also, you don't have to worry about allocating a constant size.
Also, if your Player object contains any member pointers, make sure that you don't pass any Player object by value or do assignment using them. If that is the case, you might want to write your own copy constructor and assignment operator so that shallow copy does not occur.
-40977930 0As furas suggested in his comment, you could store the counter in the session or perhaps a database. You could also store it as a hidden input field on the form.
In your template:
<input type="hidden" name="counter" value="{{ counter }}">
In your view:
counter = request.form.get('counter', type=int) or 0 return render_template('accounts/test/medium.html', word=word, output=scribble_normalized, counter=counter+1)
-9098041 0 Fancybox not working with jQuery Masonry in pages loaded through infiniteScroll I have three pages in my portfolio website built on the Masonry plugin (http://www. 4pixels.co.uk/). On the first page fancybox works perfectly for a few of the images.
But when I use infiniteScroll to load page 2 at the bottom of the first page, the fancy box links stop working and just load the thick box image into a new page.
If I load page 2 (http://www.4pixels.co.uk/index2.html) directly into the browser it worked fine (with all the css/js). I've since stripped out the js and css from this page as it loads them from page 1, but it makes no difference and fancy box still doesn't work (The image to try it with is the Responsive screens for Winston Ellis website)
All the best Andy
I have tried
$(document).ready(function() { $("#tumblelog").on("focusin", function(){ $("a.example2").fancybox({ 'overlayShow' : true, 'transitionIn' : 'elastic', 'transitionOut' : 'elastic' }); }); });
but still not working. I see your example is working so I'll have to pull it apart as I can't see were I'm going wrong..
-40464837 0 How to use addFormatters in WebMvcConfigurerAdapter@Configuration @EnableWebMvc // <mvc:annotation-driven /> public class WebApplicationConfig extends WebMvcConfigurerAdapter { @Override public void addFormatters(FormatterRegistry registry) { registry.addConverter(new EmailConverter()); } }
I add a Converter
in FormatterRegistry
,but I don't know how to use it, can someone help me out?
^\/user\/(?!login\b)(.*)
This is the corrected regex after escaping forward slashes
-24441734 0please see fiddle
http://fiddle.jshell.net/RrD74/
html:
<select id="mySelect"> <option name="xxx" value="1">text opt 1</option> <option name="xxx" value="2">text opt 2</option> <option name="xxx" value="3">text opt 3</option> </select>
js:
$(function () { $("#mySelect").change(function () { alert($("#mySelect option:selected").text()); }); });
-8365691 0 can anyone think of why using this particular class in a design time data source will break all design time bindings? I generated this class using SQLMetal.exe. It is very bindable at runtime, but if I use this class at design time, all of my design time blend bindings are busted.
I am using the MVVM-Light framework and I am building an app for WP7.
If I extract an interface for this class, and create a simple POCO that implements this interface and I use my simple poco in my design time data source, all of the bindings come alive.
Here is the class that was generated by SQLMetal.exe.
[Table(Name="InspectionGroup")] public partial class InspectionGroup : INotifyPropertyChanging, INotifyPropertyChanged, IInspectionGroup { private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty); private int _InspectionGroupId; private string _GroupName; private System.DateTime _DateCreated; private EntitySet<InspectionHeader> _InspectionHeaders; private EntitySet<InspectionPoint> _InspectionPoints; #region Extensibility Method Definitions partial void OnLoaded(); partial void OnValidate(System.Data.Linq.ChangeAction action); partial void OnCreated(); partial void OnInspectionGroupIdChanging(int value); partial void OnInspectionGroupIdChanged(); partial void OnGroupNameChanging(string value); partial void OnGroupNameChanged(); partial void OnDateCreatedChanging(System.DateTime value); partial void OnDateCreatedChanged(); #endregion public InspectionGroup() { this._InspectionHeaders = new EntitySet<InspectionHeader>(new Action<InspectionHeader>(this.attach_InspectionHeaders), new Action<InspectionHeader>(this.detach_InspectionHeaders)); this._InspectionPoints = new EntitySet<InspectionPoint>(new Action<InspectionPoint>(this.attach_InspectionPoints), new Action<InspectionPoint>(this.detach_InspectionPoints)); OnCreated(); } [Column(Storage = "_InspectionGroupId", AutoSync = AutoSync.OnInsert, DbType = "Int NOT NULL IDENTITY", IsPrimaryKey = true, IsDbGenerated = true)] public int InspectionGroupId { get { return this._InspectionGroupId; } set { if ((this._InspectionGroupId != value)) { this.OnInspectionGroupIdChanging(value); this.SendPropertyChanging(); this._InspectionGroupId = value; this.SendPropertyChanged("InspectionGroupId"); this.OnInspectionGroupIdChanged(); } } } [Column(Storage = "_GroupName", DbType = "NVarChar(100) NOT NULL", CanBeNull = false)] public string GroupName { get { return this._GroupName; } set { if ((this._GroupName != value)) { this.OnGroupNameChanging(value); this.SendPropertyChanging(); this._GroupName = value; this.SendPropertyChanged("GroupName"); this.OnGroupNameChanged(); } } } [Column(Storage = "_DateCreated", DbType = "DateTime NOT NULL")] public System.DateTime DateCreated { get { return this._DateCreated; } set { if ((this._DateCreated != value)) { this.OnDateCreatedChanging(value); this.SendPropertyChanging(); this._DateCreated = value; this.SendPropertyChanged("DateCreated"); this.OnDateCreatedChanged(); } } } [Association(Name = "FK_InspectionHeader_InspectionGroup", Storage = "_InspectionHeaders", ThisKey = "InspectionGroupId", OtherKey = "InspectionGroupId", DeleteRule = "CASCADE")] public EntitySet<InspectionHeader> InspectionHeaders { get { return this._InspectionHeaders; } set { this._InspectionHeaders.Assign(value); } } [Association(Name = "FK_InspectionPoint_InspectionGroup", Storage = "_InspectionPoints", ThisKey = "InspectionGroupId", OtherKey = "InspectionGroupId", DeleteRule = "CASCADE")] public EntitySet<InspectionPoint> InspectionPoints { get { return this._InspectionPoints; } set { this._InspectionPoints.Assign(value); } } public event PropertyChangingEventHandler PropertyChanging; public event PropertyChangedEventHandler PropertyChanged; protected virtual void SendPropertyChanging() { if ((this.PropertyChanging != null)) { this.PropertyChanging(this, emptyChangingEventArgs); } } protected virtual void SendPropertyChanged(String propertyName) { if ((this.PropertyChanged != null)) { this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } private void attach_InspectionHeaders(InspectionHeader entity) { this.SendPropertyChanging(); entity.InspectionGroup = this; } private void detach_InspectionHeaders(InspectionHeader entity) { this.SendPropertyChanging(); entity.InspectionGroup = null; } private void attach_InspectionPoints(InspectionPoint entity) { this.SendPropertyChanging(); entity.InspectionGroup = this; } private void detach_InspectionPoints(InspectionPoint entity) { this.SendPropertyChanging(); entity.InspectionGroup = null; } }
-35541123 0 You should be able to use Dijstra's algorithm, where the nodes are "between" the cells of the matrix and the connections are implied by the weights of the cells.
For a detailed answer, please refer to this question: Javascript: Pathfinding in a (50000*50000 grid) 2d array?
-1785252 0As others have said it is likely that the displayBox variable is null.
The best way to deal with this is at compile time... if you get into the following habit you will catch that sort of mistake early:
public class TestFrame extends JFrame { private final JButton aButton; private JButton bButton; public TestFrame() { // fails to compile since aButton is not instantiated // aButton = new JButton("A"); } public init() { add(aButton); add(bButton); aButton.addActionListener(....); // crash at runtime since bButton is null bButton.addActionListener(....); } }
by declaring variables as "final" the compiler forces you to give them a value. Since the buttons (and other GUI items) are not likely to change you should be able to make them all final. Once you have that you will have the com;iler help you out to avoid this sort of thing.
-2435643 0 find explorer.exe hwndI want to find & enumerate explorer.exe.
Found 'EnumChildWindows' API call but how to 'get' explorer.exe hwnd ???
-20281787 0The <style> ... </style>
belongs in the <head></head>
, not in <body>
tag
First, find the hash you want to your submodule to reference. then run
~/supery/subby $ git co hashpointerhere ~/supery/subby $ cd ../ ~/supery $ git add subby ~/supery $ git commit -m 'updated subby reference'
that has worked for me to get my submodule to the correct hash reference and continue on with my work without getting any further conflicts.
-361393 0You could use the bitblt routines to merge an image to a common canvas, then save the image again.
-6290702 0Place this in Button IBAction method
-39022161 0 Ionic avoid gray-out items on hover...[mCurrentView removeFromSuperview];
[self.view addSubView:mNewView];
I have the next list of carss whose header is clickable so it can be toggled on and off. Nevertheless, whenever I click on one of them, it turns gray. I would like to change this behavior and keep color unchanged.
<div class="list"> <div ng-repeat="event in searchResultEvents"> <div class="card"> <div class="item item-avatar item-icon-right" ng-click="toggleEvent(event)"> <img src={{event.icon}}> <i class="icon" style="font-size: 18px;" ng-class="isEventShown(event) ? 'ion-chevron-up' : 'ion-chevron-down'" ng-style="{ background: backgroundForEvent(event), color: 'grey' }"></i> <h2><b>{{event.title}}</b></h2> <p><span>{{event.dayOfWeek}} {{event.dateTime.getDate()}}</span> - <span style="color:forestgreen">{{event.dateTime.toTimeString().substr(0,5)}}h</span></p> </div> <div class="item item-body" ng-hide="!isEventShown(event)"> <div> <p ng-bind-html="event.description | hrefToJS"></p> </div> <div> <br /> <div> <i class="icon ion-map balanced" style="font-size: 25px;"></i> <p ng-bind-html="event.place | hrefToJS" style="display:inline"></p>
I have tried this:
Changing background color of Ionic list item on hover in CSS
But no luck. Perhaps this is not the CSS or I am not putting it where it belongs. I have tried adding it to ionic.app.scss (I am using SCSS instead of plain CSS).
I have made some SCSS changes on that file before and it seemed to work... what am I doing wrong now?.
Thanks in advance
-33669754 0You should try to use a UIImagePickerController
like this
@IBAction func takePhoto(sender: UIButton) { let picker = UIImagePickerController() picker.delegate = self; picker.allowsEditing = true; picker.sourceType = .PhotoLibrary; self.presentViewController(picker animated:true completion:nil); }
Then you can get the image in imagePickerController(_:didFinishPickingMediaWithInfo:)
method from UIImagePickerControllerDelegate
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { let chosenImage = info[UIImagePickerControllerEditedImage] as! UIImage UploadImage(chosenImage) picker.dismissViewControllerAnimated(true, completion: nil); } func imagePickerControllerDidCancel(picker: UIImagePickerController) { picker.dismissViewControllerAnimated(true, completion: nil); }
Finally you upload the image. Example using HTTP POST
Check this answer
function UploadImage(image : UIImage) { var imageData = UIImagePNGRepresentation(image) if imageData == nil { print("image not valid") return } // Upload .... }
Note This answer is directly written in the reply, please change any invalid code.
-7736308 0This page solve my problem but I have to make slight change in initial one:
protected void onSaveInstanceState(Bundle outState) { webView.saveState(outState); }
This portion has a slight problem for me this. On the second orientation change the application terminated with null pointer
using this it worked for me:
@Override protected void onSaveInstanceState(Bundle outState ){ ((WebView) findViewById(R.id.webview)).saveState(outState); }
-6255251 0 Javascript error - unexpected identifier I have PHP code that tries to output JavaScript and I do something like this:
trailhead_name = <?php echo $objkey->trailhead_name ?> + "";
And I get the unexpected identifier error in my JS.
-39217790 0Yes, you can using the flexible box model's order
css property. Be aware that the parent element must have display:flex
set
ul { display: -webkit-box; display: -moz-box; display: -ms-flexbox; display: -moz-flex; display: -webkit-flex; display: flex; -moz-flex-flow: wrap; -webkit-flex-flow: wrap; flex-flow: wrap; } ul li { width: 100% } ul li:nth-of-type(1) { order: 2; } ul li:nth-of-type(2) { order: 3; } ul li:nth-of-type(3) { order: 4; } ul li:nth-of-type(4) { order: 5; } ul li:nth-of-type(5) { order: 1; }
<ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul>
Also be aware that not all browsers support the flexible box model as outlined here...http://caniuse.com/#feat=flexbox
However, there are quite a few polyfills out there you can use to bring support for older browsers if you need to support older browsers
-15028375 0DS_RECURSE
doesn't exist. It was a flag in a prerelease version of Windows 95 that was removed before RTM. All the docs that refer to it talk about "Don't use it", which is now very easy to do because you can't use something that doesn't exist.
The assembly bits are transfered into the database, the original DLL location is irelevant. The idea is that an SQL loaded assembly should continue to work after a backup and restore on a different machine, it has to be entirely contained inside the database.
-22982879 0Go to People - Permisions, find a module "User", find a line "View user profiles" and set permissions there for your user roles.
-22285610 0 Trouble making css :last-child work for meObviously I must be doing something wrong, but I can't figure out what's wrong with this, it's driving me crazy.
The selector I'd LIKE to use is: .menu ul li:last-child > a
The 'unique selector' that firefox gives me is .menu > ul:nth-child(1) > li:nth-child(5) > a:nth-child(1)
the HTML is:
<div class='menu'> <ul><li><a href=''>Home</a></li> <li><a href='1'>Link 1</a></li> <li><a href='2'>Link 2</a></li> <li><a href='3'>Link 3</a></li> <li><a href='4'>Link 4</a></li> <ul> </div>
How is li:last-child > a
not selecting 'Link 4'? I am really quite confused, so thanks in advance for the upcoming lesson.
You could also use a QStyle derived class, although this might be over the top if you really only want these round buttons and not tons of widgets with custom styling.
-31285536 0SELECT
using a correlated sub-query:
select t1.PROD_NO, t1.PROD_CAT (select max(t2.PROD_DESCRIPTION) from tablename t2 where t2.PROD_NO = t1.PROD_NO and t2.PROD_DESCRIPTION <> 'N/A' and t2.PROD_DESCRIPTION <> ''), from tablename t1
JOIN
version, with a GROUP BY
to find 'not in warehouse' or 'in warehouse':
select t1.PROD_NO, t1.PROD_CAT, t2.PROD_DESCRIPTION from tablename t1 LEFT JOIN (select PROD_NO, max(PROD_DESCRIPTION) from tablename where PROD_DESCRIPTION <> 'N/A' and PROD_DESCRIPTION <> '' group by PROD_NO) t2 ON t1.PROD_NO = t2.PROD_NO
If a prod_no has both 'in warehouse' and 'not in warehouse', the MAX
will return 'not in warehouse' as value. If you want 'in warehouse' instead, switch to min(t2.PROD_DESCRIPTION)
in the sub-select.
Setting a bound property clears the data binding (for one way binding). I have never seen any Microsoft documentation on this but I have experienced it many times in my code and have come to accept it.
It makes sense if you think about it, since changing the property value means the property no longer reflects the value in the bound data.
-26536986 0p = 0.0000000000000000000001 s = str(p) print(format(p, "." + s.split("e")[-1][1:]+"f")) if "e" in s else print(p)
-25618765 0 I got this working in a Storyboard by checking Show Toolbar in the Navigation Controller. Then dragging Bar Button Items to the greyed out toolbar area now shown at the bottom of the Table View Controller. Then wiring the Bar Button Items up to methods Navigation Controller.
-24844161 0The unspecified behavior is not for the programmer to use (for the contrary if, for the programmer to known what it need to look with care and avoid), the unspecified behavior, as all the others: undefined, implementation defined, etc... are for the compiler writer to take advantage of (for example Order of evaluation of subexpressions have unspecified behavior, for that you should not pass any subexpression with side-effects in the evaluations, and assuming that you take care of this, the compiler reorder the evaluation of subexpression as more efficient it can, some subexpression can contain same calculation that can be reused and many other optimization can take advantage of the knowledge that can do evaluated in the best order it can find.
-13188773 0Here is what I ended up doing based on Wienke's recommendation. I added 3 prototype cells to my storyboard named Cell,Cell2,Cell3.
Relevant code:
static NSString *CellIdentifier = @"Cell"; static NSString *CellIdentifier2 = @"Cell2"; static NSString *CellIdentifier3 = @"Cell3"; UITableViewCell *cell; if (indexPath.section == 0 && indexPath.row == 0) { cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; } else if (indexPath.section == 0 && indexPath.row == 1) { cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier2 forIndexPath:indexPath]; } else if (indexPath.section == 1) { cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier3 forIndexPath:indexPath]; }
I also added this to check my dynamic cells and remove any lingering subviews that could be hanging around before adding the new subview.
if ([cell.contentView subviews]){ for (UIView *subview in [cell.contentView subviews]) { [subview removeFromSuperview]; } }
-14338103 0 You can create a simple authorization attribute filter (extend the AuthorizeAttribute class) and use it for your access control. Then try something like this:
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { if (filterContext.HttpContext.Request.IsAjaxRequest() || string.Compare("GET", filterContext.HttpContext.Request.HttpMethod, true) != 0) { // Returns 403. filterContext.Result = new HttpStatusCodeResult((int)HttpStatusCode.Forbidden); } else { // Returns 401. filterContext.Result = new HttpUnauthorizedResult(); } }
The effect is that, POST and AJAX requests will always receive a 403 response which makes it easier for you to handle your ajax submits in javascript. As for the non-ajax posts, it doesn't really matter what the response is because your user shouldn't have got his hands on the submit form in the first place :)
As for the other requests, the method returns 401 that the formsAuthentiction module will pick up and then redirect your response to the login page.
-14011724 0 View location outside the screenI'm doing a cards game with 4 players where the backs of the cards of 3 of the players that the phone plays as are present on the screen with part of them outside. I've succeeded in doing this using the margins for the cards views for the top and left players but having a problem with the player on the right where setting the left margin for the card view just resizes it and prevents it from going off screen.
here is a screenshot: Screenshot of the game
I think I'm missing something here...
Thanks!
-36908911 0You could bootstrap asynchronously after your request(s) complete(s). Here is a sample:
var app = platform(BROWSER_PROVIDERS) .application([BROWSER_APP_PROVIDERS, appProviders]); var service = app.injector.get(CompaniesService); service.executeSomething().flatMap((data) => { var companiesProvider = new Provider('data', { useValue: data }); return app.bootstrap(appComponentType, [ companiesProvider ]); }).toPromise();
See this question for more details:
and the corresponding plunkr: https://plnkr.co/edit/ooMNzEw2ptWrumwAX5zP?p=preview.
-7198865 0$("#my_image").attr("src","http://www.myimagepath.com/image.jpg");
-25931066 0 I think EMD is good solution to resolve cross-bin problem compares with bin to bin method. However, as some mentions, EMD is very long time. Could you suggest to me some other approach for cross-bin?
-13494229 0 Dynamically updating a DataGrid using a background workerI have an ObservableCollection
of custom class that holds a string and an int:
public class SearchFile { public string path { set; get; } public int occurrences { set; get; } }
I want to display the collection in a dataGrid
. The collection has methods that notify whenever it has been updated, so so far it's only a matter of linking it to the DataGrid.ItemsSource
(correct?). Here's the grid XAML (with dataGrid1.ItemsSource = files;
in the C# codebehind):
<DataGrid AutoGenerateColumns="False" Height="260" Name="dataGrid1" VerticalAlignment="Stretch" IsReadOnly="True" ItemsSource="{Binding}" > <DataGrid.Columns> <DataGridTextColumn Header="path" Binding="{Binding path}" /> <DataGridTextColumn Header="#" Binding="{Binding occurrences}" /> </DataGrid.Columns> </DataGrid>
Now things are more complicated. I first want to display the path
s with the default values of occurrence
of zero. Then, I want to go through every SearchFile
and update it with a calculated value of occurrence
. Here's the helper function:
public static void AddOccurrences(this ObservableCollection<SearchFile> collection, string path, int occurrences) { for(int i = 0; i < collection.Count; i++) { if(collection[i].path == path) { collection[i].occurrences = occurrences; break; } } }
And here's the placeholder worker function:
public static bool searchFile(string path, out int occurences) { Thread.Sleep(1000); occurences = 1; return true; //for other things; ignore here }
I'm using a BackgroundWorker
as the background thread. Here's how:
private void worker_DoWork(object sender, DoWorkEventArgs e) { List<string> allFiles = new List<string>(); //allFiles = some basic directory searching this.Dispatcher.Invoke(new Action(delegate { searchProgressBar.Maximum = allFiles.Count; files.Clear(); // remove the previous file list to build new one from scratch })); /* Create a new list of files with the default occurrences value. */ foreach(var file in allFiles) { SearchFile sf = new SearchFile() { path=file, occurrences=0 }; this.Dispatcher.Invoke(new Action(delegate { files.Add(sf); })); } /* Add the occurrences. */ foreach(var file in allFiles) { ++progress; // advance the progress bar this.Dispatcher.Invoke(new Action(delegate { searchProgressBar.Value = progress; })); int occurences; bool result = FileSearcher.searchFile(file, out occurences); files.AddOccurrences(file, occurences); } }
Now when I run it, there are two problems. First, updating the progress bar's value throws the The calling thread cannot access this object because a different thread owns it.
exception. Why? It's in a dispatcher, so it should work just fine. And second, the foreach
loop breaks on the bool result =...
line. I commenting it out and tried setting int occurences = 1
, and then the loop goes around, but there's something weird going on: whenever I call the method, it's either all zeroes, all ones, or a between state, with onez beginning after a seemingly random number of zeroes).
Why's that?
-29848915 0 adding tables to a list in R via loopI am reading HTML tables, and can do that fine, but I am collecting tables from multiple years. Unfortunately, the columns and rows are different in each year, so I wanted to add them all recursively to a list, so I can later apply lapply and do some analysis.
I can download the table and manipulate it into a dataframe when I do it once, but then when I add it to a list, the list only accepts the first column.
library(XML) #reg r=readHTMLTable('http://www.nhl.com/stats/team?season=20132014&gameType=2&viewName=summary#',stringsAsFactors=FALSE) r=as.data.frame(r[3]) for(i in 3:ncol(r)){ r[,i]=as.numeric(r[,i]) }
This gives me r as something I can manipulate. I want to add it to a list:
> l=as.list(NULL) > l[1]=r Warning message: In l[1] = r : number of items to replace is not a multiple of replacement length > l [[1]] [1] "1" "2" "3" "4" "5" "6" "7" "8" "9" "10" "11" "12" "13" "14" "15" [16] "16" "17" "18" "19" "20" "21" "22" "23" "24" "25" "26" "27" "28" "29" "30"
Does anyone know how I can add it into my list so I keep the dimensions
> dim(r) [1] 30 25
The issue is, I have many other tables that I would like to add, and was able to add them, but each one that was added only included the first column/element.
Any ideas is greatly appreciated
Thanks!
-24629719 0 Get session variables from Session Provider class in javascriptHi I have a Session Provider class to handle Sessions in my MVC application.
Here is the Session Provider Class...
public class SessionProvider { public static Portal.Application.BoundedContext.ScreenPop.Dtos.User LoggedUser { get { return (Portal.Application.BoundedContext.ScreenPop.Dtos.User) HttpContext.Current.Session["LoggedUser"]; } set { HttpContext.Current.Session["LoggedUser"] = value; } } public static void Clear() { HttpContext.Current.Session.Abandon(); HttpContext.Current.Session.Clear(); } }
And the User class which used to cast the above Session has these attributes.
I need to get these Name and Phone number in my View using javascript..
Here what I have dobe so far...
<script type="text/javascript"> @{ User loggedUser = SessionProvider.LoggedUser; } var loggedUserName = loggedUser.Name ; var loggedUserPhone = loggedUser.PhoneNumber; </Script>
But I have this error in firebug when I run my application..
ReferenceError: loggedUser is not defined var loggedUserName = loggedUser.Name;
How can I get those two values? I am using Razor View engine...
-34622156 0 High-precision timer in iOSWhat is the most precise way to measure time intervals in iOS? So far I have been using NSDate
to "mark" events and then timeIntervalSinceDate
method to calculate the interval, but is there more precise approach? E.g. Windows has so called QPC for that kind of thing. Is there something similar in iOS (or MacOSX) world?
I have heard it is good practice to use some kind of document management system to keep track of different versions of your code/documents for school/work etc. I am still a student so my repository would just be local to my machine. I'm looking for some advice to get started/get in the habit of doing so. Im using OSX. What is the best/easiest client to use for my purposes? I've used SVN+tortise at work for years and it works great.
Thanks!
-4913123 0 Cross-Browser Extensions API?There are tools for developing cross-platform browser plugins.
Are there any similar tools or APIs for browser extensions (i.e. toolbars, or filter systems like AdBlock)?
-37724712 0 Drop in calender using developer - awful printHello all,
So I am making a spreadsheet with dates in them - for that I used a drop down calender, via the developer tab --> Insert more controls --> Microsoft Date and Time Picker Control.
In the spreadsheet, when it's not in design more, the date format is nice and normal but when I go to print the sheet, it looks like the picture.
How do I get it to print out normally?
-7912643 0 How can I set ReSharper to ignore case-sensitivity when I search a file by name?Is there a way to turn off case-sensitivity in ReSharper when I search for a file by name -I mean by using the short-cut: "CTRL + SHIFT + T" ?
-11130239 0An invalidate queue is more like a store buffer, but it's part of the memory system, not the CPU. Basically it is a queue that keeps track of invalidations and ensures that they complete properly so that a cache can take ownership of a cache line so it can then write that line. A load queue is a speculative structure that keeps track of in-flight loads in the out of order processor. For example, the following can occur
A store buffer is a speculative structure that exists in the CPU, just like the load queue and is for allowing the CPU to speculate on stores. A write combining buffer is part of the memory system and essentially takes a bunch of small writes (think 8 byte writes) and packs them into a single larger transaction (a 64-byte cache line) before sending them to the memory system. These writes are not speculative and are part of the coherence protocol. The goal is to save bus bandwidth. Typically, a write combining buffer is used for uncached writes to I/O devices (often for graphics cards). It's typical in I/O devices to do a bunch of programming of device registers by doing 8 byte writes and the write combining buffer allows those writes to be combined into larger transactions when shipping them out past the cache.
-26874151 0I don't think that setMessageBody
appends (nor its name indicates that), so I think you should construct the body first, using a string variable, and then set the body at the end of the loop:
var body = "" for(var i=0; i < userDataName.count; i++) { body += "\(userDataName[i]) - \(userDataStatus[i])\n" } mc.setMessageBody(body, isHTML: false)
or even:
var body = (0..<userDataName.count) .map { index in "\(userDataName[index]) - \(userDataStatus[index])" } .reduce("") { $0 + $1 + "\n"} mc.setMessageBody(body, isHTML: false)
-14278154 0 after_save :notify_team after_destroy :notify_team private def notify_team Team.goals_sum end
-36337878 0 How to read Call-Info Header from Invite Message using sipml5 I use sipml5 with freeswitch and I need to detect when call should be answered automatically. The only part where I can get it from is SIP Invite message:
recv=INVITE sip:username@IP:50598;transport=ws;intercom=true SIP/2.0 Via: SIP/2.0/WSS IP;branch=z9hG4bKd451.8dc49598935d4ebdf937de014cf1d922.0 From: "Device QuickCall"<sip:NUMBER@DOMAIN>;tag=68rtr6c12v9em To: <sip:michaltesar2@IP:50598;transport=ws> Contact: <sip:mod_sofia@IP:11000> Call-ID: dcd8fb4d69f0850840a743c152f4f7358a21-quickcall CSeq: 89383073 INVITE Content-Type: application/sdp Content-Length: 882 Record-Route: <sip:IP;transport=ws;r2=on;lr=on;ftag=68rtr6c12v9em> Record-Route: <sip:IP;r2=on;lr=on;ftag=68rtr6c12v9em> Via: SIP/2.0/UDP 37.157.194.240:11000;rport=11000;received=IP;branch=z9hG4bKSNmDFvya0ceaQ Max-Forwards: 50 Call-Info: answer-after=0;answer-after=0 User-Agent: 2600hz Allow: INVITE,ACK,BYE,CANCEL,OPTIONS,MESSAGE,INFO,UPDATE,REGISTER,REFER,NOTIFY,PUBLISH,SUBSCRIBE Supported: path,replaces Allow-Events: talk,hold,conference,presence,as-feature-event,dialog,line-seize,call-info,sla,include-session-description,presence.winfo,message-summary,refer Content-Disposition: session Remote-Party-ID: privacy=off;party=calling;screen=yes;privacy=off v=0 o=FreeSWITCH 1459415113 1459415114 IN IP4 37.157.194.240 s=FreeSWITCH c=IN IP4 37.157.194.240 t=0 0 a=msid-semantic: WMS W2YlkINCSBwtCldHnD3FYpIuFQW9iaH5 m=audio 23162 RTP/SAVPF 0 101 13 a=rtpmap:0 PCMU/8000 a=rtpmap:101 telephone-event/8000 a=fingerprint:sha-256 03:8E:7D:14:E6:88:F1:75:55:70:40:E5:7F:07:9F:9F:C5:38:43:59:FB:EF:4D:70:0C:C7:F7:24:FC:7B:54:AB a=rtcp-mux a=rtcp:23162 IN IP4 37.157.194.240 a=ssrc:1258116307 cname:2vgd3UFMl25Od8lq a=ssrc:1258116307 msid:W2YlkINCSBwtCldHnD3FYpIuFQW9iaH5 a0 a=ssrc:1258116307 mslabel:W2YlkINCSBwtCldHnD3FYpIuFQW9iaH5 a=ssrc:1258116307 label:W2YlkINCSBwtCldHnD3FYpIuFQW9iaH5a0 a=ice-ufrag:CfWquvL0by0kyxfq a=ice-pwd:SmtM6ZoiRjWVi8cKdZ1ykDom a=candidate:8660741513 1 udp 659136 IP 23162 typ host generation 0 a=candidate:8660741513 2 udp 659136 IP 23162 typ host generation 0 a=ptime:20
My VOIP phone detects it from Call-Info header :
Call-Info: answer-after=0;answer-after=0
Is there any way how to access Call-Info header using sipml5?
-24694522 0 How to implement phonegap/cordova in android webview?I need just a few minutes for someone to tell me if these steps are correct for implementing cordova in a android webview:
EDIT: Ok I finally got it working these are the right steps:
1) I create project: cordova create hello com.example.hello HelloWorld
and enter the folder
2) cordova platform add android
, cordova run android
(cordova.jar is created) => the app is launched => device is ready is shown
3) I create a cordova_layout.xml in "/res/layout" with this code:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <org.apache.cordova.CordovaWebView android:id="@+id/cordova_web_view" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1" /> </LinearLayout>
4)Import the project (as an "existing project" in eclipse) and add to the main java file after imports:
public class HelloWorld extends Activity implements CordovaInterface { private CordovaWebView cordova_webview; private String TAG = "CORDOVA_ACTIVITY"; private final ExecutorService threadPool = Executors.newCachedThreadPool(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.cordova_layout); cordova_webview = (CordovaWebView) findViewById(R.id.cordova_web_view); // Config.init(this); String url = "file:///android_asset/www/index.html"; cordova_webview.loadUrl(url, 10000); } @Override protected void onPause() { super.onPause(); Log.d(TAG, "onPause"); } @Override protected void onResume() { super.onResume(); Log.d(TAG, "onResume"); } @Override protected void onDestroy() { super.onDestroy(); if (this.cordova_webview != null) { this.cordova_webview .loadUrl("javascript:try{cordova.require('cordova/channel').onDestroy.fire();}catch(e){console.log('exception firing destroy event from native');};"); this.cordova_webview.loadUrl("about:blank"); cordova_webview.handleDestroy(); } } @Override public Activity getActivity() { return this; } @Override public ExecutorService getThreadPool() { return threadPool; } @Override public Object onMessage(String message, Object obj) { Log.d(TAG, message); if (message.equalsIgnoreCase("exit")) { super.finish(); } return null; } @Override public void setActivityResultCallback(CordovaPlugin cordovaPlugin) { Log.d(TAG, "setActivityResultCallback is unimplemented"); } @Override public void startActivityForResult(CordovaPlugin cordovaPlugin, Intent intent, int resultCode) { Log.d(TAG, "startActivityForResult is unimplemented"); } }
NOTE: the activity name must match the one in manifest.xml
Hope it will help you. Have a nice day!
-12952661 1 Python 3.3 in Wamp (Apache 2.4.2 – Mysql 5.5.24 – PHP 5.4.3)I am looking at getting python up and running with my WAMP setup. I need it to test some py apps I am learning to build. I see that Mod_wsgi project was terminated and that was pretty much the only way I found on how to run python on WAMP.
Can anyone advise how to get it up and running? Thank you so much
-2745680 0 FFmpeg bitrate issueI'm dealing with a very big issue about bit rate , ffmpeg provide the -b
option for the bit rate and for adjustment it provide -minrate
and -maxrate
, -bufsize
but it don't work proper. If i'm giving 256kbps at -b
option , when the trans-coding finishes , it provide the 380kbps. How can we achieve the constant bit rate using ffmpeg. If their is +-10Kb it's adjustable. but the video bit rate always exceed by 50-100 kbps.
I'm using following command
ffmpeg -i "demo.avs" -vcodec libx264 -s 320x240 -aspect 4:3 -r 15 -b 256kb \ -minrate 200kb -maxrate 280kb -bufsize 256kb -acodec libmp3lame -ac 2 \ -ar 22050 -ab 64kb -y "output.mp4"
When trans-coding is done, the Media Info show overall bit rate 440kb (it should be 320kb).
Is their something wrong in the command. Or i have to use some other parameter? Plz provide your suggestion its very important.
-38126272 0The problem was that when I applied the VS Update 3 on VS 2015 I did not check the Microsoft Web Developer Tools option. I had to do the following to get the folder and file in place.
Program and Features -> Visual Studio -> right clich and select change -> select modify -> check Microsoft Web Developer Tools -> click update.
After the update run the DotNetCore.1.0.0-VS2015Tools.Preview2.exe file again and select repair (this step is necessary).
This will create the C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v14.0\DotNet.Web and Microsoft.DotNet.Web.targets file
-30626426 0What you're looking for is the PropertyInfo.GetValue()
method:
https://msdn.microsoft.com/en-us/library/b05d59ty%28v=vs.110%29.aspx
Example
property.GetValue(userItem, null);
Syntax
public virtual Object GetValue( Object obj, Object[] index )
Parameters
obj
Type: System.Object
The object whose property value will be returned.
index
Type: System.Object[]
Optional index values for indexed properties. The indexes of indexed properties are zero-based. This value should be null for non-indexed properties.
Return Value
Type: System.Object
The property value of the specified object.
You can get the values with use of ID
. But ID
should be Unique.
<body> <h1>Adding 'a' and 'b'</h1> <form> a: <input type="number" name="a" id="a"><br> b: <input type="number" name="b" id="b"><br> <button onclick="add()">Add</button> </form> <script> function add() { a = $('#a').val(); b = $('#b').val(); var sum = a + b; alert(sum); } </script> </body>
-126011 0 Monitoring a server-side process on Rails application using AJAX XMLHttpRequest I'm using the following in the web page but can't get a response from the server while it's processing
<script type="text/javascript"> <!-- function updateProgress() { //alert('Hello'); new Ajax.Request('/fmfiles/progress_monitor', { parameters: 'authenticity_token=' + encodeURIComponent(AUTH_TOKEN), onSuccess: function(response) { alert(response.responseText); fillProgress('progressBar',response.responseText); } }); } //--> </script> <% form_for( :fmfile, :url => '/fmfiles', :html => { :method => :post, :name => 'Form_Import', :enctype => 'multipart/form-data' } ) do |f| %> ... <%= f.file_field :document, :accept => 'text/xml', :name => 'fmfile_document' %> <%= submit_tag 'Import', :onClick => "setInterval('updateProgress()', 2000);" %>
The 'create' method in fmfiles_controller.rb then happily processes the file and gets the right results (as per the submit button on the form). If I uncomment the '//alert('Hello')' line I get a dialog saying Hello every 2 seconds ... as expected.
However, the server never logs any call to 'progress_monitor' method in 'files' not even a failed attempt.
If I click the link
<a href="#" onclick="updateProgress();">Run</a>
it makes a call to the server, gets a response and displays the dialog, so I assume the routes and syntax and naming is all OK.
I really don't know why this isn't working. Is it because 2 methods in the same controller are being called via URLs?
I'm using Rails 2.1.0 in a development environment on OS X 10.5.5 and using Safari 3.1.2
(N.B. This follows on from another question, but I think it's sufficiently different to merit its own question.)
-10117875 0Is that binary or hexadecimal value?
Basically it means you have a bus of wires, in which some bits are X
(unknown), and others are 0
.
If I saw this binary value: 0x0x0x
, it would just mean that bits 5,3, and 1 are 0
, and bits 4,2, and 0 are X
.
I would like to know when the user from a command line presses control-c so I can save some stuff.
How do I do this? I've looked but haven't really seen anything.
Note: I'm somewhat familiar with lua, but I'm no expert. I mostly use lua to use the library Torch (http://torch.ch/)
-14874357 0 How to use regex to match all element in document.doctype.internalSubsetBy using document.doctype.internalSubset, I have the following string, say str:
<!ENTITY owl "http://www.w3.org/2002/07/owl#" > <!ENTITY xsd "http://www.w3.org/2001/XMLSchema#" > <!ENTITY rdfs "http://www.w3.org/2000/01/rdf-schema#" > <!ENTITY rdf "http://www.w3.org/1999/02/22-rdf-syntax-ns#" >
Then, I use regex to extract the result:
result = regex.exec(str);
My expected output is an array in which:
result[0] = owl "http://www.w3.org/2002/07/owl#" result[1] = xsd "http://www.w3.org/2001/XMLSchema#" ... result[3] = rdf "http://www.w3.org/1999/02/22-rdf-syntax-ns#"
So, I create this regex:
var regex = /(?:<!ENTITY(.*?)>)*/g;
And here is the result, of course, it's not I want:
owl "http://www.w3.org/2002/07/owl#"
Can anyone help me to figure out the errors, and how to fix all of them ?
Note that I can use s.indexOf() to get the position of <!ENTITY
and >, and then, use s.subString() to get the same result, but I'm learning regex now, so I want to use regex.
--------------Update---------------
Thanks to Supr, I can finally figure out the error, it seems to me that, in this case, "*" doesn't mean "match one or many time", so instead of using /(?:<!ENTITY(.*?)>)*/g
, we'll use this one: /(?:<!ENTITY(.*?)>)/g
(supress the *) and then loop over the string until we get all result. Here is the source:
var str = '<!ENTITY owl "http://www.w3.org/2002/07/owl#" >' + '<!ENTITY xsd "http://www.w3.org/2001/XMLSchema#" >' + '<!ENTITY rdfs "http://www.w3.org/2000/01/rdf-schema#" >' + '<!ENTITY rdf "http://www.w3.org/1999/02/22-rdf-syntax-ns#" >' var regex = /(?:<!ENTITY(.*?)>)/g; var results = []; while ((result = regex.exec(str)) != null) { results.push(result[1]); } console.log(str); console.log("-------------------------------"); for (var i = 0; i < results.length; i++) { document.write(results[i] + "<br>"); }
For testing: http://jsfiddle.net/nxhoaf/jZpHv/
By the way, here is my solution using s.indexOf() and recursion:
var str = '<!ENTITY owl "http://www.w3.org/2002/07/owl#" >' + '<!ENTITY xsd "http://www.w3.org/2001/XMLSchema#" >' + '<!ENTITY rdfs "http://www.w3.org/2000/01/rdf-schema#" >' + '<!ENTITY rdf "http://www.w3.org/1999/02/22-rdf-syntax-ns#" >' var getNamespace = function(input) { var result = []; // Store the final result var temp = []; // Store the temporary result // Non trivial case if ((input != null) && (input.length != 0)) { // Get the begin and and index to extract the entity's content var begin = input.indexOf("<!ENTITY"); var end = input.indexOf(">"); if ((begin == -1) || (end == -1) || (begin >= end)) { // not found return null; } // Fix the begin index begin = begin + "<!ENTITY".length; // Get the content and save it to result variable var item = input.substring(begin, end); // ok, get one item // As end > begin, item is always != null item = item.trim(); // Normalize result.push(item); // Continue searching with the rest using // recursive searching temp = getNamespace(input.substring(end + 1)); // Ok, collect all of data and then return if (temp != null) { for (var i = 0; i < temp.length; i++) { result.push(temp[i]); } } return result; } else { // Trivial case return null; } } // Parse it to get the result result = getNamespace(str); console.log("*************"); for (var i = 0; i < result.length; i++) { document.write(result[i] + "<br>"); }
you can test it here: http://jsfiddle.net/nxhoaf/FNFuG/
-6716585 0 Postr Wall To Fans Page Using Graph APII am trying to post wall through my application with Facebook Graph API to user's fan page. Please give me ideas how can I past wall to the fan page using Graph API and without using the access token of fans page .
Thanks in advance!
-6523635 0An alternative way: Put it in the resource file, if something change you don't need to escape it again.
-30345829 0You can use the HttpRequest.UrlReferer
property. Create the single action in some controller:
public class SomeController : BaseController { public ActionResult Change(int value) { Session["Value"] = value; return Redirect(Request.UrlReferer.ToString()); } }
-5735706 0 Vim: Edit multi aleatory lines I'm aware of the possibility to edit multiple lines on the same column by doing:
CTRL+V down...down..down... SHIFT+I type_string_wanted
But I'd like to edit multiple specific locals addin new strings (maybe using cursor (h j k l) or mouse (with :set mouse=a)).
Like on this example, where I want to add the string 'XX' to specific locations. I.e.,
from this:
Hi. My name is Mario!
to this:
XXHi. My XXname is XXMario!
Any ideas?
-20608687 0You can use wine to run MASM code in Linux using emulator8086.
install wine : sudo apt-get install wine
Here is link for emulator: http://www.emu8086.com/
-5332046 0SELECT * FROM articles, articles_cat_main WHERE articles.id = %s AND ...
And %s is replaced with the content of a variable called $colname_article. Based on the name of that variable, I don't think it contains an integer, that can be inserted there without quotes.
If it is either empty or contains a string without quotes, it will result in the syntax error you saw.
Please note that this kind of dynamic SQL statements is prune to have SQL injection vulnerabilities.
-27826938 0 Disable or change Reporting in TFS 2013 when configured server missing/offlineLike many other out there I had the fun task of upgrading or TFS 2008 server to a brand-new TFS 2013 install.
The good news -> this has been done and documented. The bad news -> you have to migrate to TFS 2012 and then Migrate from 2012 to 2013.
All things said it mostly went fairly smooth. I cannot really complain. There is one hitch, however. Or plan was to use an intermediate server (SQLTFS01) for the TFS and SQL Server 2012 install and then most everything onto our destination server for 2013 (SQL008). Then we were to take SQLTFS01 offline and re purpose that machine.
In the end there was a missed step. It seems that our final install of TFS2013 is still pointed to SQLTFS01 for the reporting services components. See here:
Attempts to disable the reporting and analysis services portion of the server are all failing because even in order to disable the tool, it tries to connect to the existing tool.
Question: How can we disable this feature or redirect this stuff? Can we do it though setting files that I am not aware of?
Thanks, Tom
-22940241 0i'm interested in this, but that's gonna be pretty hard because in the vertical view, you dont have any information about resource, the only thing is the generated/visual planning.
So there's probably a first work to do in the renderer to add this information on the column or on every slot...
Didn't have much time but i tried to start this, and i don't have anything working actually...
If any Fullcalendar master is crossing our way... Some help would be very appreciated ;)
-39064975 0Just wondering can i assume that 2^(loglogn) has the same growth as 2^n?
No. Assuming that the logs are in base 2 then 2^log(n)
mathematically equals to n
, so 2^(log(log(n)) = log(n)
. And of course it does not have the same growth as 2^n
.
Should I take 1.1^n as a constant?
No. 1.1^n
is still an exponent by n
that cannot be ignored - of course it is not a constant.
The correct order is:
2^loglogn = log(n) n,3n nlogn, 6nlogn 4n^2 7n^3 – 10n n^8621909 1.1^n n!
I suggest to take a look at the Formal definition of the Big-O notation. But, for simplicity, the top of the list goes slower to infinity than the lower functions.
If for example, you will put two of those function on a graph you will see that one function will eventually pass the other one and will go faster to infinity.
Take a look at this comparing n^2
with 2^n
. You will notice that 2^n
is passing n^2
and going faster to infinity.
You might also want to check the graph in this page.
The usual problem when trying to use an audio signal as digital signal input is that it is high-pass-filtered to avoid offsets (long term pressure changes which could destroy the dynamic range of the soundcards Analog-to-Digital converters). This means you will get only the changes of the digital signal (like "clicks"). Actually you will be better of the higher frequency your signal has, but it will be non-trivial to process it well then (this was what ordinary modems did very well).
If you can control the digital signals sent as sound (or to the microphone jack), make sure they are modulated the signal with one or more tones, like a morse transmitter or modem. Essentially you want to use your iPhone as an Aucoustic Coupler. This is possible, but of course a bit computationally expensive considering the quite low bandwidth.
Start by using some dirt simple modulation, like 1200-1800 Hz and make an FFT of it. There's probably some reference implementation for any sound card out there to get started with.
There have been some cool viruses recently that was said to be able to jump air-gaps, they used similar techniques as this one.
If you still really want a DC (or slowly changing digital signal), check out a solution using a separate oscillator that is amplitude-modulated by the incoming signal
-28077342 0Just use min-width to prevent div from resizing.
.Site-Content-Container{min-width: 960px;}
Edited: or maybe not. position: absolute;
is an option. To be honest, it is not clear which text is not meant to resize.
You can always redirect to the error page and display an appropriate message.
if (!request.IsValid(Item_Edit)) { //skip the rest and return error Response.StatusCode = (int)HttpStatusCode.Forbidden; ViewBag.errorMessage = "Sorry you do not have access to this page"; return View("Error") // Need Help Here!!! }
And the in your error page (should have one in the shared view folder) you can add the following line
@ViewBag.errorMessage
EDIT
If you dont want to redirect to error page and stay on page x you can do the following
if (!request.IsValid(Item_Edit)) { //skip the rest and return error Response.StatusCode = (int)HttpStatusCode.Forbidden; ModelState.AddModelError("", "Sorry you do not have access to this page"); ModelForPageX modelX = new ModelForPageX(); // do any other setup you need to in order to render page X return View("X",modelX) }
This assumes you have a @Html.ValidationSummary
on the view for page X if not add the following line
@Html.ValidationSummary(true, "Unable to process the requested action:")
-7100695 0 alias for expressions in hql queries my Hibernate version is 3.2.6.ga
Googling around reveals many people are having the same problems with Hibernate HQL not handling aliases very well. Apparently HQL only lets you alias a column that exists in a table. Also, HQL generates its own aliases for all columns in the query and these have the form col_x_y_ but how these are generated I don't know.
For my case I want to add two derived columns into a third derived column. Trivial in native SQL, surprisingly difficult in HQL.
My contrived, simplified example:
sqlcmd = " SELECT aa.course.code, " + " (CASE WHEN aa.gender = 'M' THEN 1 ELSE 0 END), " + " (CASE WHEN aa.gender = 'F' THEN 1 ELSE 0 END), " + " ( col_0_1_ + col_0_2_ ) " + " FROM Student AS aa ";
How can I add the 2nd and 3rd columns together to form a 4th column in HQL?
TIA,
Still-learning Steve
-27725949 0See this answer http://stackoverflow.com/a/27727236/286335. Really short, easy and general.
-24741709 0The problem is your use of @synthesize
.
By simply writing @synthesize usertoken;
, an ivar is created that is also just called userToken
(no underscore).
If you instead do @synthesize usertoken = _userToken;
, it will work correctly.
I'm using Aquamacs (graphical emacs for OSX using emacs 24 and tramp version 2.2.3) to edit some files on a remote server. Tramp is set up to use ssh and works fine in terms of editing files.
It fails when it comes to compiling because the compiler is not in the path. It seems like tramp does not source any of the profile files like .profile or .bash_profile. /bin/sh is a link to /bin/bash so bash should be the shell used by tramp. A shell started within emacs on the remote server won't source anything, too. A ssh connection from a regular terminal emulator (tried Terminal and X11 on OS X) works as expected (everything sourced correctly).
Any ideas?
-5847615 0 Document.referrer issue on IE when the requests doesn't come from a linkPossible Duplicate:
IE has empty document.referrer after a location.replace
Hi there,
I have got an issue on using the document.referrer property in IE. When I get to a page not through a link but changing the window.location through JavaScript, the document.referrer of the destination page is empty in IE7/8. Any idea on how to get around it?
Thanks.
-1468973 0 Thread safe lazy initializer; is swapping Func<>s a good idea?The class at the bottom is an implementation of fast, thread safe, "lock free", lazy initializer.
I say "lock free", although it isn't completely; It uses a lock until it is initialized, and then replaces the call to get the data with one that doesn't use the lock. (Similar to a double checked lock with a volatile member; and from performance tests I get v. similar results.)
My question is; is this a good/safe thing to do?
(After I had written this I noticed that the .net 4.0 has a LazyInit<T>
which performs the same operations and more, but in a very highly contrived example that I created my implementation was slightly faster :-) )
NB Class has been modified to include Value
member, and volatile on the _get
class ThreadSafeInitializer<TOutput> where TOutput : class { readonly object _sync = new object(); TOutput _output; private volatile Func<TOutput> _get; public TOutput Value { get { return _get(); } } public ThreadSafeInitializer(Func<TOutput> create) { _get = () => { lock (_sync) { if (_output == null) { _output = create(); _get = () => _output; // replace the Get method, so no longer need to lock } return _output; } }; } }
-5408929 0 You need a log analyzer for IIS. Webtrends used to be quite popular. I used it a dog's life ago. Most use Google Analytics these days, but it's a different beast and tracks traffic, not data transfer volume. You really need to look at the server logs for that.
-14430016 0This, undocumented and unsupported, feature apparently never did work on Windows.
Instead you can use one of the pre-built runtime systems that loads a main.sav from the folder containing the executable. E.g. save your test.sav as main.sav instead and place it alongside sprti.exe in a folder that contains a proper folder structure for SICStus, as described in the manual, in the section Runtime Systems on Windows Target Machines.
The most common solution is to use the spld.exe tool an build a self contained executable but that requires the corresponding C compiler from Microsoft.
(I am one of the SICStus Prolog developers)
-28450786 0 setTimeout() multiple JQuery instancesSo I have a block of about 10 lines of code in JQuery. the lines are all independent, and when I execute them (I just type them in the console, its an automated test) i need them to be delayed form each other, like with 2 seconds difference. I started by using JavaScript setTimeout() on each line, but for 10 separate lines of code i assume there's a sexier way to do so... Also JQuery DELAY doesn't work since these aren't effects. Any ideas? here's the general idea of my code block..
$("#tag1").trigger("click"); $('#tag2').val("some text"); $("#tag3").trigger("keyup"); $('#tag4 select option[value="4"]').prop('selected',true); $("#tag5").val(6); $('#tag6').val(3).change(); $('#tag7').val(30).change(); $('#tag8').val("2017-06-29"); $('#tag9').val("2015-06-29"); $('#tag10').val("This is the test tasks' description."); $(".id1").trigger("click"); $(".id2").val("buy oranges");
As you can see all the tags and ID are unique... any idea would be greatly appreciated!
-8228544 0What about EvaluateIsValid(); Seems to be what you want
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.basevalidator.evaluateisvalid.aspx
from this post
http://forums.asp.net/t/1049481.aspx/1
This seems really similar to waht you want to do
http://www.codeproject.com/KB/aspnet/enhacedvalidator.aspx
-17283196 0After Noogen's answer it got me thinking if Cordova needed to be updated so i grabbed the latest phonegap files and replaced the cordova.js file and the 2.8.1 jar file and then did a clean and build - it worked!
-39093820 0The JVM is a stack-based virtual machine. VMKit was an open-source project of LLVM which implemented a JVM with a LLVM backend. The idea of VMKit was to create a toolkit for building virtual machines (or managed runtime environments) such as JVM, CLI/CLR, R's runtime etc. To find out more, see Nicolas Geoffray's PhD thesis. While the project is retired, the source code is still available.
Also, Microsoft have released llilc which is a LLVM JIT compiler for IL/MSIL/CIL (which could be argued is a stack machine). The JIT code can be found here.
-3493795 0Even better, use DEFAULT instead of NULL. You want to store the default value, not a NULL that might trigger a default value.
But you'd better name all columns, with a piece of SQL you can create all the INSERT, UPDATE and DELETE's you need. Just check the information_schema and construct the queries you need. There is no need to do it all by hand, SQL can help you out.
-23776481 0Thanks for all the help, and the answer I selected most closely answers the problem of 2 emulators running slowly.
What it turned out to be was that I was using 767MB on an Intel HAXM emulator, and creating 2 of those went over the allocated amount for HAXM. After running 1 Intel and 1 ARM emulator, it worked. The error message was somewhat inconspicuous so I didn't notice it at first.
-29371942 0When you add a Script Task or Component to an SSIS package, there is a template in your installation folder that SSIS uses.
For 2012, it'd be in Program Files (x86)\Microsoft SQL Server\110\DTS\Binn
In there, you have a VSTA11_IS_ST_CS_Template.vstax file which is just an uncompressed zip.
IS%20Script%20Task%20Project.csproj
I blogged a similar approach with Slimming down the SSIS Script Task
The specific attribute you're looking to modify in the project file is
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
What you wanted to change it to, you never specified
-19885054 1 Python user input and mathematical operation error>>> g = input("Enter a number") Enter a number43 >>> g + 2 Traceback (most recent call last): File "<pyshell#7>", line 1, in <module> g + 2 TypeError: Can't convert 'int' object to str implicitly
The program wont let me use the input variable in mathematical operations, like g + 2
So, I'm making a web browser.
And I would like to offer my user the ability to see whether a website is secure or not.
What parameters should I consider for a website to be secure?
How can I check if the website has an SSL certificate using objective-c?
-20725042 0 JS: Calling a function from within that function, when dealing with multiple instancesHow do I call a function from within the function, when I have multiple instances of that function?
I know I can simply call the function from within:
$(".mCSB_container").sortable({ revert: true, scroll: true, update: function( event, ui ){ new update(param1); }, }); function update(param1){ if (updating){ //If I'm already updating, I want to wait for that update to be finished setTimeout(function(){ update(param1); }, 100) } else { updating = true; //Proceed with the update //... postUpdate(); } } function postUpdate(){ $.ajax({ url: '/update', type: 'POST', dataType: 'json', async: true, data: postData, success: function (data) { //... updating = false; return data; }, error: function (data) { //refresh page return false; } }); }
Now I'm trying to get my head around how instantiation works in JS. I know I can create a new instance simply by calling new update(param1);
, but then what's going to happen in the timeout when I try to call the update function? I can always just create a new instance every time, but isn't that inefficient?
If I could just call the same instance from within the instance that seems like it would be ideal.
Thanks for any help, I greatly appreciate it.
-15106677 0You can also export template and then create a new project from the exported template changing the name as you prefer
-38200196 0 Is there a way to use Serenity @Managed annotation to manage custom webdriverI am trying to explore Serenity automation framework to test the application (built with SmartClientGWT) using SmartClientWebDriver
After adding a custom WebDriver (that returns SmartClientFirefoxWebDriver, because SmartClientWebDriver cannot be instantiated unfortunately) and setting it in serenity.properties file, I am able to execute a single test.
But now I want to mark my custom driver (SmartClientFirefoxWebDriver) using @Managed annotation to allow the Serenity Test runner to instantiate it before all tests are run. But it throws error:
java.lang.NullPointerException: null
Has anyone ran into a similar issue and had luck resolving it?
-20859454 0Check if you have zero value for recursion property of the model.
$this->Post->recursive = 0;
After hours of headbanging removing the above line fixed it for me
-31979750 0Why not use clpfd?
Building on my previous answer to a very related question, we query:
?- solve_n_dump([A,M] + [P,M] #= [D,A,Y]). Eq = ([2,5]+[9,5]#=[1,2,0]), Zs = [2,5,9,1,0]. Eq = ([2,7]+[9,7]#=[1,2,4]), Zs = [2,7,9,1,4]. Eq = ([2,8]+[9,8]#=[1,2,6]), Zs = [2,8,9,1,6]. Eq = ([3,5]+[9,5]#=[1,3,0]), Zs = [3,5,9,1,0]. Eq = ([3,6]+[9,6]#=[1,3,2]), Zs = [3,6,9,1,2]. Eq = ([3,7]+[9,7]#=[1,3,4]), Zs = [3,7,9,1,4]. Eq = ([3,8]+[9,8]#=[1,3,6]), Zs = [3,8,9,1,6]. Eq = ([4,5]+[9,5]#=[1,4,0]), Zs = [4,5,9,1,0]. Eq = ([4,6]+[9,6]#=[1,4,2]), Zs = [4,6,9,1,2]. Eq = ([4,8]+[9,8]#=[1,4,6]), Zs = [4,8,9,1,6]. Eq = ([5,6]+[9,6]#=[1,5,2]), Zs = [5,6,9,1,2]. Eq = ([5,7]+[9,7]#=[1,5,4]), Zs = [5,7,9,1,4]. Eq = ([5,8]+[9,8]#=[1,5,6]), Zs = [5,8,9,1,6]. Eq = ([6,5]+[9,5]#=[1,6,0]), Zs = [6,5,9,1,0]. Eq = ([6,7]+[9,7]#=[1,6,4]), Zs = [6,7,9,1,4]. Eq = ([7,5]+[9,5]#=[1,7,0]), Zs = [7,5,9,1,0]. Eq = ([7,6]+[9,6]#=[1,7,2]), Zs = [7,6,9,1,2]. Eq = ([7,8]+[9,8]#=[1,7,6]), Zs = [7,8,9,1,6]. Eq = ([8,5]+[9,5]#=[1,8,0]), Zs = [8,5,9,1,0]. Eq = ([8,6]+[9,6]#=[1,8,2]), Zs = [8,6,9,1,2]. Eq = ([8,7]+[9,7]#=[1,8,4]), Zs = [8,7,9,1,4]. true.
-20663077 0 Your DataSet is returning multiple table. You can select only one table to bind to a gridview. Here's how your DataSet looks:
Solution: For each table use separate GridView. Bind GridViews like below:
GridView1.DataSource = ds.Tables["OutbondInfo"]; GridView1.DataBind(); //Add another GridView "GridView2" in markup GridView2.DataSource = ds.Tables["InboundInfo"]; GridView2.DataBind();
Hope it helps!
-26141164 0Skype was hogging port 80
I came to this conclusion from using this on the command line:
netstat -ano
Then finding the PID against port 80 in Task Manager
Then quitting skype and seeing the issue go away.
I resolved the conflict by changing Skype settings to leave port 80 alone. This also explains why the 404 was not an IIS styled 404 page and why there was nothing in the IIS logs - just a question mark against the default website icon.
-19787734 0If you are saving javascript in external file, save as filename.json
var employees = [ { "firstName":"John" , "lastName":"Doe" }, { "firstName":"Anna" , "lastName":"Smith" }, { "firstName":"Peter" , "lastName": "Jones" } ];
Then improt filename.json in webpage using jquery as //jquery plugin must be added first
$(document).ready(function(){ $.getJSON("filename.json",function(result){ alert(result[0].firstname + result[0].lastname); }); });
-21796262 0 I need to add a header to categorize the list item in Drawer
Customize the listView
or use expandableListView
I need a radio button to select some of my options
You can do that without modifying the current implementation of NavigationDrawer
, You just need to create a custom adapter for your listView
. You can add a parent layout as Drawer
then you can do any complex layouts within that as normal.
I have a 400 similar length columns with different lengths of NA
s at the beginning of columns - How could I obtain an equal row length data frame that begins after the last row with NA
s from any column.
X<-c(NA,NA,NA,NA,3,4,5,67,8,9,2) Y<-c(NA,NA,2,3,4,1,5,6,7,8,9) s<-data.frame(X,Y) s X Y 1 NA NA 2 NA NA 3 NA 2 4 NA 3 5 3 4 6 4 1 7 5 5 8 67 6 9 8 7 10 9 8 11 2 9
Desired output:
X Y 1 3 4 2 4 1 3 5 5 4 67 6 5 8 7 6 9 8 7 2 9
-18963468 0 This question is a bit older, but still the answer may help others. My Example also depends on Commons-Io.
You can create a ContainerRequestFilter and use TeeInputStream to proxy/copy the original InputStream:
@Provider @Priority(Priorities.ENTITY_CODER) public class CustomRequestWrapperFilter implements ContainerRequestFilter { @Override public void filter(ContainerRequestContext requestContext) throws IOException { ByteArrayOutputStream proxyOutputStream = new ByteArrayOutputStream(); requestContext.setEntityStream(new TeeInputStream(requestContext.getEntityStream(), proxyOutputStream)); requestContext.setProperty("ENTITY_STREAM_COPY", proxyOutputStream); } }
And use @Inject with javax.inject.Provider in your ExceptionMapper to get the ContainerRequest injected.
The ExceptionMapper would look like this:
@Provider public class BaseExceptionMapper implements ExceptionMapper<Exception> { @Inject private javax.inject.Provider<ContainerRequest> containerRequestProvider; @Override public Response toResponse(Exception exception) { ByteArrayOutputStream bos = (ByteArrayOutputStream) containerRequestProvider .get().getProperty("ENTITY_STREAM_COPY"); String requestBody = bos.toString(); ... } }
When I have also used the @Component annotation my ExceptionMapper was not used. I think that @Provider is sufficient.
-20072950 0I'm not sure anybody is going to write the code you need. Casperjs has pretty good documentation. You need to request the page, find the id's of the login and sendKeys. I haven't run into any issues of not being able to log into a web based application using casper. IF you're completely at a loss I have a video you can watch which enters data into an Ajax application, which shouldn't be too much different than what you're trying to do. Filling out Ajax forms
-40436109 0Using the BufferReader/InputReader(System.in) classes is a good alternative to using the Scanner class in the sense that code operation is not blocked while waiting for input from the User. This is why the while loop is in play so as to actually wait for User Input. While waiting for User input, several things such as running other code can take place including the start of other Threads etc.
On the other hand, when using a Scanner object, to get input from the User you might have:
Scanner scan = new Scanner(System.in); String name = scan.nextLine();
When the scan.nextLine(); method is encountered code is completely blocked until a User enters something into the Console unless special Thread & thread locks have been put into play within your code. As a simple example, try yourself to set up a console User Input request which only gives the User 10 or 20 seconds to provide that input and upon timeout the application closes (perhaps for a login or whatever).
This is difficult to do using the Scanner object (but not impossible) since when the input request is issued further code operation is blocked yet with BufferReader/InputReader this is relatively simple to carry out since code blocking is done with your own code (usually with a while Loop). Below is a simple method example which allows you to ask the User to provide input but with a time limit:
/** * Method for asking a question (prompt) requiring an input from User within a Console window. Question (prompt) * contains a supplied time limit to answer unless 0 is supplied in which case then there is no time limit.<br><br> * * Whether this method is used within a GUI application or a Console application, code is halted until the ask() method * has either timed out or User input has been provided. The ask() method does not allow for an Empty Answer (if just * the ENTER key is pressed). Instead it continues to poll for an answer until either one is given or the time limit expires.<br><br> * * <b>Example Usage:</b><pre> * * System.out.println("[10 Seconds]"); * String question = "What is 1+1?\nA: 1\tB: 2\tC: 3\tD: 4\n"; * String answer = ask(question, 10); * * if (answer.equalsIgnoreCase("b")) { System.out.println("CORRECT!"); } * else { System.out.println("WRONG!"); }</pre><br> * * @param question (String) The prompt (question) to display within console.<br> * * @param timeLimit (Integer) The time limit in seconds for each question (prompt) to be answered. If 0 is supplied * then there is no time limit.<br> * * @param options (Optional - String)<pre> * * tickDisplay - (Default is an asterisk (*)) By default an asterisk is is displayed in sequence for * every second that expires unless of course the time limit supplied is 0 in which case * no tick display is shown. If a null string is supplied for this optional parameter then * again no tick display is shown. Any string can be supplied here. * * timeOutMessage - This optional parameter allows you to change the default display message that is displayed * when the supplied time limit has expired. This message is not displayed if a time limit of * 0 is supplied or a Null String ("") is supplied in this parameter. The default mesage is: * "\b\b\b\u001B[31mYour time is up for this question!\u001B[39;49m".</pre> * @return (String) */ public static String ask(final String question, final int timeLimit, final String... options) { boolean questionAnswered = false; String tickDisplay = "*"; String timeOutMessage = "\b\b\b\u001B[31mYour time is up for this question!\u001B[39;49m"; if (options.length > 0) { if (options.length >= 1) { tickDisplay = options[0]; } if (options.length == 2) { timeOutMessage = options[1]; } } final String td = tickDisplay; final String tom = timeOutMessage; // Establish a new Thread for performing our question timing... Thread timerThread = new Thread(new Runnable() { @Override public void run() { String tickDisplayrun = td; String timeOutMessageRun = tom; try { // See if this thread has been interrupted. If it has then // we stop our timer While/Loop (a gracefull Thread Stop). while (!Thread.currentThread().isInterrupted()) { for (int seconds = timeLimit; seconds >= 1; seconds--){ // Break out of this timer FOR loop if the question // was answered by using Thread.interrupt(). if (questionAnswered) { Thread.currentThread().interrupt(); break;} // Show that timer is ticking away... if (!td.equals("")) { tickDisplayrun = tickDisplayrun.replace("<tl>", String.valueOf(timeLimit)).replace("<s>", String.valueOf(seconds)); System.out.print(tickDisplayrun); } // ========================================================== // Or you can use this... // if (seconds < secondsForTimout) { System.out.print("-"); } // System.out.print(seconds); // ========================================================== Thread.sleep(1000); } // If the question wasn't answered and our timer loop has // expired then inform User that time is up. if (!questionAnswered) { if (!timeOutMessageRun.equals("")) { timeOutMessageRun = timeOutMessageRun.replace("<tl>", String.valueOf(timeLimit)); System.out.print(timeOutMessageRun); } Thread.currentThread().interrupt(); } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }); // Catch Exceptions for BufferReader()/InputStreamReader()... try { // Declare a BufferReader object so as to get input from User. // We use BufferReader along with InputStreamReader(System.in) // for this. BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println(question); // Declare User input variable & initialize to a Null String String input = ""; // Make sure our timer thread is dead before restarting it. //while (timerThread.isAlive()){} // Start the Timer Thread if (timeLimit > 0) { timerThread.start(); } // Loop through input from the User do { // Wait until we have User input data to complete a readLine() // or until our timer thread has set the timeOut variable to // true. while (!br.ready()) { // If our timer thread has timed Out then // let's get outta this question altogether. // First we get out of our 'wait for input' loop... if (timeLimit > 0 && !timerThread.isAlive()) { break; } } // Then we get out of our Do/While Loop. if (timeLimit > 0 && !timerThread.isAlive()) { break; } // No time-out so let's move on... // Let's see what the User supplied for an answer. // If just ENTER was supplied then input will contain // a Null String and the User can still enter an answer // until the question is timed out. input = br.readLine(); // remove any unwanted text from System.out.print() // that had made its way through the timer thread. System.out.print("\b\b\b\b\b"); } while ("".equals(input)); // Stop the timer thread. timerThread.interrupt(); return input; } catch (IOException ex) { return ex.getMessage(); } }
An example of how you can use this method:
String strg = ask("What is your name? (you have 20 seconds to answer)", 20, ""); if (strg.equals("")) { System.out.println("\nNo name provided...Quitting!"); System.exit(0); } System.out.println("\nYour name is: " + strg);
Just for the fun of it, try to accomplish the same task using the Scanner class.
As for the code block example you posted, it looks as though it simply asks the User to enter a continuous series of strings. The while loop within the code continues to accept input from the User (once the ENTER key is hit) until he/she enters null (which they can't, CTRL+D or CTRL+Z doesn't always work). At this point polling for input is halted (the while loop ends) and the input which had been placed into a String List Array is iterated through and displayed within the console window. What you want to do with the strings contained within the List array is entirely up to you....save it to a file, display it within a JTextArea component, whatever.
Now...there is a bit of a flaw with the code and the problem lies within the while loop condition. While the User is providing input he/she is permitted to continuously enter strings until the cows come home but there is no way to satisfy the the condition within the while loop. The is no bulletproof way to provide 'null' to the console so that the rest of our code can be run which iterates through the List<> array and displays each element which consists of strings the User previously entered. The solution to this is to supply an additional condition which permits the User to enter the word quit so as to indicate "I'm done making my entries...do your thing". So we change the while Loop to start like this:
while ((line = br.readLine()) != null && !line.equalsIgnoreCase("quit")) { ....... ....... }
Now, if the User enters the single word quit (regardless of letter case) we exit our while loop and the remaining code is run. We don't want to use a Null String ("") for this because we might want the blank lines provided by the User during the text entry which is usually done when starting a new paragraph for example.
-16620184 0Meanwhile, you can also "capture a subroutine's print output to a variable."
Just pass a scalar ref to open
:
#! /usr/bin/env perl use common::sense; use autodie; sub tostring (&) { my $s; open local *STDOUT, '>', \$s; shift->(); $s } sub fake { say 'lalala'; say 'more stuff'; say 1 + 1, ' = 2'; say for @_; } for (tostring { fake(1, 2, 3) }) { s/\n/\\n/g; say "Captured as string: >>>$_<<<"; }
Output:
Captured as string: >>>lalala\nmore stuff\n2 = 2\n1\n2\n3\n<<<
-3372939 0 Is it ok to have MVVM without model for temporary things? Do you think it is alright from architectural stand-point to have ViewModel - View without model for temporary things?
E.g.: I want users to input some paths so I can open some files later on. It doesn't make sense for me to store the paths anywhere just ViewModel and when the user clicks "Show all files" I then construct models of the files and ViewModels for View that represent them somehow. So really my only model is the model of the file.
-19345782 0Check your asset/www/ folder. Check the index.html file is there.
-13795550 0I would look into a Mobile Device Management provider such as Silverback (http://silverbackmdm.com/), or Zenprise (http://www.zenprise.com). Microsoft is also releasing an extension to Intune services in 2013 for MDM too.
The MDM providers allow the enforcement of device security policies, including thins such as remote wipe, password enforcement, etc. It's a great way to manage BYOD policies.
-17011472 0You need to set self.contentView
height first Use this code:
- (void)configureScrollView { [self.contentView addSubview:self.contentArticle]; CGRect frame = self.contentArticle.frame; frame.size.height = self.contentArticle.contentSize.height; self.contentArticle.frame = frame; [self.scrollView addSubview:self.contentView]; frame = self.contentView.frame; frame.size.height += self.contentArticle.frame.height; self.contentView.frame = frame; self.scrollView.contentSize = self.contentView.frame.size; self.contentArticle.editable=NO; self.contentArticle.scrollEnabled=NO; //enable zoomIn self.scrollView.delegate=self; self.scrollView.minimumZoomScale=1; self.scrollView.maximumZoomScale=7; }
-14708081 0 Objective C Unsure where method is being called? Showing what a novice I am with Objective C here. The second of these two methods is getting called by the method above. Though I have absolutely no idea where? I want to be able to wrap the part that calls the second method in an if statement to determine if the file did exist based on the returned Boolean. Example code would be appreciated, if anyone could also explain how this second method gets called that would also be fantastic.
-(void) queryResponseForURL:(NSURL *)inURL { NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:inURL]; [request setHTTPMethod:@"HEAD"]; NSURLConnection * connection = [NSURLConnection connectionWithRequest:request delegate:self]; // connection starts automatically } -(BOOL)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{ if([(NSHTTPURLResponse *)response statusCode] == 200){ NSLog(@"file exists"); return YES; }else return NO; }
-10003684 0 When you use port 636, LDAP over SSL is used,
http://en.wikipedia.org/wiki/Ldap
If you use Microsoft Network Monitor or Wireshark to capture the packets, you may gain more insights on packet level.
In this case, CRL is necessary as it is enabled by default. But you can turn it off on machine or application level,
http://www.page-house.com/blog/2009/04/how-to-disable-crl-checking.html
-1940929 0 to open an excel file, what is the difference between these 2 assemblieswhen adding a reference I see:
.net tab
microsoft.office.tools.excel
is that the one I need to read a excel file?
other posts seem to be using a COM assembly with 'interop' in it?
-11010628 0While it's possible to argue that double-clicking the map or wheel-zooming the map need not take account of the mouse location (because you are acting on the map object rather than a location on the map), pinch-to-zoom is always location-dependent because you physically stretch or squash the map around a location. To alter that behaviour would be distinctly unintuitive.
In this case you should listen for zoom_changed
or idle
and then pan the map to recentre it, so the user can see what's going on.
You could even use those events to handle the default double-click or mousewheel behaviour so that it's obvious you are changing the level of control the user normally has.
-31162775 0 Typeahead AngularStrap: too many $http callsI'm using angularstrap typeahead for autocomplete suggestions via $http. Demo here.
<input type="text" class="form-control" ng-model="selectedAddress" data-animation="am-flip-x" bs-options="address.formatted_address as address.formatted_address for address in getAddress($viewValue)" placeholder="Enter address" bs-typeahead>
Everything works fine but everytime I type a letter, a call is made. Even if I set a minLength of 3, a call is made for length one and two.
How do I prevent that behaviour? Other thing that happens is when template/controller is loaded, the function getAddress is called...
-18938527 0synchronized
on an instance method does just serialize calls per instance, synchronized
on a static method would do that per class, hence for all calls. So they have different lock objects. As one can guess now, a static synchronized
method may be used to modify those static fields.
That's because the Javascript engine is built into your browser. CURL does not know what Javascript is.
What you need to write is called a "shell script" that can be initiated with a cron task.
-7547233 0 Size of button in alertdialoghow can i change the size of button in alertdailog in code without using xml ? I'm not using view ..
Thank you The code : alertbox3.setNeutralButton("Cancel",new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } });
I don't believe so. As you alluded, it's easy to use ZipFile
with an actual file on the file system, but not so for a file embedded in your application.
For accessing a zip file in your APK, you'd have to use something like Resources.openRawResource(R.raw.zip_file)
and then wrap the returned InputStream
in a ZipInputStream
and do it the usual Java way, rather than with the Android method.
Alternatively, if you really find you need to use the ZipFile
class, you could extract the zip file from the APK to the SD card or, more reliably, to your application's local storage.
ok let's say I have these two links
<script src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script>
I'm using these as my javascript sources
and I created another file called
<script src="testing.js"></script>
but in my html I want to show the script src="testing.js" I am able to somehow put the first two links into the testing.js file?
so in my html it'll only show
<script src="testing.js"></script>
but actually it's running three scripts...
-36905087 0Only one change..
Use
$('#records_table').html('<img src="assets/content/login.gif">');
Instead of
$('#records_loading').html('<img src="assets/content/login.gif">');
Final Code:
<script> function showResult(str) { $.ajax({ url: '/getjson.php?search='+str, type: 'POST', dataType:'json', beforeSend:function(response) { $('#records_table').html('<img src="assets/content/login.gif">'); $('#records_loading thead.bg-teal').hide(); }, success: function (response) { var trHTML = ''; $.each(response, function (key,value) { trHTML += '<tr><td>' + value.ID + '</td><td>' + value.Timestamp + '</td><td>' + value.Number + '</td><td>' + value.Message + '</td><td>' + value.Status + '</td></tr>'; }); $('#records_loading thead.bg-teal').show(); $('#records_table').html(trHTML); $('.table-togglable').trigger('footable_redraw'); } }); } showResult(''); </script>
-37544765 0 sims like this plugin help you. For landscape you have to use screen.lockOrientation('landscape'); in controller. And on other page if they are not in portrait view you have to put screen.lockOrientation('portrait');
-10733956 01 million entries containing words shouldn't be slow if you have an index on the word column. This is because the words would be pretty short but with enough entropy (statistical dispersion) to leverage the key.
If this were 1 million phrases, comparing the phrases might have taken a bit longer and in order to optimise you could've broken the phrases down into the first 3 words (in different columns) and a column for the rest of the phrase with 4 column index over them.
Test the speed like this:
set_time_limit(60*60); $pdo = new PDO('mysql:host=localhost;dbname=db', 'user', 'pass'); $x = microtime(TRUE); for($i = 0; $i < 1000000; $i++) { $word = ''; for($j = 0; $j < mt_rand(0,40); $j++) { $word .= chr(97+mt_rand(0,25)); } if($_GET['select']) $pdo->query("SELECT FROM words WHERE word = '$word';"); else if($_GET['insert']) $pdo->exec("INSERT IGNORE INTO words (word) VALUES ('$word');"); } $x = microtime(TRUE)-$x; var_dump($x); CREATE TABLE IF NOT EXISTS `words` ( `word` varchar(40) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL, UNIQUE KEY `word` (`word`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1;
The speed I clocked on my laptop was initially 80.765522003174 seconds, and I've done 10 tests and the average is around 93.478111839294 seconds for the 1million select statements, meaning 1 tenth of a millisecond for each select.
Take into consideration the fact that I clocked it from PHP that means that the actual SQL execution speed is much higher, the 93.5 seconds include PHP communicating with MySQL over TPC.
I have inserted an extra 9million values into the table and tested the same script running 1million select statements against 10million values. The overall duration is around 52 seconds.
-7765871 0I just did alot of his, hope it helps
Spinner m1ssspinner = (Spinner)findViewById(R.id.m1_ss_spinner); ArrayAdapter<CharSequence> m1ssadapter = ArrayAdapter.createFromResource(this, R.array.m1_ss_list, R.layout.my_normal_spinner_style); m1ssadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); m1ssspinner.setAdapter(m1ssadapter); Spinner m1sqs1spinner = (Spinner)findViewById(R.id.m1_sqs1_spinner); ArrayAdapter<CharSequence> m1sqs1adapter = ArrayAdapter.createFromResource(this, R.array.m1_sqs1_list, R.layout.my_normal_spinner_style); m1sqs1adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); m1sqs1spinner.setAdapter(m1sqs1adapter);
-2515402 0 CSSEdit + Adobe Dreamweaver + TextMate + Transmit FTP + Firefox with FireBug and FirePHP and you good to go on MAC ;)
I moved to MAC 2 years ago, no regrets.
-9789651 0Just call .replace()
again:
var someVar = 'Hello I am a string'; var modified = someVar.replace('Hello', 'Goodbye').replace('am', 'was'); console.log(modified); // Goodbye I was a string
Remember that the String.replace()
javascript method is actually like a combination of PHP's str_replace()
and preg_replace()
- the first argument can be a regex as well as a string. So you can also do:
var someVar = 'Hello I am a string'; var modified = someVar.replace(/(hello|string)/ig, 'Goat!').replace('am', 'was'); console.log(modified); // Goat! I was a Goat!
-7902765 0 You will have to parse the Expression
that is returned from the Expression
property on the IQueryable<T>
implementation.
You'll have to query for the Queryable.Where
method being called as you crawl the Expression
tree.
Also note that while Queryable.Where
is going to be the most common way to detect a where
filter, query syntax allows for other implementations to be used (depending on what namespaces are used in the using
directives); if you have something that is not using the Queryable.Where
extension method then you'll have to look for that explicitly (or use a more generic method of filtering for a Where
method that takes an IQueryable<T>
and returns an IQueryable<T>
).
The ExpressionVisitor
class (as pointed out by xanatos) provides a very easy way of crawling the Expression
tree, I highly recommend using that approach as a base for processing your Expression
tree.
Of note is that ExpressionVisitor
class implementations are required to store and expose state on the class level. Because of that, it would be best (IMO) to create internal classes that perform the action one-time and then have a public method which creates a new instance of the ExpressionVisitor
every time; this will help with dealing with mutating state, and if done properly, will allow the method to be thread-safe as well (if that is a concern of yours).
Look at the ZOrder of the component.
-12117441 0 RowNumber() and Partition By performance help wantedI've got a table of stock market moving average values, and I'm trying to compare two values within a day, and then compare that value to the same calculation of the prior day. My sql as it stands is below... when I comment out the last select statement that defines the result set, and run the last cte shown as the result set, I get my data back in about 15 minutes. Long, but manageable since it'll run as an insert sproc overnight. When I run it as shown, I'm at 40 minutes before any results even start to come in. Any ideas? It goes from somewhat slow, to blowing up, probably with the addition of ROW_NUMBER() OVER (PARTITION BY)
BTW I'm still working through the logic, which is currently impossible with this performance issue. Thanks in advance..
Edit: I fixed my partition as suggested below.
with initialSmas as ( select TradeDate, Symbol, Period, Value from tblDailySMA ), smaComparisonsByPer as ( select i.TradeDate, i.Symbol, i.Period FastPer, i.Value FastVal, i2.Period SlowPer, i2.Value SlowVal, (i.Value-i2.Value) FastMinusSlow from initialSmas i join initialSmas as i2 on i.Symbol = i2.Symbol and i.TradeDate = i2.TradeDate and i2.Period > i.Period ), smaComparisonsByPerPartitioned as ( select ROW_NUMBER() OVER (PARTITION BY sma.Symbol, sma.FastPer, sma.SlowPer ORDER BY sma.TradeDate) as RowNum, sma.TradeDate, sma.Symbol, sma.FastPer, sma.FastVal, sma.SlowPer, sma.SlowVal, sma.FastMinusSlow from smaComparisonsByPer sma ) select scp.TradeDate as LatestDate, scp.FastPer, scp.FastVal, scp.SlowPer, scp.SlowVal, scp.FastMinusSlow, scp2.TradeDate as LatestDate, scp2.FastPer, scp2.FastVal, scp2.SlowPer, scp2.SlowVal, scp2.FastMinusSlow, (scp.FastMinusSlow * scp2.FastMinusSlow) as Comparison from smaComparisonsByPerPartitioned scp join smaComparisonsByPerPartitioned scp2 on scp.Symbol = scp2.Symbol and scp.RowNum = (scp2.RowNum - 1)
-5762751 0 Localized App Icons with Retina Display for iOS I have issues showing a localized app icon with retina display support.
How could this be done?
I tried to make Icon.png and Icon@2x.png localized, then I tried to make the proj-Info.plist localized and try to link to different Images.
But only the Icon of the project language are being shown...
-36179545 0I believe you need the scale_numeric
argument with reverse = TRUE
to flip the order of the range.
Below is an example based on the mtcars
dataset.
library(ggvis) mtcars %>% ggvis(~wt, ~mpg) %>% layer_points() %>% add_axis("x", orient = "top") %>% scale_numeric("y", reverse = TRUE)
-12813644 0 First of all, A lot depends on with which controller is your UIViewController embedded in.
Eg, If its inside UINavigationController, then you might need to subclass that UINavigationController to override orientation methods like this.
subclassed UINavigationController (the top viewcontroller of the hierarchy will take control of the orientation.) needs to be set it as self.window.rootViewController.
- (BOOL)shouldAutorotate { return self.topViewController.shouldAutorotate; } - (NSUInteger)supportedInterfaceOrientations { return self.topViewController.supportedInterfaceOrientations; }
From iOS 6, it is given that UINavigationController won't ask its UIVIewControllers for orientation support. Hence we would need to subclass it.
MOREOVER
Then, For UIViewControllers, in which you need only PORTRAIT mode, write these functions
- (BOOL)shouldAutorotate { return YES; } - (NSUInteger)supportedInterfaceOrientations { return (UIInterfaceOrientationMaskPortrait); }
For UIViewControllers, which require LANDSCAPE too, change masking to All.
- (NSUInteger)supportedInterfaceOrientations { return (UIInterfaceOrientationMaskAllButUpsideDown); //OR return (UIInterfaceOrientationMaskAll); }
Now, if you want to do some changes when Orientation changes, then use this function.
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration { }
VERY IMPORTANT
in AppDelegate, write this. THIS IS VERY IMP.
- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window { return (UIInterfaceOrientationMaskAll); }
If you want to provide only Portrait mode for all your viewcontrollers, then apply the portait mask. i.e UIInterfaceOrientationMaskPortrait
Otherwise, if you want that some UIViewControllers stay in Portrait while others support all orientations, then apply an ALL Mask. i.e UIInterfaceOrientationMaskAll
-4953932 0As BoltClock mentioned that png files are compressed, but you can view it on MAC using a little application called iphoneapp , i use it regularly and found it useful
-37673794 0Summary: It works, git-p4 is a great tool, very intelligent, comes with lot of configurable options. Multiple branches scattered wherever across depot tree migrated successfully. We need to run the import at highest level (topmost) perforce directory that covers all sub-directories or branches of interest. For efficient operation, suggested to use --changesfile option, to explicitly specify changelists to be imported. Also use git-p4.branchUser and git-p4.branchList to explicitly specify branchspecs.
Details: Here I am showing the settings that worked for me. There may be a better way to achieve the goal.
Perforce depot structure: (as mentioned in question)
Perforce client: This is set at highest (topmost) p4 directory. This is very important, otherwise git-p4 may exclude changelists (restricted due to client view) as empty commits.
//depot/... //myp4client/...
Perforce branchspecs: I created a single branchspec that covers all my branches dependency (parent/child) information
$ p4 branch -o test1 | grep "//" //depot/dev/project/master/... //depot/dev/project/branch1/... //depot/dev/project/master/... //depot/dev/project/branch2/... //depot/dev/project/branch1/... //depot/dev/sub-project/branch3/... //depot/dev/project/branch1/... //depot/dev/sub-project/branch4/... //depot/dev/project/master/... //depot/patch-project/branch5/... //depot/patch-project/branch5/... //depot/patch-project/special/developern/branch6
git-p4 config items: Next, I setup an empty git repository and following config items.
mkdir workdir cd workdir git init
(** perforce variables)
git config git-p4.user myp4user git config git-p4.passwowrd myp4password git config git-p4.port myp4port git config git-p4.client myp4client
(** force to use perforce client spec)
git config git-p4.useClientSpec true git config git-p4.client myp4client
( ** restrict to explore branchspecs created only by me)
git config git-p4.branchUser myp4user
( ** branch information, dependency relation, interestingly only last name (directory name in branch path) is required to mention, git-p4 automatically detects/pick what is required i.e. fully expanding the branch name )
git config git-p4.branchList master:branch1 git config --add git-p4.branchList master:branch2 git config --add git-p4.branchList branch1:branch3 git config --add git-p4.branchList branch1:branch4 git config --add git-p4.branchList master:branch5 git config --add git-p4.branchList branch5:branch6
Changelists file: Next, I collected all the changelists, for all branches those I am migrating.
p4 changes //depot/dev/project/master/... | cut -d' ' -f2 >> master.txt p4 changes //depot/dev/project/branch1/... | cut -d' ' -f2 >> master.txt p4 changes //depot/dev/project/branch2/... | cut -d' ' -f2 >> master.txt p4 changes //depot/dev/sub-project/branch3/... | cut -d' ' -f2 >> master.txt p4 changes //depot/dev/sub-project/branch4/... | cut -d' ' -f2 >> master.txt p4 changes //depot/patch-project/branch5/... | cut -d' ' -f2 >> master.txt p4 changes //depot/patch-project/special/developern/branch6/... | cut -d' ' -f2 >> master.txt sort -n master.txt | uniq > master_sorted.txt
Import: Finally I ran the import as below, I used "sync" and not clone.
cd workdir ../git-p4.py sync //depot/... --detect-branches --verbose --changesfile /home/myp4user/master_sorted.txt
On smaller depots “ ../git-p4.py sync //depot@all --detect-branches --verbose “ shall also work, in that case no need to create changelists file (earlier step)
Once import is finished, I am able to see git-p4 created all remote perforce branches inside single git repository.
git branch -a remotes/p4/depot/dev/project/master remotes/p4/depot/dev/project/branch1 remotes/p4/depot/dev/dev/project/branch2 remotes/p4/depot/dev/dev/sub-project/branch3 remotes/p4/depot/dev/dev/sub-project/branch4 remotes/p4/depot/patch-project/branch5 remotes/p4/depot/patch-project/special/developern/branch6
Then I created local branches from remote p4 branches
git checkout -b master remotes/p4/depot/dev/project/master git checkout -b branch1 remotes/p4/depot/dev/project/branch1 git checkout -b branch2 remotes/p4/depot/dev/dev/project/branch2 git checkout -b branch3 remotes/p4/depot/dev/dev/sub-project/branch3 git checkout -b branch4 remotes/p4/depot/dev/dev/sub-project/branch4 git checkout -b branch5 remotes/p4/depot/patch-project/branch5 git checkout -b branch6 remotes/p4/depot/patch-project/special/developern/branch6
Next I simply added a remote origin and pushed the code into git repo.
Thanks for various pointers/help available in stackoverflow and online.
POSTBACK: Part of ASP.NET's contrived technique for hiding the true stateless nature of the web/HTTP behind a stateful facade. This results in complex code (IsPostback, ...), a hard to understand page lifecycle, many different events, ... and numerous problems (ViewState size, web-farm stickyness, state servers, browser warnings (not using PRG pattern), ...)
See ASP.NET MVC instead.
-15711073 0 Will the optimizer prevent the creation of a string parameter if a constant will prevent it from being used?My question is best made with an example.
public static boolean DEBUG = false; public void debugLog(String tag, String message) { if (DEBUG) Log.d(tag, message); } public void randomMethod() { debugLog("tag string", "message string"); //Example A debugLog("tag string", Integer.toString(1));//Example B debugLog("tag string", generateString());//Example C } public String generateString() { return "this string"; }
My question is, in any of the examples, A, B or C - since the string would not be used ultimately would the optimizer remove it?
Or asked another way, would it be better to do the following, thus ensuring that the string objects would not be created?
public void randomMethod() { if (DEBUG) debugLog("tag string", "message string"); //Example A if (DEBUG) debugLog("tag string", Integer.toString(1));//Example B if (DEBUG) debugLog("tag string", generateString());//Example C }
-40773288 0 Linked workbooks - main workbook keep old values I have a main workbook with many cells linked to other workbooks cells.
The source workbooks must be replaced from time to time and some of them sometimes are just erased.
For those cells in the main workbook linked to deleted source workbooks I was expecting to get "#REF!", but instead I get old values, from the deleted workbooks.
Is there a way I can get rid of old values and get "#REF!" or blank cells instead?
-7916554 0 Error 404 with file_get_contents on one server, on another it works fineI'm have a problem with file_get_contents() - on my old server everything works fine, on my new one it throw 404 error on some URLs I'm trying to get.
All the URLs are from the same website and in the same structure - but some gives me this message:
Warning: file_get_contents(http://url.com/path_to_file.html) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 404 Not Found in /home/user/domains/domain.com/public_html/tst.php on line 3
I have DirectAdmin with his basic configurations installed on the new server, while on the other I have cPanel
Someone know what's the problem could be?
Thanks.
-3805086 0A few canned answers from well known experts: Paul Nielsen Why use Stored Procedures?
Adam Machanic: No, stored procedures are NOT bad
-12942408 0You want to change it's value, not html. It doesn't have html children.
$(this).val('Changed');
or
this.value = "Changed";
-40725863 0 gen.flow_from_directory
gives you a generator. The images are not really generated. In order to get the images, you can iterate through the generator. For example
i = 0 for batch in gen.flow_from_directory(path+'train', target_size=(224,224), class_mode='categorical', shuffle=False, batch_size=batch_size, save_to_dir=path+'augmented', save_prefix='hi'): i += 1 if i > 20: # save 20 images break # otherwise the generator would loop indefinitely
-32938880 0 They way I fixed is was by adding autocrlf = input , safecrlf = false on the git.config file
Thanks for trying to help @ macareno.marco
-4011339 0String ordinal(int num) { String[] suffix = {"th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th"}; int m = num % 100; return String.valueOf(num) + suffix[(m > 10 && m < 20) ? 0 : (m % 10)]; }
-40671489 0 It sounds like there are currently some issues with scaffolding when the models are located outside the current project. As a workaround, you can add the model temporarily to your web project and then move it to the BLL/DAL projects after scaffolding.
Example of issue my team were having with this sort of setup (not exactly what you're coming across, but I think our setups are similar enough and the problem might be due to the same issue): https://github.com/aspnet/Scaffolding/issues/249
A recent commit to fix this issue (indicates approved for version 1.0.0-preview2-update1): https://github.com/aspnet/Scaffolding/commit/b12a8068eb6312e108f2abdfa6f837b142025c0e
So I suppose up until 1.0.0-preview2-update1, this will remain an issue so long as you have a project that splits things out into more than one assembly. In my case, the project setup is too complicated to copy things into one project... So I can only bang my head against the wall :( and start typing the scaffolded code.
-16438947 0You seem to store empty string (''
) rather than NULL
in the empty fields. Those are different things in MySQL
.
Use this:
SELECT * FROM cities WHERE cssstyle > ''
By using "greater than" you give MySQL
posibility to use an index range scan on cssstyle
When I follow the link given in terminal it also gives directs me to a blank page. But if I copy and paste the link into my browser it works fine. Dont know what is happening there...
[Stack: OSX, Google Chrome, Python 3, TensorFlow installed via pip]
Ps. I would/should have commented on, not answered, this question. But my reputation is too low.
-41057455 0First of all, create a base SLES image. Luckily for you, this process is [semi]automated by SUSE through the utility called sle2docker. A manual can be found here: https://www.suse.com/documentation/sles-12/book_sles_docker/data/cha_sle2docker_installation.html https://github.com/SUSE/sle2docker
Then you should run your container, install and setup your custom software and do docker commit
to create you personal customized image. https://docs.docker.com/engine/tutorials/dockerimages/
While loading a web site, I often have the need to load code AFTER some other DOM structural event has occurred. Therefore I often end up with a lot of functions that first check if some element exist in the DOM and then do their thing in the event that said element exist.
(ns example.core (:require [cljs.core.async :as async] goog.async.AnimationDelay) (:require-macros [cljs.core.async.macros :refer [go go-loop]])) (defn register-click-handler [] (when js/window.document.body (goog.events.listen js/window.document.body goog.events.EventType.CLICK #(js/console.log "I was clicked!")) true)) (defn loop-until-true [fx] (let [c (async/chan) f (goog.async.AnimationDelay. #(async/put! c :loop))] (async/put! c :initial-loop) (go-loop [] (async/<! c) (when-not (true? (fx)) (.start f) (recur))))) (loop-until-true register-click-handler)
I think I like this pattern as it lets me write fx
that keeps trying until the DOM is in a state where the function can succeed (return true); without having to go through a great deal of ceremony in terms of dealing with retrying (just return true on success).
I am looking for improvements to loop-until-true
, a function that registers another function to keep executing until that function returns true. I don't want to actually block the execution of the code that might cause fx
to pass, so I am using a core.async block to IOC the code. This code seems to work, but I am looking for improvements and critics.
[EDIT: Irrelevant suggestion about SQLite 3.7.11 removed]
You could use insert-select with the user id as a literal:
INSERT OR IGNORE INTO messages_seen (message_id, user_id) SELECT message_id, 4 FROM messages WHERE mb_topic_id = 7
-2964976 0 Does it make sense to always wrap an InputStream as BufferedInputStream, when I know whether the given InputStream is something other than buffered?
No.
It makes sense if you are likely to perform lots of small reads (one byte or a few bytes at a time), or if you want to use some of the higher level functionality offered by the buffered APIs; for example the BufferedReader.readLine()
method.
However, if you are only going to perform large block reads using the read(byte[])
and / or read(byte[], int, int)
methods, wrapping the InputStream
in a BufferedInputStream
does not help.
(In response to @Peter Tillman's comment on his own Answer, the block read use-cases definitely represent more than 0.1% of uses of InputStream
classes!! However, he is correct in the sense that it is usually harmless to use a buffered API when you don't need to.)
Something like this?
class ParentFoo(object): def __init__(self,a,b,c=None): print(c) class ChildFoo(ParentFoo): def __init__(self,d,e,f=None): super(ChildFoo,self).__init__(d,e,c="fing") c = ChildFoo("1","2")
Official python doc here https://docs.python.org/2/library/functions.html#super
-4407957 0belong_to accepts a :foreign_key
and :class_name
attribute.
If you already have a retrieved author and you want to get the article count then using the related manager's count
method (author.article_set.count()
) is probably okay.
On the other hand if you are iterating over an (possibly lagre) Author
queryset just to get the counts, it will do a lot of queries (one to retrieve all authors and one per author to get the count). This can be easily replaced by an annotated queryset that will result in only one query:
from django.db.models import Count Author.objects.annotate(article_count=Count('articles'))
Later on in your in your template you can just use {{ article.author_count }}
.
UIBarButtonItem *temp = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]; UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; [button setImage:[UIImage imageNamed:@"BlueMarbleDrop"] forState:UIControlStateNormal]; button.frame=CGRectMake(0.0, 0.0, 60.0, 30.0); [button addTarget:self action:nil forControlEvents:UIControlEventTouchUpInside]; UIBarButtonItem* stopBtn = [[UIBarButtonItem alloc] initWithCustomView:button]; [self.toolBar setItems:[NSArray arrayWithObjects:temp,stopBtn,temp, nil]];
the output look like
i took this from UIBarButtonItem with color?
-14842907 0Google not only prohibits direct personally identifiable data, but it also prohibits data that can be used to indirectly personally identify people within your own system. So in other words, if that GUID is attached to a personally identifiable info within your own system, you cannot send that data to GA, because you can easily export the GA data, tie it back into your system, and attribute GA data to personally identifiable data.
Of course, someone would have to bring it to google's attention, and someone would have to prove there is a link to said data...
-14717951 0If I understood your requirements correctly, you can first let your lambda functor accept an argument of the appropriate type (passing by reference here, so take care of lifetime issues):
doSomething([](QNetworkReply* p) { // Here you have the sender referenced by p });
Then, your doSomething()
template function could use std::bind()
to make sure your lambda will be invoked with the appropriate object as its argument:
template<typename Functor> void MyClass::doSomething(Functor f) { connect(network_reply, &QNetworkReply::finished, bind(f, network_reply)); //... }
-23310709 0 How to use AWK command Below is what I am trying to do:
There is one PHP variable which contains a string.
$indexvalue='hotmail.com; spf=none (sender IP is 1.1.1.23)';
I want to use an AWK command to get value none
and IP value 1.1.1.23
in two different PHP variables.
How can this be done?
-9604531 0Data<void *> obj;
constructs a Data object to store void *
type using the parameterized constructor passing new Data
as the parameter value. obj
itself needs to be a pointer:
#include <iostream> int main(){ Data<float> *obj = new Data<float>(31.34f); std::cout << obj->val; }
Your version is equivalent to:
Data<void *> objs; // no param constructor /* Data<float>(31.34f); param constructor */ obj = Data<void *>(new Data<float>(31.34f)); // param constructor
-38006168 0 Get Last week date ranges in php , week Monday to sunday Using a Php date functions i would like to get the last week date ranges,
for example.
its Friday, 24th June 2016 Today.
I want the out put
Last week Start Date : 2016-06-13 (YYYY-mm-dd Format)
Last week End Date : 2016-06-19 (YYYY-mm-dd Format)
Is that possible ?
-14896988 0Problem now identified: it was IE8 and it's protected mode settings! See IE8 - Not writing certain cookies on my machine for more information...
-14847334 0Maybe try:
document.write("2 * 3 * 4".match(/[0-9]+[\s]?\*[\s]?[0-9]+[\s]?\*[\s]?[0-9]+/));
-6349743 0 You can show any kind of UIViewController
in a UIPopoverController
. A table view is not at all required for displaying a Popover controller. If you want to display a UITableviewController
, you most certainly can. Just pass it in to the popover controller.
Why must RichTextBox be readonly? What happens if it is not readonly?
If this is a known bug in the datdgrid then i would consider hacking a if-it-looks-right-it-is-right solution (i think this beats modifying/fixing a dll).
Examples, does it must be a hyperlink? Can it be a textblock instead (which you'd handle the hyperlinking part in code)?
-24274584 0 How do I match lines consisting *only* of four digits and remove lines in betweeen two regexp matches?I need to process a file consisting of records like the following:
5145 Xibraltar: vista xeral do Peñón 1934, xaneiro, 1 a 1934, decembro, 31 -----FOT-5011-- Nota a data: extraída do listado de compra. 5146 Xixón: a praia de San Lorenzo desde o balneario ca.1920-1930 -----FOT-3496-- 5147 Xixón: balneario e praia de San Lorenzo ca.1920-1930 Tipos de unidades de instalación: FOT:FOT -----FOT-3493--
I need to remove the 1 to 4 digits record number (i.e.: 5145) and any notes such as "Nota a data: extraída do listado de compra" which always come at the end of the record, after the signature (-----FOT-xxxx--) and before the next record's record number.
I've been trying to write an awk program to do this but I don't seem to be able to grasp awk's syntax or regular expressions at all.
Here's my attempt to match record numbers, those lines consisting of 1 to 4 digits only. (I think I'm missing the "only" part).
$ gawk '!/[[:digit:]]{1,4}/ { print $0 }' myUTF8file.txt
Also, I can match these (record signatures):
$ gawk '/-----FOT-[[:digit:]]{4}--/ { print $0 }' myUTF8file.txt -----FOT-3411-- -----FOT-3406-- -----FOT-3397-- -----FOT-3412-- ...
but I don't know how to remove the lines in between those and the record numbers.
Excuse my English and my repeated use of the word record, which I know might be confusing given the topic.
-15507314 0 Using Javascript on the Content of an iframeI have a page with some tabbed content on it. A couple of the tabs contain iframes and I use a handy little script to resize the iframes to suit their content. It's
function autoResize(id){ var newheight; if(document.getElementById){ newheight=document.getElementById(id).contentWindow.document.body.scrollHeight; } newheight=(newheight)+40; // Makes a bit of extra room document.getElementById(id).height= (newheight) + "px"; }
Today I have added a little jQuery script to stop the tabbed area showing until it is fully loaded. This stops the tabs doing an unsightly little jump when the loading is complete. This is the script:
$(document).ready(function(){ $("#tabber").hide(); $("#loading").hide(); $("#loading").fadeIn(1000); }); $(window).load(function(){ $("#loading").hide(); $("#tabber").fadeIn(300); });
The loading div contains a loading icon and the tabber div is the entire content of the tabbed area.
This script is also stopping the iframe resizing working. In order to understand it better I added another script:
function checkResize(id){ var win=document.getElementById(id).contentWindow.document.body.scrollHeight; alert(win);
Sure enough, "win" comes up as zero. If I delete the $("#tabber").hide() line, "win" shows a sensible number for the height of the iframe.
Is there another way of making the two things compatible?
Vlad produced the solution: I had to use the jQuery version of visibility=hidden instead of the jQuery version of display:none. That doesn't actually exist in jQuery so I found out from another StackOverflow question how to write my own functions to do it.
The final script is
(function($) { $.fn.invisible = function() { return this.each(function() { $(this).css("visibility", "hidden"); }); }; $.fn.visible = function() { return this.each(function() { $(this).css("visibility", "visible"); }); }; }(jQuery)); $(document).ready(function(){ $("#tabber").invisible(); $("#loading").hide(); $("#loading").fadeIn(1000); }); $(window).load(function(){ $("#loading").hide(); $("#tabber").visible(); });
My thanks to Vlad, and also RAS, for taking the trouble to look at my question and give their ideas.
-5672156 0You can use the Java library from here: http://www.johannes-raida.de/jnetcad. As far as I can see, it should support JT version 8 files. I used the DXF import library and was quite happy. The API is the same, so you have access to all triangles with their coordinates, normals, color and layer.
-21433795 0I would suggest you using stanford Name Entity Recognizer(NER). Stanford NER provides many classifiers.One of the classifiers provided by stanford NER can identify name,location and organization from a given text.
You can find an online demo for stanford NER in this link http://nlp.stanford.edu:8080/ner/
-27619231 0 R Web Scraping 'Failed to load HTTP Resource' with XMLI have created a function to scrape statistics from individual soccer match reports. I am usually able to use this to scrape stats from hundreds of matches at a time without a problem. However for the past week I have been away visiting family for the holidays cannot run my code at all without receiving the message:
Error: failed to load HTTP resource
I thought this was just my parents poor internet connection but I am now having the same problem wherever I go around the country!
My code starts with creating a vector of match codes for each game:
matchid <- c(369835, 369842, 369839, 369836, 369834, 369841)
My function is currently as below:
GetStats <- function(matchid){ Stats <- NULL for(i in matchid){ urli <- paste("http://www.espnfc.co.uk/gamecast/statistics/id/", i, "/statistics.html", sep="") datai <- readHTMLTable(urli) hometeami <- datai[[1]] awayteami <- datai[[2]] hometeami <- hometeami[1:11,] awayteami <- awayteami[1:11,] matchdatai <- rbind(hometeami, awayteami) matchdatai$match_id <- i matchdatai <- matchdatai[c(14, 1:13)] Stats <- rbind(Stats, matchdatai)} return(Stats) }
I then run my function on my individual match codes:
MatchStats <- GetStats(matchid) View(MatchStats)
But it is at this point that I am now receive the error message.
Could someone please help me by helping me understand what might be causing this? As far as I can see nothing has changed in the websites I am trying to scrape. Is it something caused by the internet connections I am now using? Is there a simple fix I can add in to my code to overcome this?
As mentioned, I am able to run this on hundreds of matches at once on my own connection at my flat so I am very confused!
Thank you in advance
-20674416 0Browsers render borders statically;
About animating the border of a TextBox (presuming input:text or textarea) cross-borwser AND cross-platform is impossible. For a lesser scoped of browser, per say, modern browsers, there is css-level3 with border-image
.
But it will be painfull.
About displaying a progress bar upon a TextBox, it will be quite easier, especially if your content is loaded via AJAX. It's all about a container displayed position absolute left top. Then the css animes the container.
See jquery-ui or search the net for 'animated progess bar'
-18118669 0Use this...
image { width: 100px; height: auto; }
Of course you can do <img src="src" style="width:100px; height:auto;">
and changed width and height to 100px
accordingly.
Try this:
int numItems = 0; // count of items in your shopping cart NSString *imageName = [NSString stringWithFormat:@"cartTab-%d",numItems]; // change your image [[self.tabBar.items objectAtIndex:myIndex] setImage:[UIImage imageNamed:imageName]]; // or, if you want to set it when initializing the tabBar UITabBarItem *item = [[[UITabBarItem alloc] initWithTitle:myTitle image:[UIImage imageNamed:imageName] tag:someTag];
-33155754 0 Reset the simulator and Clean and build the code.
If you are trying to run app in device than check all cerficates are verified and uninstall app and try to run again.
-13118062 0You can create your own category to be able to get array of touches that is declared in the UIPinchGestureRecognizer interface
UITouch *_touches[2];
Then, when you create your gesture recognizer, you set callback to it, that will receive recognizer as parameter. Using category method, you can get all info (you need positions in this case) for every touch and process them to determine needed rotate angle.
-40939802 0 spring boot mvc:resources mappingI want to develop web app with spring boot and i want to address my javascript and css resources in jsp files. i config my access to this files from jsp in dispatcher-servlet.xml like this:
<mvc:resources mapping="/resources/**" location="/WEB-INF/resources/" />
and in my jsp file i can use below code to access that:
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %> <img class="first-slide home-image" src="<spring:url value="/resources/images/back1.jpg"/>" alt="First slide">
how i do config mvc:resources mapping in spring boot?
-35475316 0It looks like your stack is empty do you use Intent Flags? Try a look here http://developer.android.com/guide/components/tasks-and-back-stack.html
if ya have just one Activity override the OnBackPress event and do your thing just return or something.
@Override public void onBackPressed() { return; }
Xamarin People:
public override void OnBackPressed() { base.OnBackPressed(); return; }
-4910772 0 Unfortunately attributes are just metadata, meaning they cannot run or do something on their own.
However nothing prevents you from writing an extension method with a name like SetDefaultValues
that reads default values from attributes and assigns them to properties.
I've done a similar thing in a recent project, and it proved to be a good decision because it kept all default values defined in a declarative style in a single place.
There is an interesting article on CodeProject peering into different strategies for implementation of [DefaultValue]
-based initialization and comparing their performance. I suggest you check it out.
1st thing Id check is- Open up your flat file connection manager, select the column that's being imported and see what the data type is set to -
Check the Output Column width and increase if its small
-10110928 0 How do I resolve two nodes which have the same name but under different parents? <PublicRecords> <USBankruptcies> <USBanktruptcy>...<USBankruptcy> <CourtId>...</CourtId> <USBanktruptcy>...<USBankruptcy> <CourtId>...</CourtId> </USBankruptcies> <USTaxLiens> <USTaxLien>...<USTaxLien> <CourtId>...</CourtId> <USTaxLien>...<USTaxLien> <CourtId>...</CourtId> </USTaxLiens> <USLegalItems> <USLegalItem><USLegalItem> <CourtId></CourtId> <USLegalItem><USLegalItem> <CourtId></CourtId> </USLegalItems> </PubicRecords>
I am using a combination of doc and xpath objects to extract the attributes and node contents.
NodeList bp = doc.getElementsByTagName("USBankruptcy"); NodeList nl = doc.getElementsByTagName("CourtId"); long itrBP; for (itrBP = 0; itrBP < bp.getLength(); itrBP++ ) { Element docElement = (Element) bp.item(itrBP); Element courtElement = (Element) nl.item(itrBP); NodeList df = docElement.getElementsByTagName("DateFiled"); if(df.getLength() > 0) { dateFiled = nullIfBlank(((Element)df.item(0)).getFirstChild().getTextContent()); dateFiled = df.format(dateFiled); }
But, when I say get elements of tag name CourtID, it will get all the CourtIDs, not just the ones under USBankruptcy.
Is there any way to specify the parent?
I tried NodeList nl = doc.getElementsByTagName("USBankruptcies/CourtId");
It gave me a dom error on run time.
-39315813 0I can not fully explain it, but the problem seems to be that session.downloadTaskWithURL(url)
returns an instance of some internal subclass __NSCFLocalDownloadTask
.
If you define the extension as an extension of NSURLSessionTask
instead of NSURLSessionDownloadTask
extension NSURLSessionTask { ... }
then it worked in my test.
-24821212 0Modern, LINQ-based way (old-fashined C-programmers can turn in one's grave):
List<Byte> list = new List<byte>() { 0x01, 0x5F }; var output = list.Select(x => (int)x) .Reverse() .Aggregate((x, y) => (int)0x100 * y + (int)x);
-37313590 0 About java.util.concurrent AtomicInteger I came across source code of AtomicInteger class on GrepCode and found following code snippet.
static { try { valueOffset = unsafe.objectFieldOffset (AtomicInteger.class.getDeclaredField("value")); } catch (Exception ex) { throw new Error(ex); } } private volatile int value;
How the static block know the offset of instance variable value . Static initialise when class is loaded and linked . so how can we know about the offset of the instance value at class loading time . Object are created after class loaded . Is that "value" instance variable will have fixed offset when ever object is created. Please explain .
-15963625 0select * from table_name order by cast (PARTICULARS as int) asc
You should type cast varchar to int or float to sort..
Hope it does good for you.
-30368199 0Create a Temporary Table from where condition for acknowledgements, schema will have column required in final result and used in JOIN with all your 7 tables
CREATE TEMPORARY TABLE __tempacknowledgements AS SELECT g.name AS hostgroup , '' AS hostname , a.host_id , s.display_name AS servicename , a.service_id , a.entry_time AS ack_time , '' AS AS start_time , '' AS timeperiod , a.state AS state , a.author , a.acknowledgement_id AS ack_id FROM centstorage.acknowledgements a WHERE YEAR(FROM_UNIXTIME( a.entry_time )) = YEAR(CURDATE()) AND MONTH(FROM_UNIXTIME( a.entry_time )) = MONTH(CURDATE()) AND a.service_id IS NOT NULL ORDER BY a.acknowledgement_id ASC;
Or create using proper column definition
Update fields from all tables having left join, you can use Inner Join in update. You should write 7 different update statements. 2 examples are given below.
UPDATE __tempacknowledgements a JOIN centstorage.hosts h USING(host_id) SET a.name=h.name; UPDATE __tempacknowledgements s JOIN centstorage.services h USING(service_id) SET a.acl_res_name=s.acl_res_name;
similar way update ctime from logs using Join with Logs, this is 8th update statement.
a sp can be written for this.
-38055135 0 How can I slice and parse the data received via streaming API?I am trying to connect to the Meetup streaming HTTP API and parse the received events in different records. I am using ruby over Sinatra. I chose the 'em-http-request' gem to handle the connection and 'thin' as server. Searching for info on how to handle an API streaming all that I found was about 3 to 6 years old and this is the best example that I found.
In this example the author uses a regex to find the end of each tweet and split them into different records. In my case I didn't find a way to split the stream of meetUp events.
Here is my code:
get '/' do STREAMING_URL = 'http://stream.meetup.com/2/open_events' http = EM::HttpRequest.new(STREAMING_URL).get buffer = "" http.stream do |chunk| buffer += chunk while event = buffer.slice!(/{\"utc_offset\"+.../) eventRecord = event puts eventRecord end end
I open the conection calling to //stream.meetup.com/2/open_events and I start to receive an stream of strings randomly cutted with this format:
{"utc_offset":-14400000,"venue":{"country":"us","city":"Novi","address_1":"43155 Main St Suite 2300N","name":"Game of Clues Escape Room","lon":-83.470833,"state":"MI","lat":42.478107},"rsvp_limit":0,"venue_visibility":"public","visibility":"public","maybe_rsvp_count":0,"description":"<p>Search the Emerald City for clues to help you solve riddles and puzzles to escape the room before the 60 minute timer is up. Work together to complete missions that will bring your group closer together in order to get a clue card.<\/p> \n<p>25.00 per person. Book online at www.gameofclues.com<\/p>","mtime":1467030326494,"event_url":"http:\/\/www.meetup.com\/Escape-Room-Lovers\/events\/232071150\/","yes_rsvp_count":1,"duration":3600000,"payment_required":"0","name":"Game of Clues Escape Room Novi,Mi","id":"232071150","time":1467507600000,"group":{"join_mode":"open","country":"us","city":"Novi","name":"Escape Room Lovers","group_lon":-83.52,"id":20101745,"state":"MI","urlname":"Escape-Room-Lovers","category":{"name":"games","id":11,"shortname":"games"},"group_lat":42.47},"status":"upcoming"}{"utc_offset":14400000,"venue":{"country":"ae","city":"Dubai","address_1":"Jumeirah Lake Towers, outside Dubai Marina Metro","name":"Illuminations Well-Being Center, 409, Fortune Executive Towers, Cluster T, Plot T1, ","lon":55.311668,"lat":25.264444},"rsvp_limit":0,"venue_visibility":"public","visibility":"public","maybe_rsvp_count":0,"description":"<p>Facilitator: Dr. Beryl Bazley<\/p> \n<p>Investment: Free!<\/p> \n<p>For more information call
I tryed to use .slice! over the content of buffer using as param "{"utc_offset"" which is the substring that appears at the beggining of each event but I couldn't figure out how to write the regex that gets everything enclosed between each apeareance of the substring to get as result the whole event.
Also I am not sure that adding the chunks to the variable buffer and then use of the method .slice! it's the best way of getting each event.
Which is the best way of solve this situation?
How can I slice and parse the data received via streaming API?
HERE I ADD THE IMPLEMENTATION OF THE SOLUTION SUGGESTED BY @jordan IN THE COMMENTS:
require 'yajl' require 'uri' require 'yajl/http_stream' @parser = Yajl::Parser.new(:symbolize_keys => true) STREAMING_URL = 'http://stream.meetup.com/2/open_events' Yajl::HttpStream.get(STREAMING_URL, :symbolize_keys => true) do |hash| puts hash.inspect hash.each {|key, value| puts "#{key} is #{value}" } end
-23362621 0 How to compare current time with old time in PHP I have stored date field at DB.
In PHP, i am getting that field and converted into date.
I want to compare that time with current time. If that difference is above 60 minutes. It will return some value.
I dont know how to write logic for that
$lastUpdatedField = $rows_fetch['lastUpdatedTime']; $lastUpdatedDate = new DateTime($lastUpdatedField); $nowDate = new DateTime(date('y-m-d h:m:s'));
I have old date&time is in $lastUpdatedDate variable, and current time is in $nowDate.
How to compare these two
-15608831 0You can set the NSWorkspaceDesktopImageScalingKey
in the option
parameter. Here's the possible values:
NSImageScaleProportionallyDown
If it is too large for the destination, scale the image down while preserving the aspect ratio.
NSImageScaleAxesIndependently
Scale each dimension to exactly fit destination. This setting does not preserve the aspect ratio of the image.
NSImageScaleNone
Do not scale the image.
NSImageScaleProportionallyUpOrDown
Scale the image to its maximum possible dimensions while both staying within the destination area and preserving its aspect ratio.
Declared in NSCell.h.
-33236419 0$( "input" ).keyup(function() { //It's changed });
Easy way to track any change in anywhere... Many framework with 2 ways data binding, use keyup in Javascript to $watch the changes...
Also jQuery UI date-picker has onSelect...So easy way to do ur job... look at https://jqueryui.com/datepicker for more information...
-23679059 0In this specific case i think there is a guarantee.
Some queries in Hive won't generate MR jobs and instead will IO the table directly in a serial way.
In your case, querying select * from table
will not generate a MR job (unless table
is a view).
Reading the table with a single process, reads from the first file to the last and from the head of each file to the end. hence, I believe that the order of the output in this way will be the same whenever you'll run the query.
This is of course not right in the case of MR jobs generated from the SQL.
-29278310 0The selector needs to be circle:nth-child(3)
-- the child
means that the element is the nth child, not to select the nth child of the element (see here).
You could also use:
// JS var data=[ 1,2,3,4,5,6,7,8,9 ]; var svg = d3.select("body").append("svg"); var circles = svg.append("g").attr("id", "groupOfCircles") .selectAll("circle") .data(data) .enter().append("circle") .attr("cx", function(d){ return d*20;}) .attr("cy", function(d){ return d*10;}) .attr("r" , function(d){ return d;}) .attr("fill","green"); d3.select("circle:nth-child(3)").attr("fill","red"); // <== CSS selector (DOM) d3.select(circles[0][4]).attr("fill","blue"); // <== D3 selector (node)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
if you want to use jQuery see below
<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script> </head> <body> <form id="form1" runat="server"> <script type="text/javascript"> $(document).ready(function () { if ($("#divItemDetails").text().length > 0) { $('#RepeaterDiv').show(); } }); </script> <div style="overflow: hidden; display: none" id="RepeaterDiv"> <asp:Repeater runat="server" ID="RepeaterID" DataSourceID="RepeaterDataSource"> <HeaderTemplate> All Names </br> </HeaderTemplate> <ItemTemplate> </br> <div id="divItemDetails"> <%# Container.DataItem%> </div> </br> </ItemTemplate> </asp:Repeater> <asp:ObjectDataSource runat="server" ID="RepeaterDataSource" SelectMethod="GetAllEmployees" TypeName="MyCustomBAL" /> </div> </form> </body> </html>
-37613874 0 The json u r passing is not proper. It has an extra comma ',' after price: 12.50. Even after second price element also an extra comma is added. Just remove it and it works fine.
-18900891 0 How to prevent Android App from crashing abruptlyI know this is a very broad question on how to prevent an Android app from crashing. I understand there could be many reason behind the app crashing.
Primarly my app crashed because of 2 main reasons :-
1) Out of memory while taking pictures and storing byte array in memory. I also uses bitmap to redraw the image captured.
2) Camera issues. App has a feature of autofocusing on touch events and while actually taking the pictures. These autofocus often crashes into each other. I have handled it using cancelling any existing autofocus code and discarding any further on touch events using flags once the picture is being captured. But still some time app crashes due to unknow reason.
There may be more reason behind app crashes. So my question is
1) Is there a way I can identify that app has crashed and handle that event so that instead of just showing the messsage ""UnForunately App has stopped working. Force Close." I can give a better user friendly message to user and stop the app programatically.
2) If out of memory every happens, is there a way I can identify that my App is running low on allocated memory and I can handle the scenario. OnLowMemory will give the low memory status of entire device, not just my application. I use lot of cache to store the images & heap for bitmap.
3) If the camera ever crashes (because of any reason), is there a way I can handle the scenario.
Thanks in advance. Gagan
-11364357 0 using getenv with respect to securityIf I use getenv()
to disable some verifications of my program (for instance license checking) will a hacker be able to discover easily the concerned environment variable (using strace or other ?)
Exemple of code:
if (! getenv("my_secret_env_variable")) checkLicense();
(If, on the other hand, I checked the presence of a specific file, the hacker would see it immediately with strace)
-14726896 0Using Racket:
(for/sum ([image image-list]) (image-height image))
or
(foldl (lambda (image sum) (+ (image-height image) sum)) 0 image-list)
or
(apply + (map image-height image-list))
-25904987 0 When you move the files to the production server you don't have to copy configuration.php that store the variable for robots in public $robots = '';
.
I highly recommend you to keep your development installation htaccess password protected to be sure that would never be accessed by search engines.
Hope this helps
-37154049 0There is an error in the placement of the 'projection' attribute. The answer below shows the correct one.
source: { type: "GeoJSON", geojson: { object: { type: "FeatureCollection", features: [{ type: "Feature", id: "TWN", properties: { name: "Taiwan" }, geometry: { type: "Point", coordinates: [25.038507, 121.525527] } }] }, projection: 'EPSG:4326', }
}
-23508121 0 Ajax button redirecting on Selenium webdriversI'm trying to test a site like sample and get different outcomes when clicking a button. When running selenium webdriver's --firefox and chrome-- I get redirected after this click:
@driver.find_element(css: "#shipping-zip-form .button.small").click
However, if i go to the site and run the following command in the console, I do not get redirected.
jQuery('#shipping-zip-form .button.small').click();
What is causing redirects to the homepage when running on through selenium? A thread.sleep command won't work and wait_until isn't working either. My guess is that something is happening too fast...
-36742016 0 Bash : Command line argument issue#usernamecheck.sh #!/bin/bsh DBUSER=user_1 DBPASSWORD=XXXXX DBSOURCENAME=database_1 DBNAME=database_1 DBNAME1=snapshot_v DBSERVER=X.X.X.X DBCONN="-h ${DBSERVER} -u ${DBUSER} --password=${DBPASSWORD}" echo "select user from device_id where ip='1.1.1.1'|mysql $DBCONN $DBNAME
The output of executing this script is:
user ---- JohnDoe
The above bash script which gives me user name of IP (1.1.1.1). I would like to pass the IP as a command line argument. I tried,
echo "select user from device_id where ip=$1|mysql $DBCONN $DBNAME
and executed like
$./usernamecheck.sh '1.1.1.1'
I get the error message:
Error in SQL syntax
Hope i'm passing the command line argument correct. But not sure, why does this error pop up?
-40020491 0The use of $xml
variable looks like it is loaded with SimpleXML extension. Suppose it is initialized like this:
$xml = simplexml_load_file('some-file.xml');
Then you just fetch attributes with attributes()
and check if the attribute is in the returned array:
foreach ($xml as $idof) { $attr = $idof->attributes(); if ($attr && $attr['mlssta'] != 6) { // remove it here } }
-4998548 0 Yes. The current working directory is a property of the process.
To expand on that a little - here are a couple of the relevant POSIX definitions:
The current working directory is defined as "a directory, associated with a process, that is used in pathname resolution for pathnames that do not begin with a slash character" (there is more detail in the section on pathname resolution).
chdir()
is defined to set the current working directory to a pathname.
It seems somewhat circular, but there is nothing special about a "pathname" in the context of the argument chdir()
; it is subject to pathname resolution as normal.
Although alert(some_array)
prints a string representation of the array, the array itself is not a string. Thus, it does not have .replace
. alert
is forced to convert it into a string because the alert box can only show characters.
You can simply join using a custom separator, though. join
is a function of arrays:
var all_boxes_values_clean = all_boxes_values.join(", ");
As a side note, I recommend console.log
over alert
because it:
[object Object]
you receive with alert
)There's several ways, but this is the simplest given what you are doing:
$(document).on("click", "ul.form-nav a", function(event) { event.preventDefault(); var id = event.target.href.replace(/^[^#]+/, ""); console.log("Going to: " + id); // Hide forms that do not have the selected id $('form.hidden').not(id).hide(); // Show the appropriate form $(id).show().focus(); });
View the Fiddle
-17309878 0Ideally, you would be able to specify an external "binding" for the env-entry. I know that's possible to do with WebSphere Application Server (via EnvEntry.Value properties), but I don't know if it's possible with Glassfish.
As a workaround, you could declare the env-entry for injection, and then check in PostConstruct whether any value was injected by the container (i.e., don't specify env-entry-value until you're deploying into the server). If you're using JNDI only, you can do the same thing with try/catch(NameNotFoundException).
@Resource(name="host") private String host; @PostConstruct public void postConstruct() { if (host == null) { // Not configured at deployment time. host = System.getProperty("test.host"); } }
-38014663 0 getApplicationContext() on a null object reference I allways get this java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
error while I run my app. I saw other answers but I didn't understand how to use those answer, I understood that there is some problem withe the context because there isn't call by Activity, so I also tried to pass the Activity context with no success... this is my code:
EDIT I already did your answers and it'snt worked, so I deleted this becuase I thought it'snt the solution. Due to yours answers I updated the code(with context as parmerter to the Distance class >to MySingleton class...)
public class MainActivity extends AppCompatActivity { private Button b; private TextView t; private LocationManager locationManager; private LocationListener listener; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); t = (TextView) findViewById(R.id.textView); b = (Button) findViewById(R.id.button); locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); listener = new LocationListener() { @Override public void onLocationChanged(Location location) { Log.d("Co", "onLocationChanged"); Distance distance=new Distance(); t.setText("\n " + location.getLongitude() + " " + location.getLatitude()+"\n "+distance.getDistance(location)); Location l2=new Location(""); //float distance=location.distanceTo(l2); Log.d("Co", String.valueOf(distance)); } @Override public void onStatusChanged(String s, int i, Bundle bundle) { } @Override public void onProviderEnabled(String s) { } @Override public void onProviderDisabled(String s) { Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(i); } }; configure_button(); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode){ case 10: { configure_button(); Log.d("Co", "premmsioenChecks"); } break; default: break; } } public void configure_button(){ // first check for permissions if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.INTERNET} ,10); Log.d("Co", "premmsioen"); } return; } // this code won't execute IF permissions are not allowed, because in the line above there is return statement. b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //noinspection MissingPermission locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener); locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, listener); Log.d("Co", "onClick"); Location l2=new Location(""); } }); } }
public class Distance {
static String url = ""; static String result=""; public String getDistance(Location location,Context context) { Log.d("app","getDistance"); String origins=location.getLatitude()+","+location.getLongitude(); url="https://maps.googleapis.com/maps/api/distancematrix/json?&origins="+origins+"&destinations="+destinations; Log.d("URL",url); JsonObjectRequest jsObjRequest = new JsonObjectRequest (Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Log.d("app","onRespone"); String distance=getText(response); if (distance.contains("Error")) { result=distance; return; } else { if (distance.contains("km")) { int meters = Integer.parseInt(distance.replaceAll("[\\D]", "")) * 1000; result= "The distance is " + meters + " meters"; return; } Log.d("7", String.valueOf(Integer.parseInt(distance.replaceAll("[\\D]", "")))); result= "The distance is " + distance; } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.d("app","Error Respone"); } } ); MySingleton.getInstance(context).addToRequestque(jsObjRequest); return result; } public String getText(JSONObject response) { String text=""; try { JSONArray rows = response.getJSONArray("rows"); Log.d("1", rows.toString()); if(rows.toString().contains("[]")) return text="Error"; JSONObject elements = rows.getJSONObject(0); Log.d("2", elements.toString()); rows = elements.getJSONArray("elements"); Log.d("3", rows.toString()); elements = rows.getJSONObject(0); Log.d("4", elements.toString()); Log.d("Error1","Error is @"+elements.getString("status")); if( elements.getString("status").contains("OK")) { JSONObject d = elements.getJSONObject("distance"); Log.d("5", d.toString()); text = d.getString("text"); } else { Log.d("Error2", elements.getString("status")); text = "Error-" + elements.getString("status"); } } catch (JSONException e) { text="Some error ocuerd"; } return text; }
}
public class MySingleton { private static MySingleton mInstance; private RequestQueue requestQueue; public static Context mCtx; private MySingleton(Context context) { mCtx=context; requestQueue= getRequestQueue(); } public RequestQueue getRequestQueue() { if(requestQueue==null) { requestQueue = Volley.newRequestQueue(mCtx.getApplicationContext()); } return requestQueue; } public static synchronized MySingleton getInstance(Context context) { if(mInstance==null) { mInstance=new MySingleton(context); } return mInstance; } public <T> void addToRequestque(Request<T> request) { requestQueue.add(request); } }
and this is the logcat
06-24 16:19:26.771 25300-25300/com.example.elicahi.gateor D/Co: onClick 06-24 16:19:27.556 25300-25300/com.example.elicahi.gateor D/Co: onLocationChanged 06-24 16:19:27.579 25300-25300/com.example.elicahi.gateor D/AndroidRuntime: Shutting down VM 06-24 16:19:27.579 25300-25300/com.example.elicahi.gateor E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.elicahi.gateor, PID: 25300 java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:107) at com.example.elicahi.gateor.MySingleton.getRequestQueue(MySingleton.java:24) at com.example.elicahi.gateor.MySingleton.<init>(MySingleton.java:19) at com.example.elicahi.gateor.MySingleton.getInstance(MySingleton.java:32) at com.example.elicahi.gateor.Distance.getDistance(Distance.java:79) at com.example.elicahi.gateor.MainActivity$1.onLocationChanged(MainActivity.java:54) at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:285) at android.location.LocationManager$ListenerTransport.-wrap0(LocationManager.java) at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:230) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
-25251540 0 You will need to set the flag called ecoReinstallInstalled (Installshield help does not mentioned this keyword) which is referred to in the document titled “Using Chained MSI Packages to Componentize Your Windows Installer Setup”.
Basically, you change the ‘option’ column of the ISChainPackage table of the specified chained MSI by adding the value 16 to the current value. If the value is less than 16; for example, the value is 0, replace it with 16; if the value is 1, replace it with 17 and so on. The option value determines the UI Level mode (the mode in which the chained MSI will run); 0 for Basic UI, 1 for No UI, value 16 or above will allow the chained MSI to re-run after it has been already installed.
If this does not work, which it should you need to check the chained MSI's log file by modifying the property IS_CHAINER_POST_COMMANDLINE, you could also try running the chained MSI in ui mode to see what the behaviour is.
Interestingly what alternative did you use instead of the Chained MSI functionality?
Look at my blog which by the way web page is work in progress:
http://installdeploy.com/wordpress/blog/
-38238429 0You can define a class like this:
class Stack { private: int stack[MAX_STACK]; int MIN_STACK = 0; public: . . . }
The push function can be implemented as follows:
When you increment the value of MIN_STACK before inserting, you always leave stack[0] empty and waste the space. Also use MIN_STACK
as your index and not MAX_STACK
as the value of MAX_STACK
is always 10.
void PUSH(int val) { if(MIN_STACK < MAX_STACK) { stack[MIN_STACK++] = val; /* Here MIN_STACK is incremented after insertion. It is the same as stack[MIN_STACK] = val; MIN_STACK +=1; */ } else cout << "Full stack!" << endl; }
In POP function, you have nothing to delete if MIN_STACK
is 0 because each time you push a value MIN_STACK
is incremented.MIN_STACK
always points to the next free location. SO the data to be popped out is in (MIN_STACK-1)
th position. So decrement the MIN_PATH
and use it.
void POP() { int aux; if(MIN_STACK > 0) { aux = stack[--MIN_STACK]; /* Here MIN_STACK is decremented before popping out. It is the same as MIN_STACK -= 1; aux = stack[MIN_STACK]; */ cout << " POP : " << aux << endl; } else cout << "Empty stack!" << endl; }
In your cpp
file create an object of the class as:
Stack S1; S1.PUSH(elm); S1.POP();
-35801898 0 Here is how I solved the problem, just in case somebody has a similar problem:
Take another approach, instead of joining first, then searching I chose to search first, then to join:
#INSTEAD OF COALESCE(tr2.text, tr1.text) AS description #AND MATCH(description) AGAINST(?) AS relevance_description #USE GREATEST( MATCH(tr2.text) AGAINST(?), MATCH(tr1.text) AGAINST(?) ) AS relevance_description
-35803727 0 I finally got to find out the issue I was facing. It was indeed an Oracle issue after the upgrade to Oracle 12C. We talked to the Oracle Support and they responded back with the below: Queries involving hash joins were returning wrong results in cases where hash join would receive row sets as input and produced one row at a time as output.
Because of this, the query was becoming indeterministic and giving different counts at different instances. When the query was running in SQL Developer with where clause, SQL developer was providing a different output because of where clause, since it was changing the plan of execution but when I was pasting it in Excel and then filtering, it was showing different values since in this case, the query plan was different since there was no where clause.
Sorry if my question caused any kind of confusion. I just wanted to confirm if it was something else before asking DBA to reach out to the Oracle Support regarding this.
-4892227 0Linux already has a kernel process that is zeroing memory using idle cycles so it will have memory ready to hand to processes that request it.
Your loop may or may not zero different memory depending on the particular malloc
implementation. If you really want to write a process like you describe, look into using sbrk
directly to ensure you're cycling memory in and out of your process. I bet if you check you'll find every byte given to you by sbrk
is already zero, though.
Ive made a web page with quite extensive JavaScript. Its runs fine in my browser and in my iPhone simulator. However on my iPhone 3G its very sluggish. My iPhone is pretty buggy though and often freezes for no reason so I dont know if its just my device or too much / bad code.
Other than using lots of devices (might be difficult to get my hands on), is there a good way to test this? Thanks
-31630060 0it depends on your own style.
In fact, a class which inherits from an abstract class has to use ALL attributes and methods of it - it is nearly impossible to create a clean architecture with many levels of inheritance.
The main advantage of interfaces is the flexibility - you can implement much of them but do not have to change the internal structure of your class to implement them.
In most cases, it is best practice to use interfaces, except in some software patterns like compositum or strategy pattern.
But at the end it is your decision - you have to choose the type of inheritance you want in your project.
Interfaces help you to gain flexibility, abstract classes bring more cohesiveness to your architecture because they group classes that are similar together. --> you can reuse your code of the abstract classes in its subclasses
-212308 0It turns out that FindControl does work:
CType(MyListView.FindControl("litTotal"), Literal).Text = GetTheSum()
I'd still like to know if there might be a better way though.
-36135775 0 In Java, how do I find out what is my maximum heap size?I have the following class in Java :
public class MemoryUsage { public static void main(String[] args) { Vector v = new Vector(); while (true) { byte b[] = new byte[1048576]; try { Thread.sleep(200); } catch (InterruptedException ie){} v.add(b); Runtime rt = Runtime.getRuntime(); System.out.println( "free memory: " + rt.freeMemory() ); } } public void showCurrentTime() { long time = System.currentTimeMillis(); System.out.println(time); } }
And I want to limit how much memory can be used by this program. I tried to set an initial and maximum size (from command-line), like follows :
C:\JMX_code\Memory_test>java -Xms2m -Xmx4068M MemoryUsage Error occurred during initialization of VM The size of the object heap + VM data exceeds the maximum representable size
But this doesn't work. How do I figure out what is my own maximum heap size ?
My Java version info. is as follows :
-18469152 0 clang 3.3 and constexpr constraintsJava(TM) SE Runtime Environment (build 1.7.0_02-b13) Java HotSpot(TM) 64-Bit Server VM (build 22.0-b10, mixed mode)
I'm compiling some code with clang 3.3 that seems to compile fine with gcc 4.8:
The original code was:
template <std::size_t N> struct helper { typedef void type; }; template <> struct helper<64> { typedef int64_t type; }; template <> struct helper<32> { typedef int32_t type; }; template <> struct helper<16> { typedef int16_t type; }; template <> struct helper<8> { typedef int8_t type; }; template <std::size_t I, std::size_t F> struct test { typedef typename helper<I+F>::type value_type; static constexpr std::size_t frac_mask = ~((~value_type(0)) << F); };
In clang, if I attempt to declare test<16,16> or test<8,0> I get the error:
test.cpp:41:34: error: constexpr variable 'frac_mask' must be initialized by a constant expression
static constexpr std::size_t frac_mask = ~((~value_type(0)) << F);
Playing around with it, if I convert the code to:
template <std::size_t I, std::size_t F> struct test { typedef typename helper<I+F>::type value_type; typedef typename std::make_unsigned<value_type>::type mask_type; static constexpr mask_type frac_mask = ~((~mask_type(0)) << F); };
It compiles in most cases (values of I, F), but if I declare test<8, 0>, I get the error:
test.cpp:23:36: error: constexpr variable 'frac_mask' must be initialized by a constant expression
test.cpp:66:15: note: in instantiation of template class 'test<8, 0>' requested here
test.cpp:23:66: note: left shift of negative value -1
static constexpr mask_type frac_mask = ~((~mask_type(0)) << F);
My question is - is there some rules I'm violating here in terms of the specification of constexpr? Also, for the last error - mask type is unsigned - is this a compiler issue that it thinks I'm shifting a negative value or am I misreading the code?
-13230640 0 How to obtain just particular lines of summary on lm objectThis problem comes from easier problem which I managed to solve myself. So here is my original question.
In my data I have lots of categories, but i'm not interested in estimating coefficients for all of them, I just want to test the hypothesis, that there is no difference in categories. And calling summary
on my object produces most information that I don't need for my report.
set.seed(42) dat <- data.frame(cat=factor(sample(1:10, 100, replace=T)), y=rnorm(100)) l1 <- lm(y~cat-1, data=dat) summary(l1)
How do I extract only the last line from call to summary(l1)
?
In this particular case I can just used anova
function
anova(l1)
and got only the info that I needed, just in different formatting than summary(l1)
produces.
What if I have some kind of a summary on an object and I want to extract just particular part of summary(object)
how do I do that? For example, how do I get R
to print only the line of call summary(l1)
?
p.s. I am aware of summary(l1)$fstatistic
.
You could use the row_number
function to partition by Name and Parent, like:
select * from ( select row_number() over (partition by Name, Parent order by Name, Parent) as rn , * from YourTable ) sub where rn = 1 -- Only first row for a name/parent combination
If you're looking to select only rows that are unique, in the sense that no other rows with the same name and parent exist, try:
select * from YourTable a where ( select count(*) from YourTable b where a.Name = b.Name and a.Parent = b.Parent ) = 1
-29343147 0 How to deal with big JSON file in R? I have a JSON file sizing in 500mb, and need to process it in R using fromJSON.
I've tried bigmemory packages but still failed. Either crashed or reached the memory limits.
Some code I had used like these
raw<- big.matrix(unlist(fromJSON("data.json")), ncol=24, type='integer', init=2, backingfile='data.bin')
other information Win 8 64bit, memory of 6GB, R version 3.1.3
here are some lines of the JSON file
["UPGRADE(ONLINE)", "20150223", "5693", "000000", "FR", "fr-fr", "STARADDICT II Plus", "4.0.4", 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0]
-39785628 0 There are 2 options:
As of now, sqoop export is very limited (thinking because this is not much intended functionality but other way around), it gives only option to specify the --export-dir
which is the table's warehouse directory. And it loads all columns. So you may need to load into a staging table & load it into the original base table with relevant column mapping.
You can export the data from Hive using:
INSERT OVERWRITE DIRECTORY '/user/hive_exp/orders' select column1, column2 from hivetable;
Then use the Oracle's native import tool. This gives more flexibility.
Please update if you have a better solution.
-2815239 0You are trying to access the variable which is cell array in MATLAB. Are you sure the data are stored consequently? What happens if you put double array into the structure?
matrixStruct = struct('matrix', [4, 4, 4; 5, 5, 5; 6, 6 ,6])
I think the problem is how MATLAB stores data in cell array. Try to run this:
double1 = 1; double2 = 1:2; cellempty = {[]}; celldouble1 = {1}; celldouble2 = {1:2}; cell2doubles = {1,2}; whos
The output:
Name Size Bytes Class Attributes cell2doubles 1x2 136 cell celldouble1 1x1 68 cell celldouble2 1x1 76 cell cellempty 1x1 60 cell double1 1x1 8 double double2 1x2 16 double
You can see that each element of cell array occupy additional 60 bytes to the size of numbers.
-16245662 0 Entity Framework Inheritance vs TablesOk I am very new to creating databases with Entity in mind.
I have a Master table which is going to have:
departmentID functionID processID procedureID
Each of those ID's need to point to a specific list of information. Which is name, description and owner of course they link back to each ID in the master table.
My question is, should I make 4 separate tables or create one table since the information is the same in all the tables except one.
The procedureID
will actually need to have an extra field for documentID
to point to a specific document.
Is it possible and a good idea to make one table and add some inheritance, or is it better to make 4 separate tables?
-34326354 0Solved, after change all linking to CSS :
<!-- Bootstrap Core CSS --> <link href="<?php echo base_url();?>public/css/bootstrap.min.css" rel="stylesheet"> <!-- Custom CSS --> <link href="<?php echo base_url(); ?>public/css/shop-homepage.css" rel="stylesheet">
and change config.php
to :
$config['base_url'] = 'http://localhost/cidlab';
Refer to here and Thanks to Google Chrome
-37198518 0 Excel VBA - my findnext in my selcted range is not workinghello if there is any who can help with this issue
I have a range of groups 1 to many (up to 12 rows - one row after an other per group) the initial part of the string as repeated I do not know how time they are repeated but ever time they are I need extract the relevant data which is everything after the repeated string. Now not all 12 row are in the group sometimes there are 11 or less but they are no blank rows in the group of data so what I do is once I find my header row I call a subroutine to go through the block of data and do my extraction, but when I get back and use the .findnext(v) it will not go to the next header
With big_rng ' this is column A selected Set v = .Find("Submarket:", LookIn:=xlValues, LookAt:=xlPart) If Not v Is Nothing Then firstAddress = c.Row Do Call this1(need, c.Row, tech, daily_date) Set v = .FindNext(v) need = need + 1 Loop While Not c Is Nothing And c.Address <> firstAddress End If End With
When I call this1 what I am doing is selecting another range because I do not know if my data is in the correct order I use another selection
Cells(i, 1).Select ' I know which row my group starts and I select down Range(Selection, Selection.End(xlDown)).Select ' check for substrings and copy across if the substring exists e.g. With Selection Set d = .Find("Degradation =", LookIn:=xlValues, LookAt:=xlPart) If Not d Is Nothing Then spos = InStrRev(Cells(d.Row, 1), "=") If Mid(Cells(d.Row, 1), spos + 1, 1) = " " Then output_sht.Cells(n, 5) = Right(Cells(d.Row, 1), Len(Cells(d.Row, 1)) - (spos + 1)) Else output_sht.Cells(n, 5) = Right(Cells(d.Row, 1), Len(Cells(d.Row, 1)) - spos) End If Else output_sht.Cells(n, 5) = "Error in Data" End If
when this Sub end my original selection is gone (it was column A:A), and my .findnext(v) gives me the last row of the previous group not the first row of the next group if one exists
how do I loop via findnext whilst keeping my original selection in tact
Thank you in advance
Robert
-29703600 0 threejs : error when deleting a Geometry or BufferGeometry in combination with a Sprite/Ortho cameraI load some objects using the ctm binary loader in Threejs r69. This returns Mesh objects using a BufferGeometry internally. I need to remove from the scene then delete one of these Meshes, including their material/texture/geometry. According to examples and google, I should use:
scene.remove(m_mesh); m_mesh.geometry.dispose(); m_mesh.geometry = null; m_mesh.material.dispose(); m_mesh.material = null; m_mesh = null;
This removes the object from the scene, but the screen goes black for a second, and I've got a GL error :
Error: WebGL: drawElements: no VBO bound to enabled vertex attrib index 2!
Looks like the above sequence (ran in my render() operation, just before drawing the scene) did not clean everything, or at least I still have references to non existing VBOs somewhere.
I've spent quite some time debugging the problem and came to the conclusion that this happens only when using an orthographic camera with a Sprite and a Perspective camera, in 2 differents scenes.
Basically, I draw a flat background using a Sprite and a dedicated scene, then my 3D scene with Meshes. If I delete a mesh from the 3D scene, then the drawing of the flat background fails. I can't figure out why. Looks like there's a side effect of deleting a Mesh on Sprites, even if attached to different scenes. If I comment the background drawing, then the deletion of my mesh works perfectly.
I insert below a reproduction of the problem using the standard threejs distribution. Wait about 5 seconds and you should see some GL errors on the jaavscript console.
<!DOCTYPE html> <html lang="en"> <head> <title>three.js webgl - geometries</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0"> <style> body { font-family: Monospace; background-color: #000; margin: 0px; overflow: hidden; } </style> </head> <body> <script src="build/three.min.js"></script> <script src="js/Detector.js"></script> <script src="js/libs/stats.min.js"></script> <script> if (!Detector.webgl) Detector.addGetWebGLMessage(); var container, stats; var camera, scene, renderer; frame_count = 0; init(); animate(); function init() { container = document.createElement('div'); document.body.appendChild(container); camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 2000); camera.position.y = 400; // I need a second camera for my 2D sprite (used as a background) // must use another texture so that it's not destroyed when removing the first object cameraOrtho = new THREE.OrthographicCamera(window.innerWidth / -2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / -2, 1, 10); cameraOrtho.position.z = 10; cameraOrtho.position.y = 400; sceneBackground = new THREE.Scene(); var map1 = THREE.ImageUtils.loadTexture('textures/disturb.jpg'); var material1 = new THREE.SpriteMaterial({ map: map1 }); var spriteBackground = new THREE.Sprite(material1); spriteBackground.scale.set(window.innerWidth, window.innerHeight, 1); spriteBackground.position.set(window.innerWidth / 2, window.innerHeight / 2); sceneBackground.add(spriteBackground); scene = new THREE.Scene(); var light; my_object = null; scene.add(new THREE.AmbientLight(0x404040)); light = new THREE.DirectionalLight(0xffffff); light.position.set(0, 1, 0); scene.add(light); var map = THREE.ImageUtils.loadTexture('textures/UV_Grid_Sm.jpg'); map.wrapS = map.wrapT = THREE.RepeatWrapping; map.anisotropy = 16; var material = new THREE.MeshLambertMaterial({ map: map, side: THREE.DoubleSide }); // one object is enough to demonstrate // can't reproduce the problem with a standard SphereGeometry // try to convert it to a BufferGeometry var sphereGeometry = new THREE.SphereGeometry(75, 20, 10); var bufferGeometry = new THREE.BufferGeometry().fromGeometry(sphereGeometry); my_object = new THREE.Mesh(bufferGeometry, material); my_object.position.set(-400, 0, 200); scene.add(my_object); renderer = new THREE.WebGLRenderer({ antialias: true }); renderer.setPixelRatio(window.devicePixelRatio); renderer.setSize(window.innerWidth, window.innerHeight); renderer.autoClear = false; renderer.autoClearDepth = false; container.appendChild(renderer.domElement); stats = new Stats(); stats.domElement.style.position = 'absolute'; stats.domElement.style.top = '0px'; container.appendChild(stats.domElement); window.addEventListener('resize', onWindowResize, false); } function onWindowResize() { camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); renderer.setSize(window.innerWidth, window.innerHeight); } // function animate() { requestAnimationFrame(animate); render(); stats.update(); } function render() { frame_count++; var timer = Date.now() * 0.0001; camera.position.x = Math.cos(timer) * 800; camera.position.z = Math.sin(timer) * 800; camera.lookAt(scene.position); //after a few frames I want to destroy completely the object //means remove from the scene, remove texture, material, geometry //note that here it's a Geometry, not a BufferGeometry //may be different if (frame_count > 60 * 5) { if (my_object != null) { console.log("destroy object buffer"); scene.remove(my_object); my_object.material.map.dispose(); my_object.material.dispose(); my_object.geometry.dispose(); my_object = null; } } for (var i = 0, l = scene.children.length; i < l; i++) { var object = scene.children[i]; object.rotation.x = timer * 5; object.rotation.y = timer * 2.5; } renderer.render(sceneBackground, cameraOrtho); renderer.clearDepth(); renderer.render(scene, camera); } </script> </body> </html>
Any hints on how to fix this issue?
Thank you,
Pascal
-19131961 0YourActivity.this.runOnUiThread(new Runnable() { public void run() { //What you want to do, updating a UI in main thread ect. } });
you could also refer to another post HERE
-14825381 0LastCleared/Highest will always fire, because you never clear it.
Also what is the scope of your ClearAllIntervals() function? Is it possible that a new instance is getting created that doesn't remember the previous value of LastCleared?
Note that I haven't been able to find anything that documents that setInterval returns sequential numbers, as you seem to think it does. However, since setInterval doesn't "belong" to anybody, you can't override it to capture those interval id's.
Finally, I think AS3 in the later versions of the player has functionality to release loaded movies from memory, and it certainly has sand boxing that prevents loaded MC's from attaching themselves to anything in the loading MC.
-5071389 0 Flex Hero Playbook app fails to minimizeI am having an issue with a playbook app I am working on. This is the first one i've done using Flex Burrito Hero, and on the simulator I noticed that the app fails to minimize gracefully (when multi-tasking etc). Are there any resources for handling minimization or anything that could help guide me to debug whats going on with that?
-11251593 0Here is might suggestion, if not suitable please ignore it: use a self hosted service as @driis mentioned. That is your best option for your scenario. The about hosting an HTML page inside your WCF service...yes it is possible but this is not a simple solution. To summarize in one sentence, you have to create your custom message formater and bypass the default one provided by WCF. You would create an HtmlBehavior which must inherit from WebHttpBehavior, HtmlBehaviorExtension which must inherit from BehaviorExtensionElement and finally a HtmlFormater which would implement IDispatchMessageFormatter. On the following link you will find a great article about custom formatters: http://blogs.msdn.com/b/carlosfigueira/archive/2011/05/03/wcf-extensibility-message-formatters.aspx
-33386700 0First of all you should use table to store the values you have in your IN
list and then join against that. If this is transient data, you could use temporary table.
CREATE TEMPORARY TABLE t1 (yourid VARCHAR(9) PRIMARY KEY); INSERT IGNORE INTO t1 VALUES ('44089839'),('44089839'),('44089839'),('44089839'), ('44089839'),('44089839'),('44089839'),('44089839'), ('44089839'),('44089839'),('44089839'),('44089839'), ('44089839'),('44089839'),('44089839'),('44089839'), ('44089839'),('44089839'),('44089839'),('44089839'), ('44089839'),('44089839'),('44089839'),('44089839'), ('44089839'),('96611525'),('96611525'),('96611525'), ('96611525'),('96611525'),('96611525'),('96611525'), ('96611525'),('96611525'),('96611525'),('96611525'), ('96611525'),('96611525'),('96611525'),('96611525'), ('96611525'),('96611525'),('96611525'),('96611525'), ('96611525'),('96611525'),('96611525'),('96611525'), ('96611525'),('96611525'),('96611525'),('96611525'), ('96611525'),('96611525'),('142061451'),('142061451'), ('142061451'),('142061451'),('142061451'),('142061451'), ('142061451'),('142061451'),('142061451'),('142061451'), ('142061451'),('142061451'),('142061451'),('142061451'), ('142061451'),('142061451'),('142061451'),('142061451'), ('142061451'),('142801551'),('142801551'),('142801551'), ('142801551'),('142801551'),('142801551'),('142801551'), ('142801551'),('142801551'),('142801551'),('142801551'), ('142801551'),('142801551'),('142801551'),('142801551'), ('142801551'),('142801551'),('142801551'),('142801551'), ('142801551'),('142801551'),('142801551'),('143381529'), ('143381529'),('143381529'),('143381529'),('143381529'), ('143381529'),('147713054'),('147713054'),('147713054'), ('147713054'),('147713054'),('147713054'),('147713054'), ('148164398'),('148164398'),('148164398'),('148164398'), ('148164398'),('148164398'),('148164398'),('148164398'), ('148164398'),('148164398'),('148164398'),('148296160'), ('148296160'),('148296160'),('148296160'),('148296160'), ('148296160'),('151063722'),('151063722'),('151063722'), ('151063722'),('151063722'),('151063722'),('151063722'), ('151063722'),('151063722'),('151063722'),('151063722'), ('151063722'),('151063722'),('151063722'),('151063722'), ('151063722'),('151063722'),('151063722'),('151063722'), ('151063722'),('151063722'),('153933372'),('153933372'), ('153933372'),('153933372'),('153933372'),('153933372'), ('154447237'),('154447237'),('154447237'),('154447237'), ('154447237'),('154447237'),('154447237'),('158137781'), ('158137781'),('158137781'),('158137781'),('158137781'), ('158137781'),('158217358'),('158217358'),('158217358'), ('158217358'),('158217358'),('158217358'),('158217358'), ('158217358'),('158217358'),('158217358'),('158217358'), ('158217358'),('158217358'),('158246547'),('158246547'), ('158246547'),('158246547'),('158246547'),('158246547'), ('158246547'),('158246547'),('158246547'),('158246547'), ('158246547'),('158246547'),('158246547'),('158246547'), ('158246547'),('158246547'),('158246547'),('158246547'), ('158246547'),('158246547'),('158246547'),('160734561'), ('160734561'),('160734561'),('160734561'),('160734561'), ('160734561'),('162435844'),('162435844'),('162435844'), ('162435844'),('162435844'),('162435844'),('162435844'), ('162435844'),('162435844'),('162435844'),('162435844'), ('162435844'),('162435844'),('163784258'),('163784258'), ('163784258'),('163784258'),('163784258'),('163784258'), ('163784258'),('163784258'),('163784258'),('163784258'), ('163784258'),('163784258'),('163784258'),('163784258'), ('163784258'),('163784258'),('163784258'),('163784258'), ('163784258'),('163800813'),('163800813'),('163800813'), ('163800813'),('163800813'),('163800813'),('163800813'), ('163800813'),('163800813'),('163800813'),('163800813'), ('163803246'),('163803246'),('163803246'),('163803246'), ('163803246'),('163803246'),('164617535'),('164617535'), ('164617535'),('164617535'),('164617535'),('164617535'), ('164617535'),('164617535'),('164617535'),('164617535'), ('164617535'),('164617535'),('164617535'),('164617535'), ('164617535'),('164617535'),('164617535'),('164617535'), ('164617535'),('164617535'),('164617535');
Above statement creates the temporary table, inserts data into it and also removes all the duplicates.
Once that's done, then you just use your table in you query:
SELECT id,kdt_id,kdt_goods_id,fx_price,min_retail_price,max_retail_price,fx_count,stock_num,sold_num,recommend_level,is_display,is_delete,quit_time, review_status,fx_auth,level_discount_auth,is_fx_delete,sold_status FROM apple_goods JOIN t1 ON (yourid=kdt_goods_id);
I'd also suggest that you match types in your temporary table and columns you JOIN
against, e.g. if kdt_goods_id
is INT
then yourid
in your temporary table should be INT
.
In actionDelete I have write query for get fk from all table and create activeDataProvider.and write a foreach loop for geting one by one element.
$query = new \yii\db\Query; $query->select('practiceCode')->from('member','plan','offer','appointment','product','incentive','clinic','complaint') ->where(['practiceCode' => $model->practiceCode])->all(); $query->createCommand(); $dataProvider= new ActiveDataProvider([ 'query' => $query, 'pagination' => false, ]); $models = $dataProvider->getModels(); if(count($models) >= 1) { $memberModel = new Member(); foreach ($models as $k) { $k['deleted'] = 'Y'; //$memberModel->save(); $connection->createCommand()->update('member', ['deleted' => 'Y'], ['practiceCode' => $models['practiceCode']])->execute();
Now it's work Doing same think for all table one by one
} return $this->redirect(['index']);
I am troubling with how save this Flag 'Y' in all table where this practiceCode as foreign key.Please help how to do....Thanks in advance
-16472086 0 How to repaint GUI after a certain element was removed?I'm making an app where a user would be able to add a button to the screen or remove it (I don't have those options implemented yet). So, for now I'm manually populating it with a for() loop and manually removing one of the buttons. My problem is that after the button has been removed (the removal action in the main()), there's just a blank spot. I want to be able to repaint the screen after I remove one of those buttons. In this example, index 2 (block #3) has been removed, leaving an empty space, where it was before... and I have no idea how to repaint it. I've tried validating or repainting from different places in the program with no success.
Here's the code (P.S. I'm sure my code is not the most efficient way to accomplish what I'm trying to and I'm using setLayout(null), which is not a preferred method, but for now I'm just trying to learn certain things and then expand on that to better myself and my code):
import java.awt.Color; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.LineBorder; class TestApp extends JFrame{ JFrame frame = new JFrame("Test Program"); ArrayList<JButton> grid = new ArrayList<JButton>(); private int w = 14; private static int amount = 102; private static int counter = 0; //Default Constructor (sets up JFrame) TestApp(){ frame.setLayout(null); frame.setPreferredSize(new Dimension(1186, 880)); frame.setDefaultCloseOperation(EXIT_ON_CLOSE); frame.setResizable(false); paintGrid(); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } public void newWindow() { JFrame select_win = new JFrame("Selected Frame"); JPanel select_panel = new JPanel(); select_panel.setPreferredSize(new Dimension(600, 800)); select_panel.setBackground(Color.ORANGE); select_win.add(select_panel); select_win.pack(); select_win.setResizable(false); select_win.setVisible(true); select_win.setLocationRelativeTo(null); } private void paintGrid() { for(int i = 0, y = 4; i < ((amount / w) + (amount % w)); i++, y += 104) { for(int j = 0, x = 4; j < w && (counter < amount); j++, x += 84) { addBlock(counter, x, y); counter++; } } } //Adds a block private void addBlock(int index, int x, int y){ int height = 100; int width = 80; grid.add(new JButton("counter: " + (counter + 1))); (grid.get(index)).addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { javax.swing.SwingUtilities.invokeLater(new Runnable() { @Override public void run() { newWindow(); } }); } }); (grid.get(index)).setBorder(new LineBorder(Color.BLACK)); (grid.get(index)).setBackground(Color.YELLOW); (grid.get(index)).setVisible(true); (grid.get(index)).setBounds(x, y, width, height); frame.add(grid.get(index)); } //Removes a block private void removeBlock(int index){ frame.remove(grid.get(index)); grid.remove(index); amount--; counter--; } public static void main(String [] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { @Override public void run() { TestApp app = new TestApp(); //testing block removal app.removeBlock(2); } }); } }
-17805961 0 Using blank? or present? in model-scopes in Ruby on Rails In my model, I have several scopes defined such as:
scope :myScope1, where('myField IS NULL')
This works, but I don't need to check for 'Null' - I need to check for '.blank?' - because there are cases of non-nulls which are 'blank' in the DB, which I need to include. I can use '.blank?' in my class-defs (and do - and they work there), but I cannot use this in this current context.
I have not been able to find a syntax (of the non-depreciated variety) which will work for this. Thanks.
-28499938 0 Get content ofConsider the following stripped down part of some html code:
<section id ="test" contenteditable="true" ... > <h3> This is a header </h3> <p> Some stuff in here </p> <p> Some more stuff here </p> </section>
How do I get the <h3> and <p>
elements from the section and store it in a variable?
E.g.
var result = "<h3> This is a header </h3> <p> Some stuff in here </p> <p> Some more stuff here </p>"
Also is it possible to get linebreaks etc as well?
I've tried using jquery .val()
and JS document.getElementByID(..)
, but they both return the section element altogether.
The POSIX description of fdopendir()
says:
Upon calling closedir() the file descriptor shall be closed.
So the descriptor is likely to be closed by the time you call openat()
.
And this is from a typical Linux man page for fdopendir():
-18767688 0After a successful call to fdopendir(), fd is used internally by the implementation, and should not otherwise be used by the application.
https://github.com/CJKay/PolyCalc
This is a good start. They have stopped maintaining the project due to most browsers haveing calc available but works well. I have found a couple bugs and fixed them on my sites.
If anyone would like to know my fixes please contact me
-4680447 0You friendship relationship here seems to be symmetrical.
In this case, you should insert the friends' ids in strict order: say, least id
first, greatest id
second.
This will make one record per friendship, not depending on who befriended whom.
Use this query:
SELECT 1 FROM users_friends WHERE (user_id, friend_id) = (LEAST($user_id, $SESSION['user_id']), GREATEST($SESSION['user_id'], $user_id))
to check the friendship status, and this one:
INSERT INTO users_friends (user_id, friend_id) VALUES (LEAST($user_id, $SESSION['user_id']), GREATEST($SESSION['user_id'], $user_id))
to insert a new record.
-37721507 0Instead of mapping the result to a POJO, I would suggest creating entities for both classes and mapping them with the one to one annotation JPA provides:
@Entity public class User{ @Id private long id; @OneToOne @JoinColumn(name="GROUP_ID") private Group group; ... } @Entity public class Group{ @Id private long id; ... }
Update to reflect updated question: You could then use e.g. the Criteria-API (or named queries), to query these entities:
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(); Root user = criteriaQuery.from(User.class); criteriaQuery.where(criteriaBuilder.equal(user.get("id"), criteriaBuilder.parameter(Long.class, "id"))); Query query = entityManager.createQuery(criteriaQuery); query.setParameter("id", id); User result = (User)query.getSingleResult();
-8092026 0 Eventbus event order Morning,
I'm using the SimpleEvent
bus to send data from my centralized data reviver to the Widgets. This works really fine, I get one set of new Data form the server, the success method of the RPC call puts it on the Eventbus, each widget looks if the data is for it, if yes it 'displays' it, if not, it does nothing.There is only one data set per request and the widgets don't depend on other data being already sent.
Now I have a Tree widget. The child nodes of the Tree are created throw this data sets too, and this child nodes register itself to the Eventbus to revive the data for their child nodes. The data shall be received in on rush (for performance reasons obv), so I will get multiple data sets which are put on the Eventbus at the 'same time' (in a for loop). I only control the order in which they are put there (first the root, then the data for the first child......). How does the Eventbus now proceeds the events?
Current solution approaches:
Which solution would you prefer and why?
Regards, Stefan
PS: my favorite answer would be that 1. is the standard behavior of the Eventbus^^ PPS: The solution should also be working on when introducing Webworkers.
-40356674 0 WEB2PY: Displaying data from DB with JOIN but with some conditionI am having trouble with some logic.
db.service_request
, db.technician
and db.assigned
Service Request
can be assigned to a Technician
db.assigned
is where all assigned service_request
are saved together with the Technician
's IDservice_request
EXCEPT for the service_request
that was not assigned to the current logged In Technician
How someone please tell me how to make this work ?
What I have is this, I get all service request
that has been assigned
to the current logged in Technician
, but does not get all the other service request
that has not yet been assigned
.
query=db.service_request.id==db.assigns.sr_id query2=db.assigns.technician==user_id query4=((query)&(query2)) get_assigned=db(query4).select(orderby=~db.service_request.date_time)
-28822638 0 While Hackaholic's solution is excellent (and very functional-programming), here's an alternative using list comprehensions.
The key ingredient is zip(a,b,c)
, which returns a sequence of tuples containing the ith elements of a, b, c. As Joran Beasley mentions, your code will work just by adding zip
:
d = [] for i,j,k in zip(a,b,c): d.append(i+j+k)
From here it's pretty easy to get to the list comprehension version:
d = [i+j+k for i,j,k in zip(a,b,c)]
And in fact you don't even need to unpack the tuple as i, j, k
, instead you can sum the tuple directly:
d = [sum(tup) for tup in zip(a,b,c)]
-15128158 0 You can do this with the CSS sibling selector ~
, with the caveat that your hover element must come before the elements you want to style in the markup. You can display them in any order you like, though.
#one:hover ~ #three, #six:hover ~ #four { background-color: black; color: white; } #four { margin-left: -35px; } #six { left: 80px; position: relative; } .box { cursor: pointer; display: inline-block; height: 30px; line-height: 30px; margin: 5px; outline: 1px solid black; text-align: center; width: 30px; }
<p>Hover over 1 and 3 gets styled.</p> <div id="one" class="box">1</div><!-- --><div id="two" class="box">2</div><!-- --><div id="three" class="box">3</div> <!-- this works because 4 is after 6 in the markup, despite its display position --> <p>Hover over 6 and 4 gets styled.</p> <div id="six" class="box">6</div><!-- --><div id="four" class="box">4</div><!-- --><div id="five" class="box">5</div>
-10448180 0 Perhaps gpg cannot handle UNC paths. Try using PUSHD to temporarily change your directory to the UNC path
pushd \\shared_path gpg ... popd
-30495711 0 IOS - Have UITableViewCells scroll over UIView (like the shazam app) I have a UIView above my UITableView. When the user scrolls down I want the UIView to stay in place at the top of the screen and have the cells scroll over it. The first page of the Shazam app does what I want.
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{ if (self.tableView.contentOffset.y > 0) { CGRect newframe = self.publicTopView.frame; newframe.origin.y = -self.tableView.contentOffset.y; self.publicTopView.frame = newframe; }
}
This is what I've tried so far, but it doesn't do anything. Thanks
-14444503 1 Gmail IMAP is not returning uidsI am connecting to my gmail account via IMAP to sync some of my emails and parse them. Sometimes I need to download again some emails because I did some kind of fix and now gmail is not returning me the uids
of those emails in any way, here is some code to explain myself better:
typ, data = self.connection.uid('search', None, '(SINCE 14-Dec-2012 BEFORE 20-Dec-2012)') 17:05.55 > HJBM3 UID SEARCH (SINCE 14-Dec-2012 BEFORE 20-Dec-2012) 17:05.69 < * SEARCH 17:05.69 < HJBM3 OK SEARCH completed (Success) ('OK', [''])
I have a good bunch of emails on those dates including the ones I want to parse and it doesn't return anything, depending on the date it does return some uids so is not completely broken.
I decided to try if thunderbird synced correctly those emails and it got them no problem.
I am using the python 2.6 imaplib (version 2.58)
-19866392 0The answer is here
Uses CoreGraphics and uses 30~40% less memory.
#import <ImageIO/ImageIO.h> -(UIImage*) resizedImageToRect:(CGRect) thumbRect { CGImageRef imageRef = [inImage CGImage]; CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo(imageRef); // There's a wierdness with kCGImageAlphaNone and CGBitmapContextCreate // see Supported Pixel Formats in the Quartz 2D Programming Guide // Creating a Bitmap Graphics Context section // only RGB 8 bit images with alpha of kCGImageAlphaNoneSkipFirst, kCGImageAlphaNoneSkipLast, kCGImageAlphaPremultipliedFirst, // and kCGImageAlphaPremultipliedLast, with a few other oddball image kinds are supported // The images on input here are likely to be png or jpeg files if (alphaInfo == kCGImageAlphaNone) alphaInfo = kCGImageAlphaNoneSkipLast; // Build a bitmap context that's the size of the thumbRect CGContextRef bitmap = CGBitmapContextCreate( NULL, thumbRect.size.width, // width thumbRect.size.height, // height CGImageGetBitsPerComponent(imageRef), // really needs to always be 8 4 * thumbRect.size.width, // rowbytes CGImageGetColorSpace(imageRef), alphaInfo ); // Draw into the context, this scales the image CGContextDrawImage(bitmap, thumbRect, imageRef); // Get an image from the context and a UIImage CGImageRef ref = CGBitmapContextCreateImage(bitmap); UIImage* result = [UIImage imageWithCGImage:ref]; CGContextRelease(bitmap); // ok if NULL CGImageRelease(ref); return result; }
added as a category to UIImage.
-22551203 0 How to access Global Variables in CI am trying to populate global variables but it seems to not be working . Here is my code .
typedef struct Global_ { char values[3][40] }Global_t; //function file GBL_PTR = calloc (1, sizeof (Global_t)); memset(GBL_PTR.values,'\0',sizeof(GBL_PTR.values)); //opening a file and reading it sscanf(linebuf, "List of values %s , %s \n", GBL_PTR.values[0], GBL_PTR.values[1]); printf("Why dont i see these logs %s",GBM_PTR.values[1]);
I don't see any crashes , just no logs. The compiles fine. I am new to C, can someone let me know what am I missing here. The main idea is to access a global variable from my function. How do I do it?
-6265177 0Your syntax are correct but there is some problem with CSS overriding you can use !important to you class attribute
example :
<script> $(function(){ $(".breadcrumb a:first").addClass("itemhover"); }); </script> .itemhover{ color : red !important; }
-9861369 0 "aPosition" is not used in the shader code so the GLSL-compiler has optimized away the variable. Try using it in the gl_Position assignment and you will notice that it works.
gl_Position = uMVPMatrix * uTMatrix * aPosition;
-36203869 0 Mike from Fabric and Crashlytics here.
As you saw, Crashlytics by default includes Answers. If you don't want Answers enabled on your app, then you want to invoke CrashlyticsCore()
when building your app instead of Crashlytics
.
For example, have these as your imports:
import com.crashlytics.android.Crashlytics; import com.crashlytics.android.core.CrashlyticsCore; import io.fabric.sdk.android.Fabric;
Then when you initialize Fabric, use:
Fabric.with(this, new Crashlytics.Builder().core(new CrashlyticsCore.Builder().build()).build());
and that will initialize only the crash reporting side of things.
-1931770 0 If I'm not going to be saving data into an SQL database, where should I be saving it?I'm making an encyclopedia program of sorts similar to RAWR for World of Warcraft. I'm not going to be saving data de an SQL database, but I've been conditioned so hard to always do this when I'm sure there are alternatives for these lighter case uses.
For example, my program will have no creation of new data via user input, nor deletion of data via user input. Just a program that will display information that I code into it. Nothing more, nothing less.
Where should I save these things? By save I mean, store them for deployment when I release the program.
I'm mostly going to be saving just string variables and some videos/animation (see my other question)
Thanks for the help SO. As always, you guys rock!
-5495440 0 Instruction inside a While Loop MatlabWhat does this instruction vector=[vector,sum(othervector)]
does in matlab inside a while loop like:
vector=[]; while a - b ~= 0 othervector = sum(something') %returns a vector vector=[vector,sum(othervector)]; %it keeps a new vector? ... end vector=vector./100
-1374016 0 I personally use the ActionStack, it's not that resource intensive as they say, it only pushes one more action in the dispatcher, and from there pull the data from a Model and inject it to a named segment on the view.
-21331631 0Well the algorithm is as follows:
Let, P(N)
denote the number of trees possible with N
nodes. Let the indexes of the nodes be 1,2,3,...
Now, lets pick the root of the tree. Any of the given N
nodes can be the root. Say node i
has been picked as root. Then, all the elements to the left of i
in the inorder sequence must be in the left sub-tree
. Similarly, to the right.
So, total possibilities are: P(i-1)*P(N-i)
In the above expression i
varies from 1 to N
.
Hence we have,
P(N) = P(0)*P(N-1) + P(1)*P(N-2) + P(2)*P(N-3)....
The base cases will be:
P(0) = 1 P(1) = 1
Thus this can be solved by using Dynamic Programming
.
<asp:Label ID="lblAsgn" runat="server" Text='<%# FormatText(Eval("StatusId")) %>' />
where FormatText
could be a method in your code behind:
protected string FormatText(object o) { int value; if (int.Parse(o as string, out value) && value == 0) { return "NEW"; } return "OLD"; }
-23518974 0 Using Javascript and jQuery you could refresh the image at a given rate. When the image is loaded by browser you call reloadImage() which waits 100ms and then changes the source attribute for the image to a unique path, which prevents loading the image from browser cache memory.
HTML
<img id="myImage" src="filename.jpg" onload="reloadImage()"/>
Javascript
function reloadImage(){ setTimeout(function(){ $("#myImage").attr("src",'filename.jpg? + Math.random()) }, 100); }
-15084430 0 android 4.0.3 ScrollingTabContainerView NullPointerException Our Android Application randomly crashes (very hard to repro the issue) with the following stack trace . This is seen when the orientation of the device is changed from portrait to landscape from the logcat logs. Also this issue has been seen on devices with Android 4.0.3 version. So wanted to check if it is a known issue with 4.0.3? Not sure from the code how to debug this issue as the stack trace is entirely of Android platform with no involvement of App code.
02-21 17:44:01.761 E/UncaughtException( 3344): java.lang.NullPointerException 02-21 17:44:01.761 E/UncaughtException( 3344): at com.android.internal.widget.ScrollingTabContainerView.onItemSelected(ScrollingTabContainerView.java:352) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.widget.AdapterView.fireOnSelected(AdapterView.java:882) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.widget.AdapterView.selectionChanged(AdapterView.java:865) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.widget.AdapterView.checkSelectionChanged(AdapterView.java:1017) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.widget.AdapterView.handleDataChanged(AdapterView.java:999) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.widget.AbsSpinner.onMeasure(AbsSpinner.java:179) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.widget.Spinner.onMeasure(Spinner.java:285) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.view.View.measure(View.java:12723) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.widget.HorizontalScrollView.measureChildWithMargins(HorizontalScrollView.java:1159) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.widget.FrameLayout.onMeasure(FrameLayout.java:293) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.widget.HorizontalScrollView.onMeasure(HorizontalScrollView.java:303) 02-21 17:44:01.761 E/UncaughtException( 3344): at com.android.internal.widget.ScrollingTabContainerView.onMeasure(ScrollingTabContainerView.java:117) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.view.View.measure(View.java:12723) 02-21 17:44:01.761 E/UncaughtException( 3344): at com.android.internal.widget.ActionBarView.onMeasure(ActionBarView.java:878) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.view.View.measure(View.java:12723) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4698) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.widget.FrameLayout.onMeasure(FrameLayout.java:293) 02-21 17:44:01.761 E/UncaughtException( 3344): at com.android.internal.widget.ActionBarContainer.onMeasure(ActionBarContainer.java:173) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.view.View.measure(View.java:12723) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4698) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1369) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.widget.LinearLayout.measureVertical(LinearLayout.java:660) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.widget.LinearLayout.onMeasure(LinearLayout.java:553) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.view.View.measure(View.java:12723) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4698) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.widget.FrameLayout.onMeasure(FrameLayout.java:293) 02-21 17:44:01.761 E/UncaughtException( 3344): at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2092) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.view.View.measure(View.java:12723) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1064) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2442) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.os.Handler.dispatchMessage(Handler.java:99) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.os.Looper.loop(Looper.java:137) 02-21 17:44:01.761 E/UncaughtException( 3344): at android.app.ActivityThread.main(ActivityThread.java:4424) 02-21 17:44:01.761 E/UncaughtException( 3344): at java.lang.reflect.Method.invokeNative(Native Method) 02-21 17:44:01.761 E/UncaughtException( 3344): at java.lang.reflect.Method.invoke(Method.java:511) 02-21 17:44:01.761 E/UncaughtException( 3344): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 02-21 17:44:01.761 E/UncaughtException( 3344): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 02-21 17:44:01.761 E/UncaughtException( 3344): at dalvik.system.NativeStart.main(Native Method)
-28871154 0 WSO2 Agent "Cannot proceed the authentication" but website works fine I've gotten WSO2 working on the server. I can login through the management console and EMM, publisher, and store are all working. I can create a new user through the EMM dashboard, and the email is sent correctly. So everything is fine while using the website.
I'm using the sample APK that comes with WSO2 to do some development, but every time I try to register the app pops up "Authentication Failed - Cannot proceed the authentication. Please contact an administrator." And there is no output in the console when this happens.
If I put in the incorrect credentials I get a separate error, "Authentication Failed - Incorrect login information. Please try again." So I know my credentials are correct.
What does this mean? Is there another place to find more detailed logs?
-2732209 0you need to check if you are posting all the "posting fields".. some sites use security tokens or sessions ids to prevent bots from logging on their sites. anyway, you need to install Live HTTP headers firefox extension. open it and try to login manually, then see whats being posted actually when you press login button. after you get the values. add then to the first function and test again.
-14260777 0Its easiest to start with a black and white image (I used .png) 4 bytes are allocated to each pixel, the data of which you can get by using CgContextRef and CgContextDrawImage (I used the CGBitmapContextCreate method to populate an array of pixel data as well as create a black and white image from the edited data array. I averaged the rgb values for each pixel and then changed all pixel values to black or white (alpha == 255) depending on the average of rgb's.
Then you need to package every 8 pixels into 1 print byte (thus for a pixel of 4 bytes, look at a set of 32 bytes in the data array and set the binary values of the print byte on or off depending on whether a pixel is black (add pow(2, 7 - (position of pixel in 8 pixel sequence) ) or white (do nothing).
I converted a .png image to black and white .png and then to binary and printed the values on my screen. Try to keep the width of your .png in multiples of 8 or you'll have trouble (since you need to convert 8 bytes into 1 byte.
-8641622 0To join an array of strings into a single string by a separator (character which would be a string), you could use this method of NSArray
class:
NSArray* array = @[@"iPhone", @"iPad", @"iPod"]; NSString* query = [array componentsJoinedByString:@","];
By using this method, you won't need to drop the last extra comma (or whatever) because it won't add it to the final string.
-29093118 0 Windows - only the first entry of PATH-environment variable can be foundThe following problem with my PATH-environment variable I have for some time, and it's become untolerable annoying so I would appreciate help a lot.
The following is the content of my system environment variables, which is also the output of echo %PATH% on cmd-exe.
C:\MinGW\bin; C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin; C:\msys\1.0\bin; C:\Qt\5.3\msvc2013_64\bin; C:\Users\Public\Documents\Embarcadero\Studio\15.0\Bpl;C:\Program Files (x86)\Embarcadero\Studio\15.0\bin64;C:\Users\Public\Documents\Embarcadero\Studio\15.0\Bpl\Win64;C:\Program Files\doxygen\bin;%ANT_HOME%\bin; %JAVA_HOME%\bin; %M2_HOME%\bin; C:\Program Files (x86)\MiKTeX 2.8\miktex\bin; C:\Program Files\PDF Split And Merge Basic\bin; C:\Program Files\Microsoft\Web Platform Installer; C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\;C:\Program Files\Microsoft SQL Server\110\Tools\Binn;C:\Program Files (x86)\Windows Live\Shared;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\ATI Technologies\ATI.ACE\Core-Static;C:\Program Files\SlikSvn\bin;C:\Program Files (x86)\Windows Kits\8.1\Windows Performance Toolkit;C:\Program Files (x86)\Microsoft SDKs\TypeScript\1.0;C:\Program Files\Microsoft SQL Server\120\Tools\Binn\;C:\Program Files\doxygen\bin
The thing is now, that only the first entry of this can be used, i.e the command "g++" (which is in C:\MinGW\bin ) can be found, but already the command "cl" (which is in C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin) can't be found, and all subsequent commands also not.
What am I doing wrong?
-27761566 0As an alternative, you can use flatten with len:
from compiler.ast import flatten my_list = [[1,2,3],[3,5,[2,3]], [[3,2],[5,[4]]]] len(flatten(my_list)) 11
PS. thanks for @thefourtheye pointing out, please note:
Deprecated since version 2.6: The compiler package has been removed in Python 3.
-13747021 0This can be done with the collection method "find" as you did, but the selector must be a hash.
col = db.collection(main) record = col.find({:property => value})
Find also accepts an optional hash of options. Take a look at the documentation. http://api.mongodb.org/ruby/current/Mongo/Collection.html#find-instance_method
-34705370 0like this:
<select id="mySelectTV"><option>tv</option></select> //parent <select><option>model</option></select> //sub select var x = document.getElementById("mySelectTV"); var option = document.createElement("option"); option.text = "music chanel"; x.add(option);
OR using loop
var chanels = ['chanel 1', 'chanel 2', 'chanel 3']; var x = document.getElementById("mySelectTV"); var option = document.createElement("option"); for(var i=0; i< chanels.length; i++){ option.text = chanels[i] ; x.add(option); }
-40160996 0 Some dead containers were still running in the background. I removed all of them restarted and everything works now.
I removed them using,
docker ps --all | grep restml | cut -c138- | xargs docker rm
-22182388 0 Difference between P2 and P2 Update site in Nexus P2 proxy support So I've installed nexus p2 plugin.
It gives me two options when creating a proxy on a P2 Repository. P2 and P2 Update Site.
What is the difference between the two and when should I use one over the other?
-25587086 0Since they are inline, use white-space:nowrap
to prevent the list items from appearing on a new line.
.drop_menu { white-space:nowrap; } .drop_menu > li { white-space:normal; }
Since you don't want this to occur on the children li
elements, set the white-space
property value to normal
.
You can use the dictionary returned by a call to globals()
:
input_name = raw_input("Enter variable name:") # User enters "orange" globals()[input_name] = 4 print(orange)
If you don't want it defined as a global variable, you can use locals()
:
input_name = raw_input("Enter variable name:") # User enters "orange" locals()[input_name] = 4 print(orange)
-9162573 0 to create a jabber ID account , you need to run ejabberd server and fire on
http://www.mydomain.com:5280/register/
and click on Register a Jabber account to create jabber ID on your server
-4909325 0BTW, Microsoft no longer recommends that you derive from ApplicationException
. Derive directly from Exception
, instead.
Also, in your logging, be certain to log the entire exception. Use ex.ToString(), not ex.Message, etc. This will guarantee you see everything the exception class wants you to see, including all inner exceptions.
-23915835 1 Transition Matrix in Dataframe Not Passing the ValueI am trying to implement transition matrix.
Both data and transition matrix are in DataFrames using Pandas
states_mat = pd.DataFrame(None, index=range(0,24), columns=range(0,24)) def states_update(data): states_vec = data['hr'] # Do nothing if there is no sequence if len(states_vec) < 2: return for i in xrange(1, len(states_vec)): prev = states_vec[i-1] curr = states_vec[i] states_mat[curr][prev] += 1
Data are in int64 type
It is not updating +1 count as I wanted. I believe it is some kind of type issue, but not sure how to force the type. I am using DataFrame for my data as I want to use group function to split the data and apply the above function. Any suggestions?
-21105509 0 How to call struct from separate function?#include <iostream> #include <cmath> using namespace std; struct workers{ int ID; string name; string lastname; int date; }; bool check_ID(workers *people, workers &guy); void check_something(workers *people, workers &guy, int& i); int main() { workers people[5]; for(int i = 0; i < 5; i++){ cin >> people[i].ID; cin >> people[i].name; cin >> people[i].lastname; cin >> people[i].date; if(check_ID(people, people[i]) == true) cout << "True" << endl; else cout << "False" << endl; check_something(people, people[i], i); } return 0; } bool check_ID(workers *people, workers &guy){ for(int i = 0; i < 5; i++){ if(people[i].ID == guy.ID) return true; break; } return false; } void check_something(workers *people, workers &guy, int& i){ check_ID(people, guy[i]); }
This is the code I have, it's not very good example, but I quickly wrote it to represent my problem I have because my project is kinda too big. So basically, I want to call struct from a different function and I'm getting this error: error: no match for 'operator[]' in guy[i]
on this line : check_ID(people, guy[i]);
in the function check_something
.
I'm using FPDF to create pdf. I need to insert image with Cufon font. I'm having cufon font in .js format. I read out , and i applied like,
<?php require('makefont/makefont.php'); MakeFont('c:\\Windows\\Fonts\\comic.ttf','cp1252'); ?>
No use. I need help.
font.js is like,
Cufon.registerFont({"w":168,"face":{"font-family":"BankScript","font-weight":400,"font-stretch":"normal","units-per-em":"360","panose-1":"2 0 5 6 0 0 0 2 0 4"
-9940604 0 How to do a callback between two projects? I am working in two java projects. The first supports OSGi components, second does not. The first depend to the second for logging.
My need is to add a callback in the second project from the first to recover a variable to add in the log.
-28507053 0No, you cannot use a regex as a case statement in C. In fact, C has no built-in support for any kind of regular expressions at all*. However, you can achieve the same result in terms of speed if you "expand" your regular expressions with fall-through:
switch (ch) { case '"'; case ';': case ',': case '(': case ')': case '{': case '}': case ' ': printf("\nSEPARATOR: %c found\n", ch); ch =fgetc(fin); break; case '_': case 'a': case 'b': ... // The other 24 letters go here case 'A': case 'B': ... // Same thing for uppercase letters case 'Z': printf("\nIDENTIFIER: "); ... }
Unfortunately, this would result in much longer code. You can convert it to a lookup table, though, which would be less readable, but run roughly as fast:
enum { OTHER , ID_START , DIGIT , SEPARATOR }; int map_char(unsigned char c) { static int *lookup_ptr = NULL; static int lookup[256]; if (lookup_ptr == NULL) { for (int i = 0 ; i != 256 ; i++) { if (i=='"; || i==';' || i==',' || ...) { lookup[i] = SEPARATOR; } else if (i=='_' || isalpha(i)) { lookup[i] = ID_START; } else if (isdigit(i)) { lookup[i] = DIGIT; } else { lookup[i] = OTHER; } } lookup_ptr = lookup; } return lookup_ptr[c]; }
Now you can use the function as follows:
switch (map_char(ch)) { case SEPARATOR: ... break; case ID_START: ... break; case DIGIT: ... break; case OTHER: ... break; }
* Square bracket syntax of scanf
functions only looks like regex, but it is not.
I think you use a Webkit browser like chrome, right? Chome does'n see a relation between two local files. Use Firefox or run it on a webserver ;)
"Origin null is not allowed by Access-Control-Allow-Origin" in Chrome. Why?
-22928320 0 jQuery, click event doesn't fireMy problem was (because I solved it, but I don't know why it worked): I had two 'span'
tags inside my DOM
with the same CSS
class. One span was added via AJAX request. I was trying to fire click event on them using:
$('.css class').on('click', function ...
but 'span'
tag that was added second (AJAX) didn't produce click event. When I've changed above line to:
jQuery('body').on('click', '.css class', function(e){...
everything started to work as it should. I don't know why.
-12843250 0Because of the space between the two +
, each +
is treated as a different token by the lexical analyzer.
I just realized that, you are not floating the other element, this is causing it to shift down, you should use float: left;
or right
as it's a div
so it will take up entire horizontal space, and hence it is pushed down.
.one, .two{ width: 300px; height: 450px; float:left; /* Float both elements */ background: #f00; }
Alternative
You should use display: inline-block;
and white-space: nowrap;
to prevent the wrapping of the elements
This will gave you the same effect, the only thing is 4px
white space, you can simply use
.two { margin-left: -4px; }
the above will fix the white space issue for you
-25247100 0what I'd advice you would be to first remove all unnecessary data from the line, so you get exactly what you're looking for:
addr = [ x for x in line.split(" ") if x ][2]
and then printout that value along with the values in your list:
for target in mac_addr: print("'{}' vs '{}' -> {}".format(addr, target, addr == target))
so you can check how they differ.
In the end:
with open('arp_table_output.txt','r+') as myArps: for line in myArps: # select *ONLY* the lines that contain the IP and MAC information in the input file if "Dynamic" in line: # here we extract the IP and the MAC from the line (python3 syntax) ip, _, mac, *_ = [ x for x in line.split(" ") if x ] # if you prefer python2: use `x, _, y, _, _, _ = …` # Test to printout what works and what does not. If none pass, the "in" test below will fail. for target in mac_addr: print("'{}' vs '{}' -> {}".format(mac, target, mac == target)) if mac in mac_addr: ipaddr.append(ip)
-1537113 0 This seems to be overcomplicating things somewhat: typically you would store an object's world position and orientation separately from its set of own local coordinates. Rotating the object is done in model space and therefore the position is unchanged. The world position of each coordinate is the same whether you do a rotation or not - add the world position to the local position to translate the local coordinates to world space.
Any rotation occurs around a specific origin, and the typical sin/cos formula presumes (0,0) is your origin. If the coordinate system in use doesn't currently have (0,0) as the origin, you must translate it to one that does, perform the rotation, then transform back. Usually model space is defined so that (0,0) is the origin for the model, making this step trivial.
-288180 0Try yahoo pipes.
-1821665 0There are certainly many options for this, but one that is very easy to implement and meets your criteria is an Asynchronous Web Service call.
This does not require you to start a worker thread (the Framework will do that behind the scenes). Rather than use one of the options outlined in that link to fetch the result, simply ignore the result since it is meaningless to the calling app.
-31844597 0The answer provided by @patricus above is absolutely correct, however, if like me you're looking to also benefit from casting out from JSON-encoded strings inside a pivot table then read on.
I believe that there's a bug in Laravel at this stage. The problem is that when you instantiate a pivot model, it uses the native Illuminate-Model setAttributes
method to "copy" the values of the pivot record table over to the pivot model.
This is fine for most attributes, but gets sticky when it sees the $casts
array contains a JSON-style cast - it actually double-encodes the data.
The way I overcame this is as follows:
1. Set up your own Pivot base class from which to extend your pivot subclasses (more on this in a bit)
2. In your new Pivot base class, redefine the setAttribute
method, commenting out the lines that handle JSON-castable attributes
class MyPivot extends Pivot { public function setAttribute($key, $value) { if ($this->hasSetMutator($key)) { $method = 'set'.studly_case($key).'Attribute'; return $this->{$method}($value); } elseif (in_array($key, $this->getDates()) && $value) { $value = $this->fromDateTime($value); } /* if ($this->isJsonCastable($key)) { $value = json_encode($value); } */ $this->attributes[$key] = $value; } }
This highlights the removal of the isJsonCastable
method call, which will return true
for any attributes you have casted as json
, array
, object
or collection
in your whizzy pivot subclasses.
3. Create your pivot subclasses using some sort of useful naming convention (I do {PivotTable}Pivot
e.g. FeatureProductPivot)
4. In your base model class, change/create your newPivot
method override to something a little more useful
Mine looks like this:
public function newPivot(Model $parent, array $attributes, $table, $exists) { $class = 'App\Models\\' . studly_case($table) . 'Pivot'; if ( class_exists( $class ) ) { return new $class($parent, $attributes, $table, $exists); } else { return parent::newPivot($parent, $attributes, $table, $exists); } }
Then just make sure you Models extend from your base model and you create your pivot-table "models" to suit your naming convention and voilà you will have working JSON casts on pivot table columns on the way out of the DB!
NB: This hasn't been thoroughly tested and may have problems saving back to the DB.
-11960453 0 What might I be doing wrong to get "Error: s > 0 is not TRUE" for a nlmer model?I am attempting to learn lme4, and I'll admit up front that my statistical academic training was in traditional ANOVA designs at the home of SAS (NC State) over 20 years ago. I now have about 4-5 years of experience with R, but mostly with traditional general linear models with all factors treated as fixed effects.
I now would like to estimate the parameters for a von Bertalanffy growth model for an experiment with fresh-water mussels. Shell length was measured once per year for 4 years on known individuals (ID), so this is a repeated measures design. Ultimately I would like to add a main treatment factor and a split-plot factor. But, at the moment I can't get the simplified model to run. The R code that I'm using is:
VBGF <- function(Linf, k, age, age.0) { Linf * (1-exp(-k*((age-age.0)))) } VBGF <- deriv(L ~ VBGF, namevec=c("Lin", "k", "age.0"), function.arg=VBGF) mod1 <- nlmer(L ~ VBGF(Linf,k,AGE,age.0) ~ (Linf+k+age.0|ID), mussels, start=c(50,0.1,-11), verbose=TRUE)
I get the following error, and I have been completely unsuccessful in finding a reference to what it means.
Error: s > 0 is not TRUE
It's probably something simple that I'm overlooking, so I apologize for my ignorance in advance.
-7444823 0 Jquery fading slideshow if statementHI I need to create a if statement for my slide show, if there is only one image I don't want the slideshow to be active;
Javascript:
<script type="text/javascript"> function slideSwitch() { var $active = $('#slideshow IMG.active'); if ( $active.length == 0 ) $active = $('#slideshow IMG:last'); // use this to pull the images in the order they appear in the markup var $next = $active.next().length ? $active.next() : $('#slideshow IMG:first'); // uncomment the 3 lines below to pull the images in random order // var $sibs = $active.siblings(); // var rndNum = Math.floor(Math.random() * $sibs.length ); // var $next = $( $sibs[ rndNum ] ); $active.addClass('last-active'); $next.css({opacity: 0.0}) .addClass('active') .animate({opacity: 1.0}, 1000, function() { $active.removeClass('active last-active'); }); } $(function() { setInterval( "slideSwitch()", 5000 ); }); </script>
html:
<div id="slideshow"> <img src="image1.jpg" class="active" />
JS is not really my strong suit, any help would be great!
-18053942 0You are passing the values through intent correctly. I think you are getting problems while getting the passed values. Try this and this works for me.
You have to use a bundle for getting the values.
Intent intent = new Intent(); Bundle b = intent.getExtras(); int addTaskID = b.getInt("AddTask_Id, 0);
-29044856 0 Embedding Youtube clip in rails app I have a you tube clip in my rails app. Profiles include video introductions.
I have a profile model with a youtube_url attribute.
I have a profile_helper with the following:
module ProfilesHelper def embed(youtube_url) youtube_id = youtube_url.split("=").last content_tag(:iframe, nil, src: "//www.youtube.com/embed/#{youtube_id}") end end <div class="embed-container"> <%= embed(profile.youtube_url) %> </div>
However, I get an error when I try to test this that identifies a problem with the embed line above:
undefined local variable or method `profile' for #<#<Class:0x00000103f434f0>:0x00000107f84f00>
My profiles controller has:
class ProfilesController < ApplicationController #decorates_assigned :profile before_action :authenticate_user! before_action :set_profile, only: [:show, :edit, :update, :destroy] # GET /profiles # GET /profiles.json def index @profiles = Profile.all end # GET /profiles/1 # GET /profiles/1.json def show end # GET /profiles/new def new @profile = Profile.new end # GET /profiles/1/edit def edit end # POST /profiles # POST /profiles.json def create @profile = Profile.new(profile_params) @profile.user = current_user respond_to do |format| if @profile.save format.html { redirect_to @profile, notice: 'Profile was successfully created.' } format.json { render action: 'show', status: :created, location: @profile } else format.html { render action: 'new' } format.json { render json: @profile.errors, status: :unprocessable_entity } end end end # PATCH/PUT /profiles/1 # PATCH/PUT /profiles/1.json def update respond_to do |format| if @profile.update(profile_params) format.html { redirect_to @profile, notice: 'Profile was successfully updated.' } format.json { head :no_content } else format.html { render action: 'edit' } format.json { render json: @profile.errors, status: :unprocessable_entity } end end end # DELETE /profiles/1 # DELETE /profiles/1.json def destroy @profile.destroy respond_to do |format| format.html { redirect_to profiles_url } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_profile @profile = Profile.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def profile_params params[:profile].permit( :title, :languages, :overview, :research_interests, :occupation, :about_me, :interested_in, :aspirations, :advice, :average_day, :like_to, :fyi_fact, :timezone, :image, :university_id, :link_to_external_profile, :youtube_url ) end end
Any ideas on what I've done wrong?
Thank you
-2172310 0McDowell is right, but note that you can get rid of prefix and start mode checks in your loop if you make them part of the WMI query:
SELECT * FROM Win32_Service WHERE Name LIKE 'TTTT%' AND StartMode = 'Manual'
Using this query, your script could look like this:
var strComputer = "."; var oWMI = GetObject("winmgmts://" + strComputer + "/root/CIMV2"); var colServices = oWMI.ExecQuery("SELECT * FROM Win32_Service WHERE Name LIKE 'TTTT%' AND StartMode = 'Manual'"); var enumServices = new Enumerator(colServices); for(; !enumServices.atEnd(); enumServices.moveNext()) { var oService = enumServices.item(); WScript.Echo(oService.Name); }
-34160508 0 How to assign output of compare command to a variable i have a problem with compare command.
I use this to output result to screen, but I receive nothing ( echo is empty ) but after executing command I obtain a numeric value
COMP=`compare -metric PSNR 00000003.jpg 00000004.jpg difference.png`<br> echo "$COMP"
I tried this:
OUTPUT="$(compare -metric PSNR 00000003.jpg 00000004.jpg difference.png)" echo "${OUTPUT}"
But it doesn't help
-9904192 0The way your code looks like now, you shouldn't get a warning since myclass
and myClassList
have the same lifetime. However, if myClassList
outlives myclass
, you need to dynamically allocate MyClass
:
vector<MyClass*> myClassList; { MyClass* myclass = new MyClass; myClassList.push_back(myclass); }
If the following is closer to what you actually have:
vector<MyClass*> myClassList; { MyClass myclass; myClassList.push_back(&myclass); }
then myclass
is destroyed at the closing }
, and myClassList
will contain a pointer to released memory.
Also, is MyClass
polymorphic? Do you really need to store pointers in the vector?
They are quite different in purpose.
OpenAL is a low level, cross-platform API for playing and controlling sounds.
AudioSession, as the documentation puts it, is a C interface for managing an application’s audio behavior in the context of other applications
. You may want to take a look at AVAudioSession which is a convenient Objective-C alternative to AudioSession.
You would typically use Audio Sessions for getting sound hardware information, determining if other applications are playing sounds, specifying what happens to those sounds when your application also tries to play sounds, etc.
Audio Sessions are all about managing the environment in which your application plays sounds. Even sounds played using OpenAL are subject to the rules imposed by your application's audio session.
You should really check out the docs. There is a lot to cover.
-30001768 0 Angular set ng-checked for specific child onclickIf someone clicks on the link the child input element should get the attribute ng-checked = "true" and if he clicks again it should be set false.
I already managed to implement this behaviour but the problem is that i have multiple checkbox probably around 20 and i do not want to set a unique variable for all of those
<a href="" ng-click="setSelect()"> <div class="checkbox"> <label> <input type="checkbox" ng-model="someModel" ng-checked= "selectStatus"> text </label> </div> </a>
and the according setSelect method
$scope.toggleSelect = true; $scope.setSelect = function () { if ($scope.toggleSelect){ $scope.selectStatus = true; $scope.toggleSelect = false; } else { $scope.selectStatus = false; $scope.toggleSelect = true; } };
is it possible to do this without jquery and in an easy way?
-21772610 0As Victor wrote, the sdk events are triggered by blobs, queues and tables.
A simple solution for your need: write a console application with a pollig approach. No sdk needed. Details at the beginning of http://blog.amitapple.com/post/73574681678/git-deploy-console-app/
while(true) { if ("isthereworktodo?") { var uow = new KirkleesDatabase.DAL.UnitOfWork(); uow.CommunicationRepository.SendPALSAppointmentReminders(); } Thread.Sleep(10000); // set an appropriate sleep interval }
-152857 0 As others already wrote, I believe this behavior is caused by the fact that the dialog starts its own event loop.
If you use Qt4, you can try using queued signal/slot connections as an alternative to posting events.
-26907956 0It seems that you are not using any input processor. Make your class implement InputProcessor and make your touchDown method look like this.
@Override touchDown(InputEvent event, float x, float y, int pointer, int button) { Vector3 input = new Vector3(x, y, 0); cam.unproject(input); if (ball.getBoundingCircle().contains(input.x, input.y)) { ballBounce(); } }
-6388973 0 View IE7 per-session cookies According to this answer, IE7 stores session cookies in memory and doesn't store them on the local filesystem.
Is there any way to view the session cookies that IE7 is currently storing in memory?
Thanks.
-8475202 0const int kPadding = 4; // Padding for the diference between the font's height and the line height - it's 2 for front and 2 for bottom float maxHeight = (FONT_SIZE+kPadding)*kNumberOfLinesYouNeed; CGSize labelSize = [yourString sizeWithFont:yourFont constrainedToSize:CGSizeMake(kYourNeededWidth, maxHeight) lineBreakMode:UILineBreakModeWordWrap]; youLabel.frame=CGRectMake(yourX, yourY, kYourNeededWidth, maxHeight);
I'm sorry for any mistakes. I have written this form my head.
-39030378 0Basically, the date/datetime properties in Eloquent are converted to Carbon object, so you can do it like this,
{{ $note->updated_at->format("l, h:i A") }}
-1897037 0 Xcode cannnot find my plist file when building I'm trying to build my app and every time I do I get this error:
error: The file "Wallpapers-Info.plist" does not exist.
Anyone know what causes this error? I have the wallpaper-info.plist file in my resources directory.
-1318338 0If you want to insert arbitrary markup in a template, then use structure
keyword:
<div tal:content="structure variable_that_contains_html"/>
but if you want to embed one PHPTAL template in another, then use macros:
macros.xhtml:
<div metal:define-macro="greeting">Hello World!</div>
page.xhtml:
<body><tal:block metal:use-macro="macros.xhtml/greeting"/></body>
-17750454 0 Try: location.href = location.origin + "/Process.aspx";
use ImageIO class
-2661485 0Not specific to iPhone. Just a thought:
How about ALPHA-blending the 2 images??
OR
-32074304 0 Dockerfile runs on Mac but won't run on Linux behind my proxyDisplay the 2 images one on top of the other (upper one being 50% transparent).
I have the following Dockerfile , for a container that runs just fine on my Mac, (I'm using docker-machine)
FROM perl:latest RUN cpanm SOAP::Lite RUN cpanm LWP::Simple COPY . /usr/src/myapp WORKDIR /usr/src/myapp ENTRYPOINT [ "perl", "./doceng_purge_tools/bin/akamai_purge_pattern_generic.pl" ] # CMD /bin/bash # docker build -t my_perl_purger_001 . # docker run -t my_perl_purger_001 -pattern cd/Q14299_01 -server prod
However, when I run it using docker on my corporate network. I get a low-level SSL error.
Forgive my ignorance, but I thought a feature of docker is that I can be shielded from these platform gotchas.
Is there a way I can package this up, on my Mac, and just run the container in my Linux environment, behind my firewall?
I can supply more details about the SSL errors, if that helps.
-8810900 0Try having your Activity
implement AdapterView.OnItemSelectedListener
itself. Notice I've moved the Spinners
and left out some of your code and replaced it with comments - make sure you include it where necessary...
public class ManageAccountActivity extends Activity implements AdapterView.OnItemSelectedListener { // Your ArrayAdapters as before Spinner spinSexe = null; Spinner spinProvince = null; Spinner spinCountry = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.account_management); spinSexe = (Spinner) findViewById(R.id.spin_sex); spinProvince = (Spinner) findViewById(R.id.spin_province); spinCountry = (Spinner) findViewById(R.id.spin_country); // Call setDropDownViewResource on your ArrayAdapters // Call setAdapter on your Spinners spinCountry.setOnItemSelectedListener(this); } public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { if (parent.getItemAtPosition(pos).toString().equals("Canada")) { spinProvince.setAdapter(adapterProvince); } else { spinProvince.setAdapter(adapterStates); } } public void onNothingSelected(AdapterView parent) { } }
-11054126 1 How to change contour colors in a range of values Colormap class in matplotlib has nice methods set_over
and set_under
, which allow to set color to be used for out-of-range values on contour plot.
But what if I need to set color to be used in a range of values, e.g. white out values from -0.1 to 0.1? Is there a method set_between(colormap, interval, color)
? If not, what would be the easiest solution?
Add these frameworks.. SystemConfiguration.framework Security.framework CFNetwork.framework
-20243818 0This is encapsulation
.
If you have getters like these, then private
access modifiers on your fields would make them more meaningful.
private double purchase; private int numItems;
-30891997 0 Is it of correct architecture? Did you define ABI
for the .so file? Is it marked as AndroidNativeLibrary
?
<ItemGroup> <AndroidNativeLibrary Include="path/to/libfoo.so"> <Abi>armeabi</Abi> </AndroidNativeLibrary> </ItemGroup>
Just in case here is the documentation: http://developer.xamarin.com/guides/android/advanced_topics/using_native_libraries/ http://www.mono-project.com/docs/advanced/pinvoke/ Pretty sure you've seen it though.
-28659146 0The images of your charts helped a lot in understanding what you trying to do. Using ddply with summarize from the plyr package does the same calculation as tapply but returns the result in a data frame that ggplot can use directly. Given that different data is used in the two examples, the code below seems to reproduce your chart in R:
library(plyr) df3 <- ddply(df2,.(sex, smoker), summarize, BMI_mean=mean(BMI)) ggplot(df3,aes(as.numeric(smoker), BMI_mean, color=sex)) + geom_line() + scale_x_discrete("Current Sig Smoker Y/N", labels=levels(df3$smoker)) + labs(y="Mean Body Mass Index (kg/(M*M)", color="SEX")
C++ friendship works the other way: if GameComponent
declares Position
as a friend it means that Position
has access to all the private methods of the GameCompenent
. What you need is exactly the opposite: call Position
private methods from GameComponent
So if Position::displayPositions()
is the private method of the Position class that you want to access from GameComponent then you can declare GameComponent
as a friend of Position
:
class Position { friend class GameComponent; ... };
-14389835 0 Just add a default constructor without the handle parameter. Make sure MyWindowClass subclasses NSWindow and it should work.
Also, you may need to keep a reference to your myWindow around - so that it does not get garbage collected.
-9234066 0 jQuery Mobile: Which event should listview('refresh') go in?I'm developing an application which uses WebSQL DB to store data and then retrieve it. The UI is powered by jQuery Mobile, and when I successfully get back the data from the DB, I put it in a listview.
When I do that, I get the data, but with no styling at all. Just plain web browser rendering.
To refresh the layout, I looked on jQuery Mobile Docs that I need to use $('#list').listview('refresh');
Now I tried several implementations of this and always failed. I'm asking, which event should the refresh statement go in. On my page load I load the Data and put it in the DOM.
Please Help!... Thanks...
-40386029 0 How to tar bitbucket's home directory?When i try to tar /var/atlassian/application-data/bitbucket, i get 2 errors:
tar: /var/atlassian/application-data/bitbucket/shared/config/ssh-server-keys.pem: Cannot open: Permission denied tar: /var/atlassian/application-data/bitbucket/shared/bitbucket.properties: Cannot open: Permission denied
How can i backup these 2 files without sudo? I plan to use it on cron.
-38385240 0 Retrieve Hive Data as JSON document using Java REST APII am trying to build a front end visualization screen and the backend data is in Hive. I am trying to develop a REST API that fetches data from Hive into JSON format from where I can use any D3.js or other libraries to display data.
I am new to this so need an advice as to which is the best approach to do this and in case you already have any examples about how to do this. Appreciate your response. Thanks.
-34936261 0(Spyder dev here) Sorry, but there is no support for autocomplete in the IPython Console.
That's a separate project that we just embed in Spyder, so we can't do anything about it (other than waiting for someone to add support for it later on :)
-24233088 0The problem in your code is that, on the first button click, you are adding the value to the ArrayList, of which the state is not saved during the post back. Which means, on the Button2_Click event the array list will always be empty.
Change your value property something like this. Or Save the Arraylist value to the session in the DataList1_ItemCommand event itself
ArrayList value { get { ArrayList values = null; if(ViewState["selectedValues"] != null) values = (ArrayList)ViewState["selectedValues"]; else { values = new ArrayList(); ViewState["selectedValues"] = values; } return values; } }
-15835405 0 Oracle representing hierarchy of data combinations I'm having an Oracle volume of data issue, which I think is being caused by a data representation problem. I have a hierarchy made from seven different lists, and need to store all the unique potential combinations of these elements. I need to store all the potential combinations, because I need to store additional information along with them.
Historically, we've been managing four lists, which came to a few thousand combinations. This was fine, but requirements have changed as they are wont to do, and now we are running seven lists. In my real environment, the lists store between 20 and 200 items. The total number of combinations for this now, incredibly, is about 350 billion.
As an example of what we're trying to represent with this, you could have a selection of lists like:
Colours:Red, Green, Blue
Shapes: Circle, Square, Triangle
Flavours: Peach, Banana, Raspberry
These would be stored as separate tables in Oracle like COLOURS, SHAPES, FLAVOURS, etc, and what we'd be doing is multiplying them all together (via a Cartesian join) to get an exploded table: This is what we're storing in Oracle at the moment.
COLOUR SHAPE FLAVOUR DATA_1 DATA_2 Red Circle Peach -- these hold additional information Red Circle Banana Red Circle Raspberry Red Square Peach Red Square Banana ...
and so on.
We've found we can't store billions of records within an Oracle table and have any operation performed upon them in a timely fashion. I've tried to think of different ways to store this information but my brain keeps jamming up on the number of combinations. Is there anything I can do to store the records differently? Bearing in mind they're all unique combinations, and we need to store data along with them.
Thanks for any help!
-16093122 0 PHP Recursive Array Intersect Key Tripping over string valueI'm currently receiving an error PHP Catchable fatal error: Argument 2 passed to NUI::recArrInterKey() must be an array, string given
when trying to recursively intersect a multidimensional array (grey/white list).
It seems to be tripping on the $foo['contact']['im']['provider']
section for some reason that I can't figure out?
Here's an example whitelist array ($array2) that I am using
Array ( [location] => false [network_name] => false [interests] => false [last_name] => false [url] => false [significant_other] => false [network_domains] => false [contact] => Array ( [im] => Array ( [provider] => false ) [email_addresses] => false ) )
And the method
/** * Recursive array intersect key */ private static function recArrInterKey(array $array1, array $array2) { $array1 = array_intersect_key($array1, $array2); foreach ($array1 as $key => &$value) { if (is_array($value)) { $value = self::recArrInterKey($value, $array2[$key]); } } return $array1; }
lets say that this is $array1
Array ( [location] => Seattle [occupation] => Developer [network_name] => foo.network [network_region] => foo.region [interests] => coding [last_name] => daniel [url] => false [id] => 4665228 [significant_other] => some girl [network_domains] => false [contact] => Array ( [im] => Array ( [provider] => aol ) [phone] => Array ( [provider] => at&t ) [email_addresses] => dont@mail.me ) )
I am expecting this as a return
Array ( [location] => Seattle [occupation] => Developer [network_name] => foo.network [interests] => coding [last_name] => daniel [url] => false [significant_other] => some girl [network_domains] => false [contact] => Array ( [im] => Array ( [provider] => aol ) [email_addresses] => dont@mail.me ) )
-38026521 0 VSTO, nor the Outlook object model, doesn't provide anything for that. You may try to use Windows API functions, but there is no trivial to get the job done.
Feel free to leave your feedback at https://outlook.uservoice.com/ .
-18718761 0Install your own nuget server behind the firewall/proxy and point to that as your default NuGet server.
I've used the free version of ProGet in the past as an easy to run a nuget server that also acts as a caching proxy for the main nuget gallery. It also means that if the main nuget server or your internet connection is down you will still have a nuget server that your build can connect to.
-16231933 0The problem it is, when you want to give back the focus.
I have implemented as listening each textfield and caching which is the latest. Than resign only that one ( in push ) after that restore state, require focus for that.
-20125248 0No, AsyncPattern
is no longer required as of .NET 4.5.
I have a blog post Async WCF Today and Tomorrow that compares the old way of asynchronous WCF ("Today" in the blog post: .NET 4.0) with the new way of asynchronous WCF ("Tomorrow" in the blog post: .NET 4.5).
-16209274 0You have 17GB of RAM available for about 20GB of data plus 4GB of indexes (and that's just on this DB - I don't know if there is more in your system, but mongostat says you have total datafile size of about 28GB).
If you are querying over your entire dataset, wouldn't you expect that eventually new data records being read can no longer fit into RAM without displaying some of the previously read (and loaded into RAM) records? That's what you're seeing with page faulting.
It's not data storage that you are concerned about, it's data being used or queries or accessed. If it all can't stay in RAM then it will get swapped out and then will need to be swapped back in when accessed again.
-17773698 0global objects which inherit from Object,
That's a wrong assumption, global objects are host objects and they can inherit from whatever they want or not inherit anything at all. The code for example doesn't work in IE10.
The particular toString
method stored on Object.prototype
is the only one that returns the internal class name for sure. Functions, arrays, numbers etc do not inherit the Object.prototype
toString
method but define their own toString
method, as in Number.prototype.toString !== Object.prototype.toString
.
- What are some advantages/disadvantages to using either approach?
Using sequential numbers
Advantages: Easy to implement
Disadvantages: Possible vector for attack. See this video for a high-level overview.
Using random numbers
Advantages: Solves the problems outlined in the video re: sequential record attacks
Disadvantages: Since there's only 10 bits of entropy, ID's would have to be much longer if your app grows.
Base 64 (use this instead of hex)
Advantages: 64 bits of entropy means an ID 5 chars long would have 64^5 possible permutations. This allows for comparatively much shorter URLs. Use SecureRandom.urlsafe_base64
for this.
Disadvantages: None, really.
- Is there a good industry standard or best practice for generating synthetic ids for concepts like users, groups, posts, etc..
To my knowledge, no. Anything sufficiently random and of sufficient length should be fine. Within your model, you'd want to check if an ID is taken first so you don't have duplicates, but outside of that there's little to worry about.
- What's the best way in Ruby/Rails to generate each of these IDs? I know of SecureRandom.hex but that seems to generate a long hash.
Like I said above, I recommend using SecureRandom.urlsafe_base64
I'm facing some problems launching my rails app hosted on bluehost.
I think that the problem is the passenger version interacting with the rails 4 app but I'm not sure.
When I launch my app I get this trace:
Ruby (Rack) application could not be started These are the possible causes: There may be a syntax error in the application's code. Please check for such errors and fix them. A required library may not installed. Please install all libraries that this application requires. The application may not be properly configured. Please check whether all configuration files are written correctly, fix any incorrect configurations, and restart this application. A service that the application relies on (such as the database server or the Ferret search engine server) may not have been started. Please start that service. Further information about the error may have been written to the application's log file. Please check it in order to analyse the problem. Error message: Could not initialize MySQL client library Exception class: RuntimeError Application root: /home5/barracam/rails_apps/admin/admin Backtrace: # File Line Location 0 /home5/barracam/ruby/gems/gems/mysql2-0.3.18/lib/mysql2.rb 31 in `require' 1 /home5/barracam/ruby/gems/gems/mysql2-0.3.18/lib/mysql2.rb 31 in `' 2 /usr/lib64/ruby/gems/1.9.3/gems/bundler-1.3.5/lib/bundler/runtime.rb 72 in `require' 3 /usr/lib64/ruby/gems/1.9.3/gems/bundler-1.3.5/lib/bundler/runtime.rb 72 in `block (2 levels) in require' 4 /usr/lib64/ruby/gems/1.9.3/gems/bundler-1.3.5/lib/bundler/runtime.rb 70 in `each' 5 /usr/lib64/ruby/gems/1.9.3/gems/bundler-1.3.5/lib/bundler/runtime.rb 70 in `block in require' 6 /usr/lib64/ruby/gems/1.9.3/gems/bundler-1.3.5/lib/bundler/runtime.rb 59 in `each' 7 /usr/lib64/ruby/gems/1.9.3/gems/bundler-1.3.5/lib/bundler/runtime.rb 59 in `require' 8 /usr/lib64/ruby/gems/1.9.3/gems/bundler-1.3.5/lib/bundler.rb 132 in `require' 9 /home5/barracam/rails_apps/admin/admin/config/application.rb 7 in `' 10 /home5/barracam/rails_apps/admin/admin/config/environment.rb 2 in `require' 11 /home5/barracam/rails_apps/admin/admin/config/environment.rb 2 in `' 12 config.ru 3 in `require' 13 config.ru 3 in `block in' 14 /home5/barracam/ruby/gems/gems/rack-1.5.2/lib/rack/builder.rb 55 in `instance_eval' 15 /home5/barracam/ruby/gems/gems/rack-1.5.2/lib/rack/builder.rb 55 in `initialize' 16 config.ru 1 in `new' 17 config.ru 1 in `' 18 /etc/httpd/modules/passenger/lib/phusion_passenger/rack/application_spawner.rb 225 in `eval' 19 /etc/httpd/modules/passenger/lib/phusion_passenger/rack/application_spawner.rb 225 in `load_rack_app' 20 /etc/httpd/modules/passenger/lib/phusion_passenger/rack/application_spawner.rb 157 in `block in initialize_server' 21 /etc/httpd/modules/passenger/lib/phusion_passenger/utils.rb 563 in `report_app_init_status' 22 /etc/httpd/modules/passenger/lib/phusion_passenger/rack/application_spawner.rb 154 in `initialize_server' 23 /etc/httpd/modules/passenger/lib/phusion_passenger/abstract_server.rb 204 in `start_synchronously' 24 /etc/httpd/modules/passenger/lib/phusion_passenger/abstract_server.rb 180 in `start' 25 /etc/httpd/modules/passenger/lib/phusion_passenger/rack/application_spawner.rb 129 in `start' 26 /etc/httpd/modules/passenger/lib/phusion_passenger/spawn_manager.rb 253 in `block (2 levels) in spawn_rack_application' 27 /etc/httpd/modules/passenger/lib/phusion_passenger/abstract_server_collection.rb 132 in `lookup_or_add' 28 /etc/httpd/modules/passenger/lib/phusion_passenger/spawn_manager.rb 246 in `block in spawn_rack_application' 29 /etc/httpd/modules/passenger/lib/phusion_passenger/abstract_server_collection.rb 82 in `block in synchronize' 30 prelude> 10:in `synchronize' 31 /etc/httpd/modules/passenger/lib/phusion_passenger/abstract_server_collection.rb 79 in `synchronize' 32 /etc/httpd/modules/passenger/lib/phusion_passenger/spawn_manager.rb 244 in `spawn_rack_application' 33 /etc/httpd/modules/passenger/lib/phusion_passenger/spawn_manager.rb 137 in `spawn_application' 34 /etc/httpd/modules/passenger/lib/phusion_passenger/spawn_manager.rb 275 in `handle_spawn_application' 35 /etc/httpd/modules/passenger/lib/phusion_passenger/abstract_server.rb 357 in `server_main_loop' 36 /etc/httpd/modules/passenger/lib/phusion_passenger/abstract_server.rb 206 in `start_synchronously' 37 /etc/httpd/modules/passenger/helper-scripts/passenger-spawn-server 99 in `' Powered by Phusion Passenger, mod_rails / mod_rack for Apache and Nginx.
I tried to run a rails 3 app and all works fine. What do you think about the problem?
Any help is really appreciated.
-12078361 0have you made sure that during MDM enrollment, the MDM payload (PayloadType = com.apple.mdm) you deliver has the correct Topic?
i.e. in your APN push cert that you've downloaded from apple.you'll see something like CN = com.apple.mgmt.external.[GUID]. This needs to be the same value delivered to your IOS device during MDM enrollment.
If APN does not give any error during the message upload, or the feedback service does not return the deviceID which indicates that the device is not available, it should mean that it will be delivered correctly to the device. The next phase is to determine if the IOS device is setup to listen to the APN message via this topic.
You can try connecting your device to XCode or IPCU, in the console logs, it will contain logs indicating if APN was able to successfully deliver this message using the agreed upon topic.
Here's also an article on troubleshootin APN http://developer.apple.com/library/ios/#technotes/tn2265/_index.html
there's a downloadable profile in the above article that you can load to your device for additional verbose logging.
-3626662 0 Android, Google Analitics: how to implement page view tracking on "/quit" application exit?I need to track my Android application exit as a page view. My application has several activities, but there is no hierarchy, so there is not an unique exit point.
My understanding is that "application exit" means another application is on top of mine, hiding it completely. So if my application is no more visible, there is an "application exit". Is my understanding correct?
So, how could I track this "application exit" with Google Analytics?
Looking forward for advice. Thank you.
-13249368 0Some browsers will add all attributes as named properties of the DOM element, others will only add standard attributes. In both cases you can get non–standard attributes using getAttribute
, however such a scheme is not recommended.
It is common to use standard attributes and DOM properties and only use getAttribute where necessary as it is inconsistently implemented in different browsers.
-12508376 0Try This
ActivityManager am = (ActivityManager) getApplicationContext().getSystemService("activity"); Method forceStopPackage; forceStopPackage =am.getClass().getDeclaredMethod("forceStopPackage",String.class); forceStopPackage.setAccessible(true); forceStopPackage.invoke(am, pkg);
In manifest file add this
<uses-permission android:name="android.permission.FORCE_STOP_PACKAGES"></uses-permission>
-12112023 0 Your definition of your status
field is incorrect. CharFields require a "max_length" attribute that is a positive integer.
Change it to the following:
models.CharField(max_length=..., choices=STATUS_CHOICES)
See also here
-34471227 0You can use one of many versions of is expression:
enum E : float { E1 = 2.0 } static if (is(typeof(E.E1) Base == enum)) { pragma(msg, Base); // float }
Implementation of your desired template could look like this:
template EnumValueType(T) if (is(T == enum)) { static if (is(T Base == enum)) alias EnumValueType = Base; }
-25548013 0 Mail() function php sends the mails into the spam filters I'm trying to send my newsletter from a php file to some contacts from a database. But when I'm sending the mail to a Google Mail account, the mail is going to the spam filters and not in Inbox. If I send the mail to a Yahoo Mail account, it's working perfectly.
I tryed a lot of possibilities, and I wrote the code necessarry to be a nice e-mail but no result for G-Mail. If you can give me an idea to make my php function not so spammy, I would be grateful. Thanks in advance.
The php code for this is:
function spamcheck($field) { $field=filter_var($field, FILTER_SANITIZE_EMAIL); if(filter_var($field, FILTER_VALIDATE_EMAIL)) { return TRUE; } else { return FALSE; } } if(isset($_REQUEST) && isset($_POST['check'])) { if(!empty($_POST['check'])) { $mailcheck = spamcheck($_POST["from"]); foreach($_POST['check'] as $checkB) { if($mailcheck==FALSE) { echo "Invalid Imputs!"; } else { $to = $checkB; $headers = "Reply-To: Caron Chiropractic ".$_POST['from']."\r\n"; $headers .= "Return-Path: Caron Chiropractic ".$_POST['from']."\r\n"; $headers .= "From: Caron Chiropractic ".$_POST['from']."\r\n"; $headers .= "Organization: Caron Chiropractor\r\n"; $headers .= "MIME-Version: 1.0\r\n"; $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n"; $headers .= "X-Priority: 3\r\n"; $headers .= "X-Mailer: PHP/" . phpversion(); $message = '<table style="margin: auto; width: 500px; font-family: sans-serif, Verdana, Arial, Helvetica, sans-serif; text-align: center; border-width: 2px; border-color: #999999; box-shadow: 0 0 10px gray; background: #F0F0F0;"> <tr> <td style="width: 500px; background: #003366; -webkit-border-radius: 10px; -moz-border-radius: 10px; -ms-border-radius: 10px; -o-border-radius: 10px; border-radius: 10px;"> <img src="http://www.caronchiro.com/feedback/png/logo.png" alt="Logo" style="width: 200px;"> </td> </tr> <tr> <td> <br> </td> </tr> <tr> <td style="height: 20px;"> </td> </tr> <tr> <td> <br> </td> </tr> <tr> <td> <h3>A friendly hello from Caron Chiropractic!</h3> </td> </tr> <tr> <td> <br> </td> </tr> <tr> <td> <p>We would like to hear about your experience with us. If you have a moment, please take our two-question survey.</p> </td> </tr> <tr> <td> <br> </td> </tr> <tr> <td> <a href="http://www.caronchiro.com/feedback/survey.php" style="background: #003366; border: none; padding: 5px 10px 5px 10px; text-shadow: 1px 1px #000; color: #FFF; text-decoration: none; -webkit-border-radius: 10px; -moz-border-radius: 10px; -ms-border-radius: 10px; -o-border-radius: 10px; border-radius: 10px;">Take the survey!</a><br><br> </td> </tr> <tr> <td> <p>Thank you for helping us improve our services.</p> </td> </tr> <tr> <td> <a href="http://www.caronchiro.com/feedback/unsubscribe.php?id='.md5($to).'" style="text-decoration: none; color: #003366;">Unsubscribe</a> </td> </tr> <tr> <td> <br> </td> </tr> <tr> <td> <p style="color: #B7B7B7;">CopyRight © 2014</p> </td> </tr> </table>'; $subject = "A friendly hello from Caron Chiropractic!"; mail($to,$subject,$message,$headers); } } } }
-22882163 0 Refresh Master-Detail gridcontrol I have a devexpress Master-View gridcontrol , bound to Entity bindingsource. Programatically I update some records on bindingsource , but the Gridcontrol is not refreshed with new data. I use the following methods : ( GridviewMaster - is Master View , GridviewChild - is Detail view )
GridControl1.RefreshDataSource() GridControl1.MainView.RefreshData() GridControl1.DefaultView.RefreshData() GridViewMaster.RefreshData() GridViewChild.RefreshData()
But without success.I know that the bindingsource is updated , but the Gridcontrol is not. Only when i close and open the form again the gridcontrol is updated. What can I do ? ( without querying again the database) Thank you ! '
-30097122 0I have a more compact method.
I think it's more readable and easy to understand. You can refer as below:
This is your var I delcare response
:
response = [ {'country': 'KR', 'values': ['Server1']}, {'country': 'IE', 'values': ['Server1', 'Server3', 'Server2']}, {'country': 'IE', 'values': ['Server1', 'Server3']}, {'country': 'DE', 'values': ['Server1']}, {'country': 'DE', 'values': ['Server2']}, ]
Let's merge the values.
new_res = {} for e in response: if e['country'] not in new_res: new_res[e['country']] = e['values'] else: new_res[e['country']].extend(e['values'])
You can print new_res
if you want to know its content. It's like as below:
{ 'KR': ['Server1'], 'DE': ['Server1', 'Server2'], 'IE': ['Server1', 'Server3', 'Server2', 'Server1', 'Server3'] }
Invoking collections
module collects elements:
from collections import Counter new_list = [] for country, values in new_res.items(): # elements are stored as dictionary keys and their counts are stored as dictionary values merge_values = Counter(values) # calculate percentage new_values = [] total = sum(merge_values.values()) for server_name, num in merge_values.items(): #ex: Server1-40.0 new_values.append("{0}-{1:.1f}".format(server_name, num*100/total)) percent = merge_values["Server1"]*1.0*100/total new_list.append({"country": country, "percent": percent, "values": new_values})
You can print new_list
when finishing calculating result:
[{'country': 'KR', 'percent': 100.0, 'values': ['Server1-100.0']}, {'country': 'DE', 'percent': 50.0, 'values': ['Server1-50.0', 'Server2-50.0']}, {'country': 'IE', 'percent': 40.0, 'values': ['Server1-40.0', 'Server2-20.0', 'Server3-40.0']}]
So you can get answer you want.
-31860435 0 What is the easiest way to truncate an IP address to /24 in C?Is there a method that can truncate the IP address to /24? Or, should I parse the IP address manually and do the conversion?
Edit:
Ip address is IPv4 and is stored in the Dotted decimal format surrounded by quotes as char *
. I am expecting the /24 to be char *
too.
Example format: "64.233.174.94" .
/24 expected format: "64.233.174.0"
Hope this helps. Thanks.
-28361768 0exec
is for executing system functions, not for running scripts. (Take a look at the manual, it's helping: http://php.net/manual/de/function.exec.php)
To achieve what you want, you could pass the path to php executable and add the script as parameter, like this:
<?php $phpExecutable = 'C:/xampp/bin/php.exe' $path = 'C:/xampp/htdocs/user/execute.php'; exec($phpExecutable." ".$path, $output,$return); var_dump($return); echo "hi"."<br>"; echo "end";?>
Should work. I do not know where your php executable is located, so please adapt it to your location.
Happy coding.
-20215732 0 How could uptime command show a cpu time greater than 100%?Running an application with an infinite loop (no sleep, no system calls inside the loop) on a linux system with kernel 2.6.11 and single core processor results in a 98-99% cputime consuming. That's normal. I have another single thread server application normally with an average sleep of 98% and a maximum of 20% of cputime. Once connected with a net client, the sleep average drops to 88% (nothing strange) but the cputime (1 minute average) rises constantly but not immediately over the 100%... I saw also a 160% !!?? The net traffic is quite slow (one small packet every 0.5 seconds). Usually the 15 min average of uptime command shows about 115%.
I ran also gprof but I did not find it useful... I have a similar scenario:
IDLE SCENARIO %time name 59.09 Run() 25.00 updateInfos() 5.68 updateMcuInfo() 2.27 getLastEvent() .... CONNECTED SCENARIO %time name 38.42 updateInfo() 34.49 Run() 10.57 updateCUinfo() 4.36 updateMcuInfo() 3.90 ... 1.77 ... ....
None of the listed functions is directly involved with client communication
How can you explain this behaviour? Is it a known bug? Could be the extra time consumed in kernel space after a system call and lead to a calculus like
%=100*(apptime+kerneltime)/(total apps time)?
-32752372 0 Datagrid checkbox selection lost when refresh datagrid WPF MVVM I have the datagrid that populated with caseRefNo,subjrMatr, Download data in it. my backgroundworker is running and return caseRefNo and Download percentage. I user DispatcherTimer to update download percentage (every 3 sec) according to caseRefNo.
i can show download percentage in datagrid filtered by caseRefNo. The problem starts here. i cannot check my checkbox because of DispatcherTimer refresh the CollectionView that i bind to datagrid.
Here is my ViewModel source code.
public class DataGridDownloadViewModel:BindableBase { public ObservableCollection<tblTransaction> TransList { get; private set; } public DispatcherTimer dispatchTimer = new DispatcherTimer(); public CollectionView TransView { get; private set; } private String _UpdatePer; public String UpdatePercentage { get { return _UpdatePer; } set { SetProperty(ref _UpdatePer, value); } } private string _caseId; public string CaseID { get { return _caseId; } set { SetProperty(ref _caseId, value); } } public DataGridDownloadViewModel(List<tblTransaction> model) { dispatchTimer.Interval = TimeSpan.FromMilliseconds(3000); dispatchTimer.Tick += dispatchTimer_Tick; BackGroundThread bgT = Application.Current.Resources["BackGroundThread"] as BackGroundThread; bgT.GetPercentChanged += (ss, ee) => { UpdatePercentage = bgT.local_percentage.ToString(); }; bgT.GetCaseID += (ss, ee) => { CaseID = bgT.local_caseRef; }; TransList =new ObservableCollection<tblTransaction>(model); TransView = GetTransCollectionView(TransList); TransView.Filter = OnFilterTrans; var tokenSource = new CancellationTokenSource(); var token = tokenSource.Token; var cancellationTokenSource = new CancellationTokenSource(); dispatchTimer.Start(); } private void dispatchTimer_Tick(object sender, EventArgs e) { UpdateDataGrid(); } public void UpdateDataGrid() { foreach (tblTransaction tran in TransList) { if (tran.caseRefNo == CaseID) { tran.incValue = int.Parse(UpdatePercentage); tran.IsCheck = tran.IsCheck; } else { tran.incValue = tran.incValue; tran.IsCheck = tran.IsCheck; } } TransView.Refresh(); } bool OnFilterTrans(object item) { var trans = (tblTransaction)item; return true; } public CollectionView GetTransCollectionView(ObservableCollection<tblTransaction> tranList) { return (CollectionView)CollectionViewSource.GetDefaultView(tranList); } }
Here is my view:
<Window x:Class="EmployeeManager.View.DataGridDownload" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="DataGridDownload" Height="600" Width="790"> <Grid> <DataGrid HorizontalAlignment="Left" ItemsSource="{Binding TransView}" AutoGenerateColumns="False" Margin="10,62,0,0" VerticalAlignment="Top" Height="497" Width="762"> <DataGrid.Columns> <DataGridTextColumn Header="caseRefNo" Binding="{Binding caseRefNo}" /> <DataGridTextColumn Header="subjMatr" Binding="{Binding subjMatr}" /> <DataGridTextColumn Header="Download %" Binding="{Binding incValue}" /> <DataGridTemplateColumn> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <CheckBox x:Name="TestCheckBox" IsChecked="{Binding IsCheck,Mode=TwoWay}"></CheckBox> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> </DataGrid.Columns> </DataGrid> <Label Content="{Binding UpdatePercentage}" HorizontalAlignment="Left" Background="Blue" Foreground="White" Margin="10,10,0,0" VerticalAlignment="Top" Width="338" Height="30"> </Label> <Button Content="Button" HorizontalAlignment="Left" Margin="672,20,0,0" VerticalAlignment="Top" Width="75"/> </Grid>
This is my tblTransaction Model
public class tblTransaction { public string caseRefNo { get;set;} public string subjMatr { get; set; } public int incValue { get; set; } public DateTime? longTime { get; set; } private bool _ischk = false; public bool IsCheck { get { return _ischk ;} set { _ischk = value; } } }
Please guide me how to do it. any help really appreciate. df
-30129866 0 Double issue with "this" scope in xmlhttprequest javascriptI have two huge issues with this
scope in my javascript code. After creating setAJAXGet
object, callback function was lost and couldn't be called correctly. So instead of calling this.funct
I set ajax.parent = this
; and call this.parent.funct
- works ok.
function setAJAXGet() { this.askServer = function() { var ajax = new XMLHttpRequest(); ajax.parent = this; ajax.contentType = "charset:utf-8"; ajax.onreadystatechange = function() { if (ajax.readyState==4 && ajax.status==200) { this.parent.funct(ajax.responseText); } } ajax.open( "GET", this.url+'?'+this.vars, true ); ajax.setRequestHeader("Content-Type", "text/xml; charset=utf-8"); if (navigator.onLine) ajax.send( null ); else this.functError(); } this.functError; this.funct; this.vars; this.url; }
Things get a little more complicated when I try to call setAJAXGet()
from the other object and the callback function is inside that object. Callback function is called correctly, but every other function in the object (from the callback function) gets invisible.
function someObject() { this.asyncGet = function() { var get = new setAJAXGet(); //do some config here... get.funct = this.processAsyncData; get.askServer(); } this.someOtherFunction = function() { } this.processAsyncData = function(ajaxText) { // ajaxText is OK this.someOtherFunction(); // this.someOtherFunction is not defined (how so?) } this.asyncGet(); }
I can solve this problem by passing object to the processAsyncData
by modified setAJAXGet()
as argument, but it looks ugly.
function someObject() { this.asyncGet = function() { var get = new modifiedSetAJAXGet(); //do config here... get.object = this; // stores 'this' and sends it to callback as argument get.funct = this.processAsyncData; get.askServer(); } this.someOtherFunction = function() { } this.processAsyncData = function(object, ajaxText) { // ajaxText is OK object.someOtherFunction(); // object.someOtherFunction works just fine } this.asyncGet(); }
I believe that you know more elegant solution.
-38679728 0I found the answer to your question due to @Squidward. From the above article I went to https://msdn.microsoft.com/ru-ru/library/windows/apps/xaml/hh868212.aspx
In my code I added the following and my OnLanched field in the Arguments data. Now I might be able to make plans!
ToastTemplateType _toastTemplate = ToastTemplateType.ToastText02; XmlDocument _toastXml = ToastNotificationManager.GetTemplateContent(_toastTemplate); //this set argument for OnLaunched IXmlNode toastNode = _toastXml.SelectSingleNode("/toast"); ((XmlElement)toastNode).SetAttribute("launch", "111111"); //---
-34688909 0 I decided to do it through code behind. This means that I do lose my ability to use the design-time data to preview my UI; but it works at run time.
So, in the xaml I have.
<controls:MetroTabControl Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="0" Grid.RowSpan="2" ItemsSource="{Binding ElementName=ucMe, Path=TabSitesCollection}">
Where ucMe is the UserControl and TabSitesCollection is a
protected CollectionViewSource m_TabSitesCollectionViewSource; protected CompositeCollection m_TabSitesComposites; public ICollectionView TabSitesCollection { get { return m_TabSitesCollectionViewSource.View; } }
That gets initialised in the constructor as follows
public ConfigSiteView() { m_TabSitesComposites = new CompositeCollection(); m_TabSitesCollectionViewSource = new CollectionViewSource(); m_TabSitesCollectionViewSource.Source = m_TabSitesComposites; InitializeComponent(); }
Then, on the Loaded event I can do
m_TabSitesComposites.Add(new CollectionContainer() { Collection = GetModel.View }); m_TabSitesComposites.Add(new TabItem() { Header = "hi" }); m_TabSitesComposites.Add(new TabItem() { Header = "ho" });
This results in almost my desired UI
I now simply need to spiff up my settings tab item and i'm done. For reference, the xaml designer does not have any preview data - Unless I change the xaml so that the preview loads up (which then breaks the actual execution)
It would have been nice to have it both work while running, and on preview, but I haven't figured out how to do that, and it's not a current priority.
-41068958 0For an <activity-alias>
declared like this:
<activity-alias android:name=".main.MainActivityAlias" android:targetActivity=".main.MainActivity">
The ComponentName
can be created like this:
ComponentName componentName = new ComponentName("com.company.htmlapp", "com.company.htmlapp.main.MainActivityAlias");
In my case I could also do it dynamically:
try { PackageManager pm = getPackageManager(); PackageInfo packageInfo = pm.getPackageInfo(this.getPackageName(), 0); ComponentName componentName = new ComponentName(packageInfo.packageName, MainActivity.class.getPackage().getName() + ".MainActivityAlias"); i.setComponent(componentName); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); }
-33889276 0 Update: Thanks to @Putnik for pointing out an easier way (but I prefer only listing sites-enabled):
grep server_name /etc/nginx/sites-enabled/* -RiI
Old Post:
Try something like this:
find /etc/nginx/sites-enabled/ -type f -print0 | xargs -0 egrep '^(\s|\t)*server_name'
Hope that helps!
-4789888 0 ActionListener phases in JSFHI,
I have a doubt on calling the ActionListener method in the JSF beans. For example every request or submission of JSF form is gone through the life cycle of six phases. But, when we are triggering the particular event like action listener or value change listener, is there any lifecycle associated with that request?
Please clarify me.
-23126422 0I would approach it by using a variable in the scope to hold the state, and chaining $timeout
s to move between the states. So on the element that will be clicked:
<span ng-click="startChange()">Click me to start</span>
and in the controller:
$scope.state = 'a'; $scope.startChange = function() { $scope.state = 'b'; return $timeout(angular.noop, 30 * 1000).then(function() { $scope.state = 'c'; return $timeout(angular.noop, 60 * 1000); }).then(function() { $scope.state = 'd'; return $timeout(angular.noop, 120 * 1000); }).then(function() { $scope.state = 'e' }); }
The angular.noop
is just a function that does nothing. It's a slightly personal preference, but I find it a bit easier to see the flow of activity where the callback passed to $timeout
does nothing, and all action on the scope are always in the then
success callback of the promise.
In the template for the background div:
<div class="background-state-{{state}}">....</div>
and then in CSS set the colours:
.background-state-a {background-color: red} .background-state-b {background-color: green} .background-state-c {background-color: blue} ...
However, I'm not sure what else you have in the controller or your exact use-case. You might want to separate some logic out into a directive, as it might be mixing business logic with view logic.
-3653551 0 Mixing Qt threads with COM threadsI'm working on a little project that uses DirectShow/COM for capture, and DShow makes callbacks using its own threads when my application gets imaging data.
I'm also using Qt in my project, and I'm wanting to use Qt for synchronisation and thread-safety. I'm wondering how I can use Qt Threads in this case.
I understand I can also use Win32's CriticalSection functions, but this would make it harder to port my code to other platforms (as the DShow stuff is the only Windows-specific code in my project).
My question is: "how do I use Qt's thread safety features when working with non-Qt threads?"
-8814194 0 TableViewCell's textLabel value returns to 1 when cell is scrolled out of the viewi have a table view in which i can add 1 or subtract 1 to the value of my cell.textLabel.text
but when i switch views and return or scroll a cell out of the view, and when it comes back into view, the textLabel
's value returns to 1
which is the original starting point! Please help! Here is the code to add and subtract 1:
- (IBAction)addLabelText:(id)sender{ cell = (UITableViewCell*)[sender superview]; // <-- ADD THIS LINE cell.textLabel.text = [NSString stringWithFormat:@"%d",[cell.textLabel.text intValue] +1]; } - (IBAction)subtractLabelText:(id)sender { cell = (UITableViewCell *)[sender superview]; if ( [[cell.textLabel text] intValue] == 0){ cell.textLabel.text = [NSString stringWithFormat:@"%d",[cell.textLabel.text intValue] +0]; } else{ cell.textLabel.text = [NSString stringWithFormat:@"%d",[cell.textLabel.text intValue] -1]; } }
-31851165 0 Consider the following:
> console.log({ foo : { bar : [ { xxx : 1 } ] } }) { foo: { bar: [ [Object] ] } }
This is showing similar output to what you are seeing. The reason for the unexpected output is that a regular console.log()
will only show nested objects up to a specific depth, after which it will abbreviate the output (in this case, it will show [Object]
instead of the actual object). This doesn't mean the object is invalid, though, it's just shown in this shorter format when you print it.
One solution to get to see the whole object is to convert it to JSON first:
> console.log('%j', { foo : { bar : [ { xxx : 1 } ] } }) {"foo":{"bar":[{"xxx":1}]}}
Or, in your case:
console.log('%j', data);
-34864844 0 How do I open an existing django project in LiClipse? Really dumb question, but it's taking me too long to figure out how to open an existing django project "mysite" in LiClipse (mysite wasn't created within LiClipse). I tried import and wasn't seeing anything obvious, I tried creating a new project (file>new>project... )with the "Use default" setting unchecked (and browsed to the mysite home directory) but it still created a new project instead of loading mysite. If I browse to each individual file in mysite I can open them in LiClipse but I want mysite to be recognized by LiClipse as a django project.
If anyone with some experience using LiClipse and Django can take a few minutes to walk me through it I'd greatly appreciate it.
-20837850 0 Tailor ansible roles to environmentI have a number of environments, that require a bunch of text files to be tailored in order for things like mule to speak to the right endpoints.
For this environment, this works:
ansible-playbook test03.yml
The only difference between an environment (from ansible's perspective) is the information held in ./roles/esb/vars/main.yml.
I've considered using svn to keep a vars/main.yml for each environment, so each time I need to configure an environment I check out roles and then vars/main.yml for that environment, before I run the command above.
To me, not an elegant solution. How can I do this better?
Directory structure
./test03.yml ./roles/esb/vars/main.yml ./roles/esb/tasks/main.yml ./roles/esb/templates/trp.properties.j2
./test03.yml
--- - hosts: test03-esb gather_facts: no roles: - esb
./roles/esb/vars/main.yml
--- jndiProviderUrl: 'jnp://mqendpoint.company.com:1099' trp_endpoint_estask: 'http://tmfendpoint.company.com:8080/tmf/estask' trp_endpoint_builderQ: 'jnp://mqendpoint.company.com:1099'
./roles/esb/tasks/main.yml
--- - name: replace variables in templates template: src=trp.properties.j2 dest=/path/to/mule/deploy/conf/trp.properties
./roles/esb/templates/trp.properties.j2
trp.endpoint.estask={{ trp_endpoint_estask }} trp.endpoint.builderQ={{ trp_endpoint_builderQ }}
-35756030 0 You seem to want the triggering event to be a focusin
. Maybe your page navigation calls for this, instead of a simple click. In order to make the div.CinP
itself focusable you should add to it a tabindex
attribute.
How about
$(".CinP").focusin(function() { $(this).css("background-color", "#fefefe"); $('.Cj4Jbc').focus(); });
-22278499 0 I was able to get the tgmath.h
functions to work by including the header at the top of my PCH file.
At some point (read: Xcode update) I had to start disabling Modules to get this to work. The details of such are in the question Dima links to below.
-33372070 0On the latest SDK, Under "C:\Program Files (x86)\Google\Cloud SDK" you should find an uninstall.exe. Just execute it.
-33283325 0A Self-closing tag is a special form of start tag with a slash immediately before the closing right angle bracket. These indicate that the element is to be closed immediately, and has no content. Where this syntax is permitted and used, the end tag must be omitted. In HTML, the use of this syntax is restricted to void elements and foreign elements. If it is used for other elements, it is treated as a start tag. In XHTML, it is possible for any element to use this syntax. But note that it is only conforming for elements with content models that permit them to be empty.
The examples you listed would generally contain content, JavaScript, or other elements, so having a proper start and end tag would delimit the scope of those elements/tags.
-29892707 1 set value to 99 percentile for each column in a dataframeI am working with the data which looks like a dataframe described by
df = pd.DataFrame({'AAA' : [1,1,1,2,2,2,3,3], 'BBB' : [2,1,3,4,6,1,2,3]})
what i would like to do is to set value to roundup(90%) if value exceeds 90 percentile. So its like capping max to 90 percentile. This is getting trickier for me as every column is going to have different percentile value.
I am able to get 90 percentile value using
df.describe(percentiles=[.9])
so for column BBB 6 is greater than 4.60 (90 percentile), hence it needs to be changed to 5 (roundup 4.60).
In actual problem I am doing this for large matrix, so I would like to know if there is any simple solution to this, rather than creating an array of 90 percentile of columns first and then checking elements in for a column and setting those to roundup of 90 percentile
-38125285 0Your xPath
seems to be wrong try with below xPath
:-
//a[text()='Study1_AS_06-20-16_1.xml']/preceding::input[@name='.select']
Note :- for more clarification about xPath
need to follow this
Hope it will help you..:)
-29805806 0 Setting FragmentStatePagerAdapter count to 0 does not destroy any current visible fragmentsI have a PagerAdapter with a dynamic number of elements. You can modify the number of tabs with a single call, which clears the list and the count to 0. Unfortunately, this does not remove the fragment that is currently showing.
public class MyPagerAdapter extends FragmentStatePagerAdapter { private List<Pojo> pojos = new ArrayList<>; @Override public int getCount() { return pojos.size(); } public void removeAll() { this.pojos.clear(); notifyDataSetChanged(); } }
Does anyone know how to force the ViewPager to clear himself?
UPDATE 1:
If you use viewPager.removeAllViews()
then the viewPager is unusable afterwards even after adapter notifies new data changes.
You can see this post, it seems that you have a similar JSONArray.. you can simply use:
JSONArray yourArray = new JSONArray(jsonString); // do the rest of the parsing by looping through the JSONArray
-33595292 0 How do I create a Live Support chat application in C#? I'm attempting to build a live support chat application in C# using a WCF microservice and after endless searches I still can't find the answer, hopefully someone here can point me in the right direction.
My problem is that rather than a typical chat room a where users broadcast messages to all connected clients, I need the application to be more like a Live Support app found on websites such as Amazon or eBay.
Ideally multiple customer support agents will have a pre installed WinForms chat application on their machines, when a customer opens a chat window (aspx page) it will connect to a server/service and the server/service will then call all connected customer support agents until one answers. At this point the customer and agent will be connected in a private chat window.
Could somebody please give me some insight or ideas on how to do this?
Thanks,
Owen
-27105645 0 Is it possible to run Swift testcases from command line without an Xcode project?I have made some extensions for Array & String class in Array.swift and String.swift files; I have also added unit test for them, in ArrayTest.swift and StringTest.swift, respectively. Now I would like to run these unit tests from command line without an Xcode project file.
After reading How can I run XCTest for a swift application from the command line? I have came up with something like this:
xcrun -sdk macosx swiftc -F/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/Library/Frameworks \ -Xlinker -rpath \ -Xlinker /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/Library/Frameworks \ -lswiftCore Array.swift \ -module-name array_extension
... which seems to compiling the array extensions into a module. But how can I compile / link the ArrayTest.swift
file against this module?
You cannot. PHP is interpreted on the server side and jQuery is interpreted on the client side.
You should either use an anchor <a href="session_destroy.php">
to go to another PHP page and destroy the session or use AJAX to call the destroy function without leaving the page.
jQuery('button').click( function () { jQuery.get("session_destroy.php"); } );
-8738380 0 Just use preventDefault and it will work
$("#txt1").bind('keydown', function (e) { if (e.which == 9) { $("#txt2").focus(); e.preventDefault() } } );
BTW, its much better to use direct selectors with ids (#txt2 instead of input[id$=txt2]).
-19933607 0You have to add url of website that you are ajaxing to, to your Access Element value in your config.xml
.
<access origin="http://yourwebsite.com" subdomains="true" />
-17415160 0 Solved partially (please read bottom of this) separating up\down movement from left\right: changed the above mousemove function to
if (event->buttons() & Qt::RightButton) { setMatrixes(); gluUnProject(event->x(), -event->y(), 0, model_matrix, proj_matrix, view_matrix, &newx, &newy, &newz); float acc=sqrt((int)dx^2+(int)dy^2); acc*=acc; qDebug()<< acc; if (dy<dx){ if (event->x()>lastPos.x()){ emit SignalPreviewMouseChanged((float)(newx/2500)*acc,0,(float)(-newz/2500)*acc); } else { emit SignalPreviewMouseChanged((float)(-newx/2500)*acc,0,(float)(newz/2500)*acc); } } else{ if (event->y()<lastPos.y()) emit SignalPreviewMouseChanged(0,(float)(newy/1750)*acc,0); else { emit SignalPreviewMouseChanged(0,(float)(-newy/1750)*acc,0); } } isPressed=true; } lastPos = event->pos(); updateGL();
while in the controller:
void Controller::SlotMouseTranslationValueChanged(float val1, float val2, float val3){ if (val1!=0) sceneRef->translate(val1,0,0); if (val2!=0) sceneRef->translate(0,val2,0); if (val3!=0) sceneRef->translate(0,0,val3); facade->window->getPreview()->RebuildScene(); }
Now it has no lag and everything works fine.
Consideration:
Now I am not dragging the object but using the gluUnproject to retrieve the plan on which my object can move (then calling translate function that add\sub values to object position).So where my mouse points to is different from the position of the object on my screen.
How to achieve this result?could someone explain me the logical steps?
-14284922 0Possible dupplicate of ASP.NET MVC bind array in model
Here is blogpost explaining what you have to do.
-13858364 0If you do not want to change your pom.xml you may set the skip to true from command line using the –D option. This was mentioned above as "overridden the skip parameter within an execution". This is quite similar to -Dmaven.test.skip=true usage.
mvn site -Dcheckstyle.skip=true
-7259030 0 I know this isn't an ideal solution but you could use a HTML5 worker instead of setInterval (though I don't know if they are paused in the background as well - I'm assuming they are not, that would be very odd if they were)?
And it does add lots of backwards compatibility issues for PC browsers that are not HTML5 compliant :(
http://www.sitepoint.com/javascript-threading-html5-web-workers/
-18477199 0I just figure it out. If I don't specify the container string, it workds. Maybe something wrong with the container string.
-5947079 0It's per compute unit. The local memory is used by all workgroups executed on the compute unit. One single group can't exceed this size, since it must be executed on a single compute unit.
For example, in your case, if each workgroup requires 8K of local memory, at most two workgroups can be scheduled at the same time on each compute unit.
-29071106 0F# uses single =
for equality operator:
let t = seq { 1..10 } |> Seq.takeWhile (fun e -> e % 2 = 0)
-10430603 0 Windows-1251 or code page CP1251 is a popular 8-bit character encoding, designed to cover languages that use the Cyrillic script such as Russian, Bulgarian, Serbian Cyrillic and other languages. It is the most widely used for encoding the Bulgarian, Serbian and Macedonian languages. In modern applications, Unicode is a preferred character set.
Source and more information: Windows-1251 on the English Wikipedia
-3901814 0This strongly resembles a very similar problem in Visual Studio 2008 SP1. It was fixed with a post-SP hotfix. But there's other evidence that the hotfix didn't get incorporated into the code base, this feedback item was also a problem. It isn't that unusual for hotfixes to not get integrated back.
There isn't a feedback item that exactly describes your problem, at least that I can find. I'd recommend you file one. Given the usual trouble with reproduce bugs like this, I'd strongly recommend you include a reproduction project that exhibits this problem with instructions on how to reproduce the issue.
There is a workaround of sorts for your issue, you could go into Debug + Windows + Threads, right-click the threads you don't want to debug and select Freeze. Don't forget to Thaw them later.
These bugs were fixed again in Visual Studio 2010 Service Pack 1.
-29021123 0Try something like this:
<style> .ui-header, .ui-footer, .ui-btn-icon-notext:after { background-color: #23B14D !important; color: #fff !important; text-shadow: none !important; } .ui-btn { background-color: #fff !important; } .ui-li-has-alt a:first-child { border-top: #FFC90F 8px solid !important; } .ui-li-has-alt a:last-child { border-top: #00A3E8 8px solid !important; } </style>
You can do this with "while read" and avoid awk if you prefer:
while read a b c d e f g h i; do if [ ${a:0:2} == "Ge" ]; then echo $h $i >> allgood.txt; elif [ ${a:0:2} == "ea" ]; then echo $c $d >> allgood.txt; fi; done < abc.txt
The letters represent each column, so you'll need as many as you have columns. After that you just output the letters you need.
-18101066 0No. The code execution jumps out of the inner first loop the moment a break is encountered.
Even if the code is this way
break; continue; break;
the same thing happens. Continue is just a way to tell the compiler to iterate the loop further skipping any code in between.
-11228009 0 How to Set Access for a specific user to specific module in backend Joomla 2.5.4?I have Joomla 2.5.4 in which I have two different ype of user groups, Now I want these both user to have specific access to specififc Modules/Components at Administrator(Backend)
Please guide me to find a ay to achive this.
-11697733 0You're wrong about what's causing that error. On windows *.exe has stopped working
. generally means that your application has segmentation faulted.
This can be caused by any read or write out of the memory bounds, which generally means you messed up with a free()
/delete
, a malloc()
/new
, or a NULL
somewhere, but with more code, or without further explanation, I cannot diagnose further.
You say the data will never change, so I don't see why you need to use HTML5 IndexedDB.
You don't even need to store it in JSON format, just create the JS objects directly for optimal performance:
var data = [{ categoryName: "Animal", categoryId: 1, QA: [ { question: "Which animal barks ?", answer: "dog" }, { question: "Which animal moos ?", answer: "cow" }, ] }, { categoryName: "Grammar", categoryId: 2, QA: [ { question: "Opposite of men ?", answer: "women" }, { question: "Vowels ?", answer: "AEIOU" }, ] }];
-4867911 0 WindowsFormsSynchronizationContext.Current has Post and Send methods from which you can delegate command to UI thread
-11926172 0 I have js error , saying Object [object Object] has no method 'countdown'I have a website working fine in all browsers except IE. When I look at the console it says:
Object [object Object] has no method 'countdown'
The website name is: http://www.rivalhost.com/
The problem is with menu. Please help me out of this guys. Thanks in advance
-3105216 0Any reason not to use
Vector<Vector<server_session> >
and let it do the dynamic allocation and management for you?
-36962917 0This is a feature of javac introduced in JDK 8. You need to include -parameters
javac command line option to activate it. Then you will be able to get parameter names like this:
String name = String.class.getMethod("substring", int.class).getParameters()[0].getName() System.out.println(name);
From Spring documentation 3.3 Java 8 (as well as 6 and 7)
You can also use Java 8’s parameter name discovery (based on the -parameters compiler flag) as an alternative to compiling your code with debug information enabled.
As specified in the javadoc for ParameterNameDiscoverer class:
Parameter name discovery is not always possible, but various strategies are available to try, such as looking for debug information that may have been emitted at compile time, and looking for argname annotation values optionally accompanying AspectJ annotated methods.
This is the link to related JIRA item in Spring project Java 8 parameter name discovery for methods and constructors
JDK Enhancement Proposal JEP 118: Access to Parameter Names at Runtime
-32456111 0 gzip encoded responses doesn't decodeI use gzip encoding in php:
ob_start("ob_gzhandler"); echo json_encode($arr); ob_end_flush();
It works locally on my OpenServer, but uploaded to production it doesn't get decoded by browser.
I get
‹мќ]s›8Зї ГЕs±"...
instead of json object. Where can be an issue?
Prod headers:
Server: nginx/1.2.6 Date: Tue, 08 Sep 2015 11:30:56 GMT Content-Type: text/html; charset=WINDOWS-1251 Content-Length: 3661 Connection: keep-alive X-Powered-By: PHP/5.2.17 Content-Encoding: gzip Vary: Accept-Encoding
Local headers:
Connection:Keep-Alive Content-Encoding:gzip Content-Length:4066 Content-Type:text/html Date:Tue, 08 Sep 2015 11:30:57 GMT Keep-Alive:timeout=10, max=100 Server:Apache/2.2.27 (Win32) Vary:Accept-Encoding
-37671362 0 How to run a function in service when click on actionClick of Notification? I have written an app. But i cant solve my problem. I have an AlarmManager to push Notification. And now I want to have a button on my Notification. when I click that button, my app will run a function in service ( post request to thingspeak ) but i have tried many ways but i cant solve it. Help me plz! I have 4 classes: Activiti, Alarm_reciever, HttpRequest and RingtonePlayingService. here is my code to push notification.
public int onStartCommand(Intent intent, int flags, int startID) { Log.e("start", "startingcommand" + startID + ": " + intent); long[] v = {500, 3000}; Intent intent1 = new Intent(this.getApplicationContext(), MainActivity.class); PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent1, 0); Notification mNotify = new Notification.Builder(this) .setContentTitle("Smart Mini Garden Alarm") .setContentText("Click để kiểm tra và tưới cây !!! ") .setTicker("Đã tới giờ tưới !!") .setSmallIcon(R.drawable.iconchuan_72) .setVibrate(v) .setContentIntent(pIntent) .setAutoCancel(true) .build(); NotificationManager mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
I want to have a addAction ( button in notification bar ) And here is my httpRequest i want to run when i click On button in notification
public void postData() { String fullUrl = "https://api.thingspeak.com/update?api_key=RICJCNNCNMDURNDS&field1=1" HttpRequest mReq = new HttpRequest(); String data = ""; String response = mReq.sendPost(fullUrl,data);
What i can do next to solve my problem.
-33576948 0I solved this removing and adding the platform again.
For some reason I still had some dependecies on an old plugin I uninstalled.
-15296557 0As this is my first responsive design, I have had to use media queries to adapt the css based upon the screen/viewport size. It appears that only the "media="'screen'" and "media='print'" declarations work in IE7 and IE8 meaning my declaration of : will not work. This is the reason my background-images are not displaying because IE7 and 8 do not understand this declaration and therefore ignore it. Thanks for the other valid answers guys but they are things I already knew about and had tried.
-9970668 0 repaint function not working ..i have a problem with the repaint function
when i compile, the error is
pc3@pc3-desktop:~/Desktop$ javac LoadImageApp.java LoadImageApp.java:17: cannot find symbol symbol : method repaint(int,int,int,int,int) location: class java.awt.Graphics g.repaint(1000,0,0,1440,900) ^ 1 error
and this is my code -->
import java.awt.*; import java.awt.event.*; import java.awt.image.*; import java.io.*; import javax.imageio.*; import javax.swing.*; public class LoadImageApp extends Component { BufferedImage img; public void paint(Graphics g) { g.drawImage(img, 0, 0, null); super.update(g); g.repaint(1000,0,0,1440,900); } public LoadImageApp() { try{ img = ImageIO.read(new File("screenshot.jpg")); }catch(IOException e){} } public Dimension getPreferredSize() { if (img == null) { return new Dimension(100,100); } else { return new Dimension(img.getWidth(null), img.getHeight(null)); } } public static void main(String[] args) { JFrame f = new JFrame("Load Image "); f.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e) { System.exit(0); } }); f.add(new LoadImageApp()); f.pack(); f.setVisible(true); } }
can anyone tell me what is the problem ? i intend to do a program that is display the image and keep refreshing every 0.1 seconds . the image will be receive from other machine and every 0.1 seconds and the image will be keep override the old image ..
thanks in advance for those who reply .. THANK YOU !!!!!!
-899322 0It's a big urban legend in the Java world that calling System.gc() will actually, reliably do something for you. It won't.
It is a mere suggestion that the JVM attempt to do something. The Javadoc for the method is purposefully ambiguous in this regard.
The other big bugbear is nulling references. When a reference goes out of scope, it is already nulled by the VM, doing that yourself is redundant and misleading. If there are other references still around, they will still be available and your assignment will do nothing (unless you go and visit every other reference available -- but then, what's the point? that's what the VM is already doing).
So to answer your questions:
Here is a sample page having an issue:
http://estorkdelivery.com/template/view/69
Our website serves up a template preview. Once you enter text information and tab out of a field, the website serves up an updated preview of the image with the text added to the field.
When the server returns this image:
http://estorkdelivery.com/file/preview/verify_token:149505eb811f8856a12ec6e71e2932f082a97edf
It shows up broken with the following message in my console:
Resource interpreted as Image but transferred with MIME type text/html: http://estorkdelivery.com/file/preview/verify_token:149505eb811f8856a12ec6e71e2932f082a97edf
Trying to cover all bases, I've verified the server has the following MIME types set:
application/x-javascript .js
image/jpeg jpeg jpg jpe
image/png png
I'm not sure why this is happening. I was wondering if someone could help me troubleshoot. Any ideas?
Thanks!
Update 04/27/2012 - My question was marked down, but I have done research on this issue. If this question doesn't merit an answer, can someone at least point me in the direction I need to go in order to continue troubleshooting? I don't ask questions lightly and I have read plenty of similar issues on StackOverflow to find myself still with the same problem. It's discouraging to be marked down without a polite explanation. Thanks.
-10274848 0Ohk, its a mistake on my part.. Misunderstood what the documentation says. The documentation mentions:
A local analysis uses the same quality profile as the one used on the server for the latest analysis.
But here, on the server means not by selecting 'remotely' in sonar eclipse, but by analyzing the same project with some other runner like the simple java runner. Once the same project, (with same name) is analyzed on the server using the simple java runner, the quality profile used during that run is used when running locally through sonar-eclipse. This also means:
If you have the relevant permissions within Management Studio, this shouldn't take too long to work out. It sounds like the bad-user AD group has limited permissions within SQL Server.
You need to check the settings in Security in the GUI, and check the mappings for each of these AD groups - clicking on the databases to see what permissions they have on each database.
-12542408 0There is no such thing as a line in the DOM. But you can scroll to a element. There is a really nice jQuery extension that does it scrollTo.
But to make a bookmark could be a bit messy. Because you need both jQuery and this plugin.
To make it work you would have to book mark with:
javascript: document.location = [website url] ; [jQuery's File content] ; [the plugin] ; [jQuery scrollTo code]
Where [jQuery scrollTo code]
would be something like:
$(...).scrollTo( $('ul').get(2).childNodes[20], 800 );
-21032521 0 Retrieve parameters from List using Rcpp New to Rcpp I am testing how to retrieve and use a nested list from R with a known structure without copying parts of the list again. The small code example (with embedded R code) seems to work (cout is used for debugging).
The list rL retrieved from R may be very big so I do not want to reallocate memory (copy parts of rL). Do the current code copy parts of rL?
Best Lars
#include <Rcpp.h> #include <iostream> using namespace Rcpp; using namespace std; // [[Rcpp::export]] SEXP testing(const List rL) { List L(rL); SEXP sL2(L["L2"]); List L2(sL2); SEXP sStateGrpL2(L2["stateGroups"]); List stateGrpL2(sStateGrpL2); SEXP sStateAllocL2(L2["stateAlloc"]); CharacterVector stateAllocL2(sStateAllocL2); SEXP sActionGrpL2(L2["actionGroups"]); List actionGrpL2(sActionGrpL2); SEXP sActionAllocL2(L2["actionAlloc"]); List actionAllocL2(sActionAllocL2); vector<string> stateLabels; vector<string> actionLabels; CharacterVector actionNames; for(int n2 = 0; n2< as<int>(L2["stages"]); n2++) { stateLabels = as< vector<string> >(stateGrpL2[as<string>(stateAllocL2[n2])]); int s2Size = stateLabels.size(); SEXP sAllocA(actionAllocL2[n2]); List allocA(sAllocA); actionNames = as<CharacterVector>(allocA[0]); cout << "stage:" << n2 << " sN:" << as<string>(stateAllocL2[n2]) << "\n"; for (int s2=0; s2<s2Size; ++s2) { cout << " s:" << stateLabels[s2] << " aN:" << actionNames[s2] << "\n"; actionLabels = as< vector<string> >(actionGrpL2[ as<string>(actionNames[s2]) ]); int a2Size = actionLabels.size(); for (int a2=0; a2<a2Size; ++a2) { cout << " a:" << actionLabels[a2] << "\n"; } } } return wrap(0); } /*** R L <- list( L2=list(stages=2, stateGroups=list(s1Grp=c("a","b","c"),s2Grp=c("d","e")), stateAlloc = c(rep("s1Grp",1),rep("s2Grp",1)), actionGroups = list(a1Grp=c("terminate","keep"), a2Grp=c("finish")), actionAlloc = list(list( rep("a1Grp",3) ), list( c("a1Grp","a2Grp") ) ) ) ) testing(L) */
-1778368 1 Python float - str - float weirdness >>> float(str(0.65000000000000002)) 0.65000000000000002 >>> float(str(0.47000000000000003)) 0.46999999999999997 ???
What is going on here? How do I convert 0.47000000000000003
to string and the resultant value back to float?
I am using Python 2.5.4 on Windows.
-25629595 0The short answer is, you can't. WINE does not expose a bottled Windows environment's COM registry out to linux—and, even if it did, pywin32
doesn't build on anything but Windows.
So, here are some options, roughly ordered from the least amount of change to your code and setup to the most:
win32com
-like API, then change your code to use that to connect to the bottled Excel remotely.ssh
ing into a Windows box and running minimal WSH scripts.LibreOffice
or whatever you prefer instead of Excel.How about just causing an exception by hand, i.e. raise(SomeMeaningfulException)? That should get handled automatically by the errormiddleware.
-39549660 0You would need the schema to do that. You can a new table called as user_logs and implement a trigger which stores old_record and new_record. This will help you to get the desired log for change.
-20661904 0 LINQ create new object and order by propertywith this query I create a new object:
var allData = from op in _opg join tp in _tpg on op.DataGiorno equals tp.DataGiorno join ts in _tsg on op.DataGiorno equals ts.DataGiorno select new {op, tp, ts};
the main source, "_opg" is a List>. Basically as "op" is a DateTime type, I would order this new object by "op" in ascending way. Any hints?
-27504900 0 Android Bluetooth Paring Input DeviceI am trying to make a pairing by code and it works only for normal devices. If I use a bluetooth scanner it pairs with it but the device doesn't work till I go to android settings and select the Input Device checkbox. How can I do this by code?
Thank you.
Here is my pairing code:
public static BluetoothSocket createL2CAPBluetoothSocket(String address, int psm){ return createBluetoothSocket(TYPE_L2CAP, -1, false,false, address, psm); } // method for creating a bluetooth client socket private static BluetoothSocket createBluetoothSocket( int type, int fd, boolean auth, boolean encrypt, String address, int port){ try { Constructor<BluetoothSocket> constructor = BluetoothSocket.class.getDeclaredConstructor( int.class, int.class,boolean.class,boolean.class,String.class, int.class); constructor.setAccessible(true); BluetoothSocket clientSocket = (BluetoothSocket) constructor.newInstance(type,fd,auth,encrypt,address,port); return clientSocket; }catch (Exception e) { return null; } } private void doPair(final BluetoothDevice device, final int deviceTag) { try { Method method = device.getClass().getMethod("createBond", (Class[]) null); method.invoke(device, (Object[]) null); } catch (Exception e) { Log.e(LOG_TAG, "Cannot pair device", e); } BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) { final int state = intent.getIntExtra( BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR); final int prevState = intent.getIntExtra( BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR); if (state == BluetoothDevice.BOND_BONDED && prevState == BluetoothDevice.BOND_BONDING) { Log.d(LOG_TAG, "Paired with new device"); if (listener != null) { listener.onBluetoothPairedDeviceChange(bluetoothAdapter .getBondedDevices().iterator().next() .getName(), deviceTag); } context.unregisterReceiver(this); } else if (state == BluetoothDevice.BOND_NONE && prevState == BluetoothDevice.BOND_BONDING) { Log.d(LOG_TAG, "Cannot pair with new device"); if (listener != null) { listener.onBluetoothStatusChange(BluetoothHelper.IDLE_STATUS); } context.unregisterReceiver(this); } } } }; IntentFilter intent = new IntentFilter( BluetoothDevice.ACTION_BOND_STATE_CHANGED); context.registerReceiver(mReceiver, intent); }
-33074533 0 The statndard way to interact with ajax in Wordpress through WP AJAX.You can do like this. $.ajax( { type: 'POST', url: "/wp-admin/admin-ajax.php?action=your_action_name", dataType: 'json', cache: false, data:{ your data should be here }, success: function(response) { alert('success'); }, error: function(xhr, textStatus, errorThrown) { alert('error'); } }); then in functions.php or plugin file you need to register a hook for ajax request.wp_ajax should be prefix your action hook name and then method for processing the request. add_action('wp_ajax','method_name'); function method_name(){ here is your code }
-13271633 0 This DELETE
all the records from the table abc
with JOIN
to another table. It deletes all the records in the table abc
that has a RECORD_TYPE
value equal to the RECORD_TYPE
in the other table AND in the same time the value IN
are equals in the two table.
It is a normal DELETE
clause, Where the FROM
can contain extra joined table as specified by the documentation:
-40902580 0 Trigger background sync using notification when app not runnningFROM clause:
This extension, specifying a join, can be used instead of a subquery in the WHERE clause to identify rows to be removed.
I already implemented this:
{"aps": {"content-available": 1}}
In Apple docs on Push Notification, they are saying:
When a silent notification arrives, iOS wakes up your app in the background so that you can get new data from your server or do background information processing.
#
(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
After receive silent notification. In this method, I am downloading some data from the server then data synchronization.
EXPECTED:
The goal is when user open/using the app, it should reflect the latest position for the user.
ACTUAL:
Receive silent notification, download data from server, then data synchronization are works fine when app is running in foreground and background.
But can't wakes up the app in background and to do that when my app is not in running state (app is not launched or killed from app switcher).
QUESTION:
I silent notification doesn't work when app not running? (can't wake up app in background)
Is there missing code in my code which need implemented?
If this way doesn't work when app not running. Is there any way to keep my app local data always same/synced with the database server (when I'm using or not the app)? how other app do it?
-29819166 0set fix width in File Uploader as: style="width:300px". This will not distort the design and will restrict the filename within the given width limit
-37865171 0You can use awk with 2 files.
$> cat file.txt Hi {YOU}, it's {ME} $> cat repl.txt YOU=John ME=Leonardo $> awk -F= 'FNR==NR{a["{" $1 "}"]=$2; next} {for (i in a) gsub(i,a[i])}1' repl.txt file.txt Hi John, it's Leonardo
awk
command goes through replacement file and stores each key-value in an array a
be wrapping keys with {
and }
.Update:
To do this without creating repl.txt you can use `process substitution**:
awk -F= 'FNR==NR{a["{" $1 "}"]=$2; next} { for (i in a) gsub(i,a[i])} 1' <(( set -o posix ; set ) | grep -E '^(YOU|ME)=') file.txt
-13261719 0 In private conversation, @Nicklasos suggest me another way how to do what I need - using argv() function. It is just:
if argc() == 0 autocmd VimEnter * call RestoreSess() end
-33541798 0 for k,v in pairs(t2) do t1[k] = v end
key for string solution
-25652504 0In the basic example you need to include the ZeroClipboard.js script. I added:
<script src="ZeroClipboard.js"></script>
to the html head section. Then - which was not so clear for me either - the main.js script needs to be added after the button. I didn't reference the file (which isn't in the package as far as I could tell), but included the script directly - this way:
<button id="copy-button" data-clipboard-text="Copy Me!" title="Click to copy me.">Copy to Clipboard</button> <script type="text/javascript"> var client = new ZeroClipboard( document.getElementById("copy-button") ); client.on( "ready", function( readyEvent ) { // alert( "ZeroClipboard SWF is ready!" ); client.on( "aftercopy", function( event ) { // `this` === `client` // `event.target` === the element that was clicked event.target.style.display = "none"; alert("Copied text to clipboard: " + event.data["text/plain"] ); } ); } ); </script>
Hope this helps somebody (more than one year on I gues you have either solved it or moved on!!)
-27220201 0 Detecting or Preventing Calls to a Method from a Specific MethodI am writing a JUnit test for code submitted to a competition. The rules of the competition require that certain methods not be called from other methods. (I unfortunately can not change the rules.)
The contestants are all implementing an interface we supplied which includes an add(K key, V value)
method and a delete(K key)
method. We need to test that entries do not implement delete by adding every other element to a new object and return that object.
We are also trying to avoid adding dependencies outside of the Java core since we are using a lot of automated tools (like the Marmoset Project) to test the hundreds of submissions.
I read through the documentation for Java Reflection and Instrumentation and nothing jumped out at me.
We are using Java 8 if it makes a difference.
-18058576 0 ASP.NET MVC show collection of data in View inside of TextAreaI access data with:
public ActionResult Index() { //IEnumerable<ChatLogs> c = from p in db.ChatLogs select p; //return View(c); using (var db = new ChatLogContext()) { var list = db.ChatLogs.ToList(); return View(list); } }
I would like to know how to save this collection of data inside of TextArea in View? When we used webforms we could just textBox.Text = textBox.Text + "some data from database";
View:
@model IEnumerable<Chat.Models.ChatLogs> @Html.TextArea("chatScreen", new { @Class = "chatScreen" })
Thank you.
-17400102 0Imagine you have the following text:
BAAAAAAAAD
The following regexs will return:
/B(A+)/ => 'BAAAAAAAA' /B(A+?)/ => 'BA' /B(A*)/ => 'BAAAAAAAA' /B(A*?)/ => 'B'
The addition of the "?" to the + and * operators make them "lazy" - i.e. they will match the absolute minimum required for the expression to be true. Whereas by default the * and + operators are "greedy" and try and match AS MUCH AS POSSIBLE for the expression to be true.
Remember + means "one or more" so the minimum will be "one if possible, more if absolutely necessary" whereas the maximum will be "all if possible, one if absolutely necessary".
And * means "zero or more" so the minimum will be "nothing if possible, more if absolutely necessary" whereas the maximum will be "all if possible, zero if absolutely necessary".
-19186338 0 Rounded edges of 3d cubeI have created a 3D cube. I want the edges of the cube to be smooth and curved - not sharp.
HTML
<div class="wrap"> <div class="cube"> <div class="front">front</div> <div class="back">back</div> <div class="top">top</div> <div class="bottom">bottom</div> <div class="left">left</div> <div class="right">right</div> </div> </div>
CSS
.wrap { perspective: 800px; perspective-origin: 50% 100px; } .cube { position: relative; width: 200px; transform-style: preserve-3d; } .cube div { position: absolute; width: 200px; height: 200px; background: #aaa; } .back { transform: translateZ(-100px) rotateY(180deg); } .right { transform: rotateY(-270deg) translateX(100px); transform-origin: top right; } .left { transform: rotateY(270deg) translateX(-100px); transform-origin: center left; } .top { transform: rotateX(-90deg) translateY(-100px); transform-origin: top center; } .bottom { transform: rotateX(90deg) translateY(100px); transform-origin: bottom center; } .front { transform: translateZ(100px); } @keyframes spin { from { transform: rotateY(0); } to { transform: rotateY(360deg); }; }
For animating the cube .cube { animation: spin 5s infinite linear; }
Please help me in solving this problem.
-26837839 0 Finding the mean of more than one vectorI am tring to get the mean of three vectors but the mean function is not working.
Example:
A = [1 2 3 4 5]; B = [2 3 4 5 6]; C = [3 4 5 6 7]; V = mean(A,B,C); % should be [2 3 4 5 6] as each column is the some of the same column in A, B and C divided by three.
Any Help?
-11563130 0If you wish to reduce page sizes, I would not be looking at this technique (if it's even possible), instead I would format the source code to remove all unnecessary characters (extra spaces add data to be loaded and increase the doc size). Also, make sure your css is a streamlined as possible for example..
If you have many duplicate classes that have to have unique ids, rather than having:
uniqueclass1{ width:100px; height:100px; background:#999; } uniqueclass2{ width:100px; height:100px; background:#999; }
You can reduce this to:
uniqueclass1, uniqueclass2{ width:100px; height:100px; background:#999; }
This will help to reduce the size.
-40184850 0Add this to dims
Dim SndrName As String
then this SndrName = objItem.SenderName & "_"
next to
For Each objItem In selItems lCountEachItem = objItem.Attachments.Count SndrName = objItem.SenderName & "_" ' <--- Add this
and change the saveas
' Get the full saving path of the current attachment. strAtmtPath = strFolderPath & SndrName & atmt.FileName '
-17440004 0 Not able to install app on emulator [2013-07-03 10:24:58 - SimpleAndroid] Failed to install SimpleAndroid.apk on device 'emulator-5554! [2013-07-03 10:24:58 - SimpleAndroid] (null) [2013-07-03 10:24:59 - SimpleAndroid] Launch canceled!
I have tried all solutions as given on the web and stackover flow which includes wiping all the user data on emulator startup
I have increased the ADB connection timeout to 30000 also. My emulator and sdk are of the same version. All my packages are installed perfectly as java is working fine
Please help someone
Im trying to run multiple excel formulas in a cell in excel.
Currently i have:
=IF(E2="off", "Not Scheduled", "")
What this does is if a cell shows "1" then another cell remains blank. If a cell shows "Off" then the other cell shows "Not Scheduled"
On top of that i want to include a formula that
If G1 is less then or greater then D1 show "Missed Time Window"
So my questions:
How do i build multiple formulas into the same cell? How do i tell excel that the data in cell D1 contains a timeframe? The data in cell D1 for example shows "14:00 - 16:00" so if G1 is less then or greater then the time set in D1 then show "Missed Time Window"
-23310758 0The Boost Graph Library actually seems to have an implementation of a clique search algorithm, although I have not been able to find the documentation for it. However, you can take a look at the implementation source code of the algorithm and at this example to get an idea of how it's used. For your purpose, you could do something like this (this code compiles and works with Boost 1.55.0 and g++ 4.8.2 using flag -std=c++11
):
#include <boost/graph/undirected_graph.hpp> #include <boost/graph/bron_kerbosch_all_cliques.hpp> #include <set> #include <iostream> // this is the visitor that will process each clique found by the algorithm template <typename VertexWeight> struct max_weighted_clique { typedef typename boost::property_traits<VertexWeight>::key_type Vertex; typedef typename boost::property_traits<VertexWeight>::value_type Weight; max_weighted_clique(const VertexWeight& weight_map, std::set<Vertex>& max_clique, Weight& max_weight) : weight_map(weight_map), max_weight(max_weight), max_clique(max_clique) { // max_weight = -inf max_weight = std::numeric_limits<Weight>::lowest(); } // this is called each time a clique is found template <typename Clique, typename Graph> void clique(const Clique& c, const Graph& g) { // check the current clique value std::set<Vertex> current_clique; Weight current_weight = Weight(0); for(auto it = c.begin(); it != c.end(); ++it) { current_clique.insert(*it); current_weight += weight_map[*it]; } // if it is a bigger clique, replace if (current_weight > max_weight) { max_weight = current_weight; max_clique = current_clique; } } const VertexWeight& weight_map; std::set<Vertex> &max_clique; Weight& max_weight; }; // may replace with long, double... typedef int Weight; // this struct defines the properties of each vertex struct VertexProperty { Weight weight; std::string name; }; int main(int argc, char *argv[]) { // graph type typedef boost::undirected_graph<VertexProperty> Graph; // vertex descriptor type typedef boost::graph_traits<Graph>::vertex_descriptor Vertex; // create the graph Graph g; // add vertices Vertex v1 = boost::add_vertex(g); g[v1].weight = 5; g[v1].name = "v1"; Vertex v2 = boost::add_vertex(g); g[v2].weight = 2; g[v2].name = "v2"; Vertex v3 = boost::add_vertex(g); g[v3].weight = 6; g[v3].name = "v3"; // add edges boost::add_edge(v1, v2, g); boost::add_edge(v1, v3, g); boost::add_edge(v2, v3, g); // instantiate the visitor auto vertex_weight = boost::get(&VertexProperty::weight, g); std::set<Vertex> max_clique; Weight max_weight; max_weighted_clique<decltype(vertex_weight)> visitor(vertex_weight, max_clique, max_weight); // use the Bron-Kerbosch algorithm to find all cliques boost::bron_kerbosch_all_cliques(g, visitor); // now max_clique holds a set with the max clique vertices and max_weight holds its weight auto vertex_name = boost::get(&VertexProperty::name, g); std::cout << "Max. clique vertices:" << std::endl; for (auto it = max_clique.begin(); it != max_clique.end(); ++it) { std::cout << "\t" << vertex_name[*it] << std::endl; } std::cout << "Max. clique weight = " << max_weight << std::endl; return 0; }
I don't know if this code would perform better or worse than Cliquer (I've not done much clique searching in big graphs), but you might as well give it a try (and share your conclusions :) )
There is also a Parallel Boost Graph Library, but unfortunately it does not seem to implement a clique search algorithm (not even a "hidden" one).
Also, I've just bumped into a parallel implementation of an algorithm to find maximum cliques called MaxCliquePara. I've not used it, so I cannot talk about ease of use or performance, but it looks good. However, note that this implementation search for cliques with maximum amount of vertices, which is not exactly what you're looking for - although maybe you can tweak the code to your needs.
EDIT:
It seems that there exists some documentation about the BGL bron_kerbosch_all_cliques()
in the quickbook sources of the library. Although it's a documentation generator, it's fairly readable. So there's that.
You can do this using an attribute on your wcf service:
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)] class MySingleton : ... {...}
With this your WCF service has a single instance, that is used by all callers.
For details see: http://msdn.microsoft.com/en-us/magazine/cc163590.aspx
-26862782 0 How to use Otto event bus with Android AnnotationsI am working on an app where I want to use Android Annotations and Otto Bus Event from Square
For the integration of these two libraries together I have followed this link here. Also I have used the Otto 2.0-wip
lib that is suggested there and not that from Otto Git
.
This is how I do the implementation:
I created a singleton class for the bus:
@EBean(scope = EBean.Scope.Singleton) public class BusProviderAA extends BasicBus{ }
I declare an object for this class inside my Fragment Class
where I want to subscribe
at events :
@Bean BusProviderAA ottoBus; @AfterInject protected void initAfterInjectMFragment() .... // my stuff here ottoBus.register(this); } @Override public void onStop() { super.onStop(); ottoBus.unregister(this); } @Subscribe public void onChangeUserDetailsEvent(ChangeUserDetailsEvent mEvent){ Log.e(" s onChangeUserDetailsEvent", "ss onChangeUserDetailsEvent"); if(mEvent.msg.contains("Data_changed")){ //TODO } }
I post event to the bus from my communicator class
when it gets callback
from server communication. This is how I post event
to my bus inside this class:
@Bean //To use this enhanced class in another enhanced class or in an enhanced Android component, use @Bean: BusProviderAA ottoBus; public void callbackResponse(....){ ....// my stuff here and after callback ottoBus.post(changeUserDetailsEvent(serverResponse.getMsg())); } @Produce public ChangeUserDetailsEvent changeUserDetailsEvent(String msg){ return new ChangeUserDetailsEvent(msg); }
And this is my ChangeUserDetailsEvent
class:
public class ChangeUserDetailsEvent { public final String msg; public ChangeUserDetailsEvent(String msg) { this.msg = msg; } }
Problem: My problem is that my method which is subscribed at bus event onChangeUserDetailsEvent
doesnt get called and I dont even know how to debug to fix this problem.
I should mention that bus event works perfectly when I implement it in a Fragment
that doesn't use Annotations, and a Bus
singleton without Annotation. This is the Bus singleton class when I don't use Annotations:
public class BusProvider { private static final Bus BUS = new BasicBus(); // me lib public static Bus getInstance(){ return BUS; } private BusProvider(){} }
Thanks!
EDIT
I also have a problem when I update to androidannotations:3.2
changing my gradle file
from:
compile 'org.androidannotations:androidannotations:3.1' apt 'org.androidannotations:androidannotations:3.1'
to:
compile 'org.androidannotations:androidannotations:3.2' apt 'org.androidannotations:androidannotations:3.2'
.
For version 3.1 it compiles but doesnt work otto event bus
. With version 3.2 it gives error.This means that AA library has made some changes that I need to implement or it has bugs. How can I find the solution ?
This is one of the errors(for demonstration): Error:(27, 25) error: cannot find symbol class UserAccountActivity_ which is a class that is activity.
This is my androidannotations.log:
17:26:05.187 [Daemon Thread 13] INFO o.a.AndroidAnnotationProcessor:84 - Initialize AndroidAnnotations 3.2 with options {androidManifestFile=C:\Users\Armando\Android Studio\Hu\app\build\intermediates\manifests\full\debug\AndroidManifest.xml, resourcePackageName=XXPack} 17:26:05.244 [Daemon Thread 13] INFO o.a.AndroidAnnotationProcessor:108 - Start processing for 15 annotations on 100 elements 17:26:05.273 [Daemon Thread 13] DEBUG o.a.h.AndroidManifestFinder:98 - AndroidManifest.xml file found with specified path: C:\Users\Armando\Android Studio\Hu\app\build\intermediates\manifests\full\debug\AndroidManifest.xml 17:26:05.279 [Daemon Thread 13] INFO o.a.AndroidAnnotationProcessor:171 - AndroidManifest.xml found: AndroidManifest [applicationPackage=XXPack, componentQualifiedNames=[XXPack.SplashScreen, XXPack.HomeActivity, XXPack.ActivityProve, XXPack.UserAccountActivity_, XXPack.CartActivity_, com.facebook.LoginActivity], permissionQualifiedNames=[android.permission.INTERNET, android.permission.READ_EXTERNAL_STORAGE, android.permission.write_external_storage], applicationClassName=null, libraryProject=false, debugabble=false, minSdkVersion=14, maxSdkVersion=-1, targetSdkVersion=21] 17:26:05.280 [Daemon Thread 13] INFO o.a.r.ProjectRClassFinder:50 - Found project R class: XXPack.R 17:26:05.286 [Daemon Thread 13] INFO o.a.r.AndroidRClassFinder:44 - Found Android class: android.R 17:26:05.304 [Daemon Thread 13] INFO o.a.p.ModelValidator:42 - Validating elements 17:26:05.304 [Daemon Thread 13] DEBUG o.a.p.ModelValidator:62 - Validating with EActivityHandler: [XXPack.CartActivity, XXPack.UserAccountActivity] 17:26:05.306 [Daemon Thread 13] DEBUG o.a.p.ModelValidator:62 - Validating with EFragmentHandler: [XXPack.fragments.AddAddressFragment, XXPack.fragments.AddressBookFragment, XXPack.fragments.ChangePasswordFragment, XXPack.fragments.MyOrdersFragment, XXPack.fragments.MyVouchersFragment, XXPack.fragments.NewsLetterFragment, XXPack.fragments.PaymentMethodFragment, XXPack.fragments.PersonalDataFragment, XXPack.fragments.UserAccountFragment] 17:26:05.308 [Daemon Thread 13] DEBUG o.a.p.ModelValidator:62 - Validating with EBeanHandler: [XXPack.bus.BusProviderAA, XXPack.communicator.UserAccountCommunicator] 17:26:05.308 [Daemon Thread 13] DEBUG o.a.p.ModelValidator:62 - Validating with EViewGroupHandler: [XXPack.layouts.AddressBookItem, XXPack.layouts.CartItem, XXPack.layouts.OrdersItem, XXPack.layouts.UserAccountListFooter, XXPack.layouts.UserAccountListHeader] 17:26:05.319 [Daemon Thread 13] DEBUG o.a.p.ModelValidator:62 - Validating with ItemClickHandler: [lv_user_account(int)] 17:26:05.321 [Daemon Thread 13] DEBUG o.a.p.ModelValidator:62 - Validating with OptionsMenuHandler: [XXPack.fragments.UserAccountFragment] 17:26:05.323 [Daemon Thread 13] DEBUG o.a.p.ModelValidator:62 - Validating with BeanHandler: [ottoBus, ottoBus, communicator] 17:26:05.324 [Daemon Thread 13] DEBUG o.a.p.ModelValidator:62 - Validating with ProduceHandler: [produceNonceEvent(XXPack.models.Nonce), produceErrorEvent(XXPack.models.ErrorCommunication), produceFeatureCategoryEvent(java.util.ArrayList<XXPack.models.SimpleCategory>), produceErrorEvent(XXPack.models.ErrorCommunication), produceProductEvent(java.util.ArrayList<XXPack.models.Product>), produceErrorEvent(XXPack.models.ErrorCommunication), changeUserDetailsEvent(java.lang.String), produceErrorEvent(XXPack.models.ErrorCommunication), produceUserEvent(XXPack.models.User), produceErrorEvent(XXPack.models.ErrorCommunication)] 17:26:05.325 [Daemon Thread 13] WARN o.a.p.ModelValidator:69 - Element ProduceHandler unvalidated by 17:26:05.325 [Daemon Thread 13] WARN o.a.p.ModelValidator:69 - Element ProduceHandler unvalidated by 17:26:05.325 [Daemon Thread 13] WARN o.a.p.ModelValidator:69 - Element ProduceHandler unvalidated by 17:26:05.325 [Daemon Thread 13] WARN o.a.p.ModelValidator:69 - Element ProduceHandler unvalidated by 17:26:05.326 [Daemon Thread 13] WARN o.a.p.ModelValidator:69 - Element ProduceHandler unvalidated by 17:26:05.326 [Daemon Thread 13] WARN o.a.p.ModelValidator:69 - Element ProduceHandler unvalidated by 17:26:05.326 [Daemon Thread 13] ERROR o.a.h.AnnotationHelper:126 - @com.squareup.otto.Produce can only be used on a method with zero parameter, instead of 1 17:26:05.327 [Daemon Thread 13] WARN o.a.p.ModelValidator:69 - Element ProduceHandler unvalidated by 17:26:05.327 [Daemon Thread 13] ERROR o.a.h.AnnotationHelper:126 - @com.squareup.otto.Produce can only be used on a method with zero parameter, instead of 1 17:26:05.327 [Daemon Thread 13] WARN o.a.p.ModelValidator:69 - Element ProduceHandler unvalidated by 17:26:05.327 [Daemon Thread 13] WARN o.a.p.ModelValidator:69 - Element ProduceHandler unvalidated by 17:26:05.328 [Daemon Thread 13] WARN o.a.p.ModelValidator:69 - Element ProduceHandler unvalidated by 17:26:05.328 [Daemon Thread 13] DEBUG o.a.p.ModelValidator:62 - Validating with SubscribeHandler: [onNonceEvent(XXPack.event.NonceEvent), onErrorEvent(XXPack.event.ErrorEvent), onFeaturesAndCategory(XXPack.event.FeatureCategoryEvent), onNonceEvent(XXPack.event.NonceEvent), onErrorEvent(XXPack.event.ErrorEvent), onUserEvent(XXPack.event.UserEvent), onChangeUserDetailsEvent(XXPack.event.ChangeUserDetailsEvent)] 17:26:05.328 [Daemon Thread 13] WARN o.a.p.ModelValidator:69 - Element SubscribeHandler unvalidated by 17:26:05.328 [Daemon Thread 13] WARN o.a.p.ModelValidator:69 - Element SubscribeHandler unvalidated by 17:26:05.328 [Daemon Thread 13] WARN o.a.p.ModelValidator:69 - Element SubscribeHandler unvalidated by 17:26:05.328 [Daemon Thread 13] WARN o.a.p.ModelValidator:69 - Element SubscribeHandler unvalidated by 17:26:05.328 [Daemon Thread 13] WARN o.a.p.ModelValidator:69 - Element SubscribeHandler unvalidated by 17:26:05.328 [Daemon Thread 13] WARN o.a.p.ModelValidator:69 - Element SubscribeHandler unvalidated by 17:26:05.328 [Daemon Thread 13] DEBUG o.a.p.ModelValidator:62 - Validating with AfterInjectHandler: [initAfterInjectCart(), initAfterInjectAddAddress(), initAfterInjectAddressBook(), initAfterInjectChangePass(), initAfterInjectAddressBook(), initAfterInjectPersonalData()] 17:26:05.328 [Daemon Thread 13] DEBUG o.a.p.ModelValidator:62 - Validating with AfterViewsHandler: [initAfterViewsCart(), initUserAccountAct(), initAddAddressFragment(), initAddressFragment(), initChangePassFragment(), initMyOrdersFragment(), initMyVoucherFragment(), initNewsLetterFragment(), initPaymentFragment(), initViewsAfterViews(), initUserAccountFragment()] 17:26:05.333 [Daemon Thread 13] INFO o.a.p.ModelProcessor:69 - Processing root elements 17:26:05.338 [Daemon Thread 13] DEBUG o.a.p.ModelProcessor:160 - Processing root elements EActivityHandler: [XXPack.UserAccountActivity, XXPack.CartActivity] 17:26:05.353 [Daemon Thread 13] DEBUG o.a.p.ModelProcessor:160 - Processing root elements EFragmentHandler: [XXPack.fragments.AddressBookFragment, XXPack.fragments.AddAddressFragment, XXPack.fragments.NewsLetterFragment, XXPack.fragments.MyOrdersFragment, XXPack.fragments.UserAccountFragment, XXPack.fragments.PaymentMethodFragment, XXPack.fragments.PersonalDataFragment, XXPack.fragments.ChangePasswordFragment, XXPack.fragments.MyVouchersFragment] 17:26:05.358 [Daemon Thread 13] DEBUG o.a.p.ModelProcessor:160 - Processing root elements EBeanHandler: [XXPack.bus.BusProviderAA, XXPack.communicator.UserAccountCommunicator] 17:26:05.358 [Daemon Thread 13] DEBUG o.a.p.ModelProcessor:160 - Processing root elements EViewGroupHandler: [XXPack.layouts.CartItem, XXPack.layouts.UserAccountListFooter, XXPack.layouts.OrdersItem, XXPack.layouts.AddressBookItem, XXPack.layouts.UserAccountListHeader] 17:26:05.363 [Daemon Thread 13] INFO o.a.p.ModelProcessor:77 - Processing enclosed elements 17:26:05.368 [Daemon Thread 13] INFO o.a.AndroidAnnotationProcessor:250 - Number of files generated by AndroidAnnotations: 18 17:26:05.368 [Daemon Thread 13] INFO o.a.g.ApiCodeGenerator:52 - Writting following API classes in project: [] 17:26:05.373 [Daemon Thread 13] DEBUG o.a.g.SourceCodewriter:55 - Generating class: XXPack.bus.BusProviderAA_ 17:26:05.388 [Daemon Thread 13] DEBUG o.a.g.SourceCodewriter:55 - Generating class: XXPack.layouts.AddressBookItem_ 17:26:05.456 [Daemon Thread 13] DEBUG o.a.g.SourceCodewriter:55 - Generating class: XXPack.layouts.CartItem_ 17:26:05.468 [Daemon Thread 13] DEBUG o.a.g.SourceCodewriter:55 - Generating class: XXPack.layouts.OrdersItem_ 17:26:05.480 [Daemon Thread 13] DEBUG o.a.g.SourceCodewriter:55 - Generating class: XXPack.layouts.UserAccountListFooter_ 17:26:05.491 [Daemon Thread 13] DEBUG o.a.g.SourceCodewriter:55 - Generating class: XXPack.layouts.UserAccountListHeader_ 17:26:05.500 [Daemon Thread 13] DEBUG o.a.g.SourceCodewriter:55 - Generating class: XXPack.CartActivity_ 17:26:05.514 [Daemon Thread 13] DEBUG o.a.g.SourceCodewriter:55 - Generating class: XXPack.UserAccountActivity_ 17:26:05.529 [Daemon Thread 13] DEBUG o.a.g.SourceCodewriter:55 - Generating class: XXPack.fragments.AddAddressFragment_ 17:26:05.546 [Daemon Thread 13] DEBUG o.a.g.SourceCodewriter:55 - Generating class: XXPack.fragments.AddressBookFragment_ 17:26:05.559 [Daemon Thread 13] DEBUG o.a.g.SourceCodewriter:55 - Generating class: XXPack.fragments.ChangePasswordFragment_ 17:26:05.587 [Daemon Thread 13] DEBUG o.a.g.SourceCodewriter:55 - Generating class: XXPack.fragments.MyOrdersFragment_ 17:26:05.600 [Daemon Thread 13] DEBUG o.a.g.SourceCodewriter:55 - Generating class: XXPack.fragments.MyVouchersFragment_ 17:26:05.613 [Daemon Thread 13] DEBUG o.a.g.SourceCodewriter:55 - Generating class: XXPack.fragments.NewsLetterFragment_ 17:26:05.624 [Daemon Thread 13] DEBUG o.a.g.SourceCodewriter:55 - Generating class: XXPack.fragments.PaymentMethodFragment_ 17:26:05.634 [Daemon Thread 13] DEBUG o.a.g.SourceCodewriter:55 - Generating class: XXPack.fragments.PersonalDataFragment_ 17:26:05.649 [Daemon Thread 13] DEBUG o.a.g.SourceCodewriter:55 - Generating class: XXPack.fragments.UserAccountFragment_ 17:26:05.664 [Daemon Thread 13] DEBUG o.a.g.SourceCodewriter:55 - Generating class: XXPack.communicator.UserAccountCommunicator_ 17:26:05.670 [Daemon Thread 13] INFO o.a.p.TimeStats:81 - Time measurements: [Whole Processing = 426 ms], [Generate Sources = 302 ms], [Process Annotations = 40 ms], [Extract Annotations = 27 ms], [Validate Annotations = 25 ms], [Find R Classes = 18 ms], [Extract Manifest = 6 ms], 17:26:05.671 [Daemon Thread 13] INFO o.a.AndroidAnnotationProcessor:122 - Finish processing
-37775833 0 in the spring configuration, taking a xml way for example, make sure that the mapper.xml files are located at the place assigned as the value of the property named mapperLocations
. Once I had it at mappers/anotherfolder/*.xml. And that causes the pain.
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="typeAliasesPackage" value="somepackage.model"/> <property name="mapperLocations" value="classpath*:mappers/*.xml"/> </bean>
-21167133 0 Adding vertical spacing to NORTH component in BorderLayout I have a JFrame with a BorderLayout
. I added a JPanel
to the NORTH side of the JFrame
. In this panel I want to add components to it in an absolute positioning. In the Center side of the JFrame I added another JPanel
which should take a huge space. However when I run the application I see nothing from the North JPanel
as the Center JPanel
occupied all the space of the JFrame
! How can I give vertical space to the North JPanel?
I really need to used absolute positioning for the north JPanel.
Here's my code:
public class AAAA extends JFrame { private JPanel contentPane; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { AAAA frame = new AAAA(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public AAAA() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 1136, 520); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); contentPane.setLayout(new BorderLayout(0, 0)); setContentPane(contentPane); JPanel panel = new JPanel(); contentPane.add(panel, BorderLayout.NORTH); panel.setLayout(null); JButton btnNewButton = new JButton("New button"); btnNewButton.setBounds(0, 0, 117, 29); panel.add(btnNewButton); JPanel panel_1 = new JPanel(); contentPane.add(panel_1, BorderLayout.CENTER); } }
-9344397 0 If you are putting multiple things inside a tag, as you are for your h2
, you need to indent them all rather than inlining one and adding a second. Haml thinks you are trying to nest your ul
inside the text above it.
= form_for @talent do |f| - if @talent.errors.any? #error_explanation %h2 = pluralize(@talent.errors.count, "error") "prohibited this user from being saved:" %ul - @talent.errors.full_messages.each do |msg| %li= msg
Or if you didn't want the text inside the h2
you've just got the indentation for your ul
wrong. Bring it back two spaces.
#error_explanation %h2= pluralize(@talent.errors.count, "error") "prohibited this user from being saved:" %ul - @talent.errors.full_messages.each do |msg| %li= msg
-15131397 0 function isNumeric(n) { return !isNaN(parseFloat(n)) && isFinite(n); }
use this function to check each input
-2813149 0$('ul#accordion a').filter(':contains(' + bctext + ')'
is now preferred to the deprecated
$('ul#accordion a').contains(bctext);
(as commented by Crescent Fresh)
-5740820 0 How to close pop up window in servlet and redirect the servlet to parent windowi am creating a pop up window through jsp and passing some selected values in pop up window to jsp. while doing this i am using servlet ie. from pop up window i am calling servlet and in servlet i am using request dispacher and forwarding the result to jsp. this whole process is working fine, but the new jsp which i am calling from servlet is coming in the same pop up window. how can i close the pop up window in servlet and redirect the servlet to parent window.
-6742728 0 How to get textbox value in to another page... php / MySQLI need to get textbox value to another php page. By clicking 'Box' icon i want to submit perticular row only. I already got row ID to 'Box' icon. How can i do that with the while loop.
thanks in advance
Tharindu
-8316226 0 Bash - Search and append stringsIf I wanted to search for a line in a file and append a string to the end of that line, how can I go about it? I.E.:
file=?
I want to search for file=?
and replace the question mark with a file path. The file path is located in a variable $FILEPATH
file=$FILEPATH
Thanks!
EDIT
sed -i -f "s,file=\?,file=$FILEPATH,g"
The above works well and is what I'm looking for but is there a way to replace the question mark? With the code above if I have the following:
FILEPATH=/file/path
Properties file:
something=? file=?
The replacement produces:
Properties file:
something=? file=/file/path?
Is there a way to replace the ?
completely?
Assuming IInteract is defined as something like
interface IInteract<T1, T2>
and you are using it for a field of a class Foo:
class Foo { List<IInteract...> field; }
Then if you want to defer the decision of what types to bind to the IInteract type arguements you need to parameterize the container class:
class Foo<T1, T2> { List<IInteract<T1, T2>> field; }
The type arguments to IInteract here will be bound when you define a concrete instantiation of the container class, like: var x = new Foo<int, double>().
This will cause the IInteract field to be of type IInteract<int, double>
for that particular instantiation of the Foo generic type.
Look at this post How to write UTF-8 characters using bulk insert in SQL Server?
Quote: You can't. You should first use a N type data field, convert your file to UTF-16 and then import it. The database does not support UTF-8.
Original answers
look at the encoding of youre text file. Should be utf8. If not this could cause problems.
Open with notepad, file-> save as and choose encoding
After this try to import as a bulk
secondly, make sure the column datatype is nvarchar and not varchar. Also see here
-39996980 0I had some troubles with the the above solution, as my data was contained in a single data frame. Using ...
data=df$A
in the aesthetics doesn't work as this will provide ggplot with a vector of class "numeric", which isn't supported.
Therefor, to overlay different columns all contained in the same data frame, I'd suggest:
vec1 <- rnorm(3000, 0, 1) vec2 <- rnorm(3000, 1, 1.5) df <- data.frame(vec1, vec2) colnames(df) <- c("A", "B") library(ggplot2) ggplot() + geom_density(aes(x=df$A), colour="red") + geom_density(aes(x=df$B), colour="blue")
For most people this might seem obvious, but for me as a beginner, it wasn't. Hope this helps.
-34470311 0 Search in JSON api url with ajaxI have an api URL it's output JSON, it is about daily deals like groupon.
I want to create a search form and client search in this json
Samle json url here
I'm decode JSON like that and show it but how to search in this api url i don't know.
$param = array( 'apiKey' => 'VN43ZG2LLHKHHIU6', 'publisherId' => 316, //'isPopular' => 'on', 'p' => $sayfasi, 'itemInPage' => $sayi ); if(isset($tagid) && $tagid !='') $param['tagIds[]'] = $tagid; if(isset($cityId) && $cityId !='') $param['cityId'] = $cityId; $jsonurl = 'http://api.myaffwebsiteurl.com/deal/browse.html?'.http_build_query($param); //$json = CurlConnect($jsonurl $json = file_get_contents($jsonurl); $json_output = json_decode($json);
Search form should search in deals: title, description
Sample deals json block
"deals":[ { "id":"1041296", "title":"Tüm Cinemaximum'larda İndirimli Sinema Biletleri 9.50 TL'den Başlayan Fiyatlarla!", "description":"Cinemaximum İndirimli Bilet Fırsatı\r\nCinemaximum'larda indirimli bilet fırsatını kaçırmayın. ", "howToUse":null, "endDate":"2015-12-26 23:59:59", "discountPercent":"41", "country":"Turkey", "businessIds":"", "latLngs":"", "city":"", "provider":"Fırsat Bu Fırsat", "realPriceWithSymbol":"16 TL", "dealPriceWithSymbol":"9.50 TL", "showDealUrl":"http://www.firsatbufirsat.com/firsat/tum-cinemaximumlarda-indirimli-sinema-biletleri?pid=316", "buyDealUrl":"http://www.firsatbufirsat.com/satin-al/1041296/tum-cinemaximumlarda-indirimli-sinema-biletleri.html?pid=316", "image200_H":"http://img1.mekan.com/files/images/deal/image/200_H/104/1041296_b9ef.jpg?r=2", "timeLeft":43377 },...
-1655132 0 For using MySQL with .NET I'd recommend you this tutorial, and for your problem specially part 6, about reading the data with a MySQLDataReader.
An (almost working) sample by copy&paste from there with some changes:
Private Sub getData() Dim conn As New MySqlConnection Dim myCommand As New MySqlCommand Dim myReader As MySqlDataReader Dim SQL As String SQL = "SELECT LabelContent FROM myTable" conn.ConnectionString = myConnString ' your connection string here' Try conn.Open() Try myCommand.Connection = conn myCommand.CommandText = SQL myReader = myCommand.ExecuteReader ' loop through all records' While myReader.Read Dim myLabelValue as String myLabelValue = myReader.GetString(myReader.GetOrdinal("LabelContent")) ' ... do something with the value, e.g. assign to label ' End While Catch myerror As MySqlException MsgBox("There was an error reading from the database: " & myerror.Message) End Try Catch myerror As MySqlException MessageBox.Show("Error connecting to the database: " & myerror.Message) Finally If conn.State <> ConnectionState.Closed Then conn.Close() End Try End Sub
-5925253 0 Why not use:
theElementYouWantToClick.onClick()
-799773 0 The short answer is "no". Unless you're talking about a very long running backgrounded process on the server side, in which case you could have a second Ajax request initiate a stop on it. But if you're talking about a regular request to an Apache/PHP server, then no... identifying which Apache thread your request was running in would be trouble enough.
It would be much easier to verify your Ajax request somehow before even starting the process; make sure it's what you want to be running. You could have a Javascript confirmation process as well if you need the user to be aware that what they are doing cannot be interrupted.
As Steven posted, having a reversal process sounds like it might be in your best interest as well.
-29879532 0 show and hide list elements in a sequenceI'm trying to show and hide list elements (that I can't advice a individual class to) in a sequence, i.e. delayed.
this is my html…
<ul id="aclass"> <?php for ($i = 0; $i < count($enties); ++$i) : <li class="animation"> <div id="frame"> </div> </li> <?php endfor; ?> </ul>
so far I have
$(document).ready(function() { function showpanel() { $("ul#aclass > li").each(function() { $(this).css("display", "none"); }); setTimeout(showpanel, 200) });
I want to see the first li element for two seconds, then replaced but the second one for two seconds, then the next one etc. I don't know how to select the "next" li element and to run the function on each element successively.
Thanks for help.
-2574676 0 Change metadata of pdf file with pypdfI'd like to create/modify the title of a pdf document using pypdf. It seems that the title is readonly. Is there a way to access this metadata r/w?
If answer positive, a piece of code would be appreciated.
Thanks
-38856907 0Your lambda receives a numpy array, which does not have a .rank
method — it is pandas's Series
and DataFrame
that have it. You can thus change it to
pctrank = lambda x: pd.Series(x).rank(pct=True).iloc[-1]
Or you could use pure numpy along the lines of this SO answer:
def pctrank(x): n = len(x) temp = x.argsort() ranks = np.empty(n) ranks[temp] = (np.arange(n) + 1) / n return ranks[-1]
-32688021 0 Main thing is : Make sure you have Build Action of your Resource Dictionary set to Resource.
-34386334 0I assume the pairs have also a corresponding value by which to group them into polygons. If you gave each group two pairs of coordinates that escribed a "rectangle" around the polygon, you could significantly limit the search with a simple SQL comparison.
The latter computation of whether or not the point is included in the actual polygon seems not practically possible with just SQL.
That's one suggestion.
-52391 0If you would just like to know how much memory is being used in your JVM, and how much is free, you could try something like this:
// Get current size of heap in bytes long heapSize = Runtime.getRuntime().totalMemory(); // Get maximum size of heap in bytes. The heap cannot grow beyond this size. // Any attempt will result in an OutOfMemoryException. long heapMaxSize = Runtime.getRuntime().maxMemory(); // Get amount of free memory within the heap in bytes. This size will increase // after garbage collection and decrease as new objects are created. long heapFreeSize = Runtime.getRuntime().freeMemory();
edit: I thought this might be helpful as the question author also stated he would like to have logic that handles "read as many rows as possible until I've used 32MB of memory."
-30209091 0 JComboBox does not trigger actionPerformed() when there is an exception on the AWT-EventQueue-0 thread //This is my test class Public class crazySwing extends JFrame { private DefaultListModel model; public crazySwing() { initUI(); } private void initUI() { Vector v= new Vector(); v.add(1); v.add(2); //comboxbox with 2 items JComboBox test = new JComboBox(v); test.addActionListener(new ClickAction()); createLayout(test); setLocationRelativeTo(null); setDefaultCloseOperation(EXIT_ON_CLOSE); } private void createLayout(JComponent... arg) { JPanel pane = (JPanel) getContentPane(); GroupLayout gl = new GroupLayout(pane); pane.setLayout(gl); pane.setToolTipText("Content pane"); gl.setAutoCreateContainerGaps(true); gl.setHorizontalGroup(gl.createSequentialGroup() .addComponent(arg[0]) .addGap(200) ); gl.setVerticalGroup(gl.createSequentialGroup() .addComponent(arg[0]) .addGap(120) ); pack(); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { crazySwing ex = new crazySwing(); ex.setVisible(true); } }); } private class ClickAction extends AbstractAction { @Override public void actionPerformed(ActionEvent e) { System.out.println("testing on exception"); //This will trigger a null Pointer exception List test = null; test.get(0); } } }
Hi guys, I'm working on a Java rich client and I encountered the above symptom. When the JComboBox is clicked for the first time, a null pointer exception will be thrown by the code and then, when I try clicking on the JComboxBox again, actionPerformed() is not triggered.
I have tried it on a JButton but it won't happen to a JButton.
This is not a question about how to resolve a NPE. Kindly read the posting title.
-108016 0What about first selecting the position of the players and goal and an equal length path and afterwards build a maze respecting the defined paths? If the paths do not intersect this should easily work, I presume
-31703086 0Adding a reference to a new dll requires restarting visual studio.
-24336955 0Events and listeners passing and receiving data.
I don't use globals.
However I don't know how to use events in raw javascript or if data passing can be done. I use jquery/node which allow for passing data and just works beautifully.
-14909719 0 Naming convention for IDs in AndroidAndroid 2.3.3.
I have a question regarding naming the IDs in Android.
Let's say I have two buttons in Activity1 (save and cancel). I name them (IDs) as btnSave and btnCancel. Now I have Activity2, where in I have save and cancel buttons as well. Both does the same functionality. What will happen if I give the IDs as btnSave and btnCancel.
Will i face a problem while compiling? When I press, R.id. and ctrl+space, will I get two btnSave and btnCancel(s) to choose from?
And most importantly, Why should I name them differently, if I should?
-15927282 0If it's not too late, I'd suggest implementing a SEQUENCE
instead of counting. You may not get strict numeric order (there can be gaps), but you'll get a unique value every time:
CREATE SEQUENCE Config_Parm_Values_Seq START WITH <1 + your current max ID>;
Also note that your INSERT
as it stands right now will behave as follows:
So, even if you don't use the sequence, I'd consider a "plain old" INSERT
instead of an INSERT ... SELECT
. This example uses the sequence:
insert into CONFIGURATION_PARAMETER_VALUES ( ID , NAME , DESCRIPTION , DATA_TYPE , VALUE_STRING , VALUE_INTEGER , VALUE_DATE , VALUE_FLOAT , VALUE_TIMESTAMP , APPLICATION_ID , DELETED ) VALUES ( Config_Parm_Values_Seq.NEXTVAL -- Use seqname.nextval to get -- the next value from the sequence , 'Alert_Statuses_AllExceptNoStatus' , 'Suspicious' , 'String' , 'RBS_EIM_AL_008' , null , null , null , null , (select MAX(ID) from APPLICATIONS where name = 'Rabobank v 1.0.0.0') , 'N')
-8704097 0 Syslog heartbeat and monitoring Does anybody know how or even if, since I can't locate much on it, syslog offers any heartbeat mechanism?
I'm specifically thinking about how to monitor the devices that offer up syslog messages.
I'm not specifically looking to use an external solution, but instead something syslog possibly offers itself, which can be monitored/interrogated and flagged if something is down.
Or is their a standard lightweight tcp-based heartbeat protocol which runs on win/linux/bsd/solaris/aix/hp-ux?
-27359113 0Try this:
searchText.getElement().getStyle().setLineHeight(20, Unit.PX);
If you want to do this often (i.e. for many components), you should consider using CSS to style the textfield. This involves:
add a stylename to the textfield
searchText.addStyleName("mytextfield");
in your CSS, define the styles for mytextfield
class:
.mytextfield { line-height: 20px }
Before everything sorry for my english, i am italian, and italians are not so good with other langs... Anyway, here's my actual code:
time_t t = time(0); struct tm * now = localtime( & t ); cout << (now->tm_mday) << '/' << (now->tm_mon + 01) << '/' << (now->tm_year + 1900) << endl; cout << (now->tm_hour) << ':' << (now->tm_min) << ':' << (now->tm_sec) << endl; cout << ; system("cls");`
Well, as you can see it prints out date(italian date order, so GG-MM-YYYY) and hour:mins:secs. Is there something like now->tm_millisecond? Or it's more complicated? As you can imagine i don't want the current date in millinseconds(millisecons passed till years 0) as almost everyone wants. I just want to get the elapsed time in MSs from the last beginning of a second. I am a beginner in c++, the basic code's took around the web. I just wan't the satisfaction to get itfinished. PLEASE DO NOT TELL ME TO MAKE BETTER THIS, TO MAKE BETTER THAT, TO USE A NEW WAY TO CLEAR SCREEN INSTEAD OF system("cls")
RESPOND TO WHAT I ASKED.
Remove:
maven { url "http://dl.bintray.com/populov/maven" }
and instead of
compile 'com.viewpagerindicator:library:2.4.1@aar'
add:
compile 'com.mcxiaoke.viewpagerindicator:library:2.4.1@aar'
Clean and sync gradle.
-10051408 0Since you should assign like this:
private int number1; public void setNumber(int value){ this.number1 = value; }
-38745811 0 This is my Item model
public class Item { [Key] public int ID { get; set; } [Display(Name = "Nazwa przedmiotu")] [Required(ErrorMessage = "Nazwa przedmiotu jest wymagana.")] public string Nazwa { get; set; } [Required(ErrorMessage = "Kategoria jest wymagana.")] public string Kategoria { get; set; } public string Magazyn { get; set; } [Required(ErrorMessage = "Kod jest wymagany.")] public string Kod { get; set; } [Display(Name = "Ilość zakupiona")] //[Required(ErrorMessage = "Ilość ogólna jest wymagana.")] public double Ilosc_zakupiona { get; set; } [Display(Name = "Ilość wypożyczona")] //[Required(ErrorMessage = "Ilość wypożyczona jest wymagana.")] public double Ilosc_wypozyczona { get; set; } [Display(Name = "Ilość magazynowa")] //[Required(ErrorMessage = "Ilość magazynowa jest wymagana.")] public double Ilosc_magazynowa { get; set; } [Display(Name = "Ilość zużyta")] //[Required(ErrorMessage = "Ilość zużyta jest wymagana.")] public double Ilosc_zuzyta { get; set; } [Display(Name = "Straty")] //[Required(ErrorMessage = "Straty są wymagane.")] public double Straty { get; set; } public string Sektor { get; set; } [Display(Name = "Półka")] public string Polka { get; set; } [Display(Name = "Pojemnik")] public string Pojemnik { get; set; } }
And the HttpPost function
[HttpPost] public ActionResult DodajPrzedmiot(Item itm) { if (ModelState.IsValid) { try { using (var db = new DatabaseContext()) { if (itm.Ilosc_zakupiona - itm.Ilosc_wypozyczona < 0) throw new ArgumentOutOfRangeException(); itm.Ilosc_magazynowa = itm.Ilosc_zakupiona - itm.Ilosc_wypozyczona; db.Items.Add(itm); //db.Database.ExecuteSqlCommand("INSERT INTO Items(Nazwa_przedmiotu, Kategoria, Kod, Ilosc_ogolna, Ilosc_pozostala, Ilosc_wypozyczona, Wartosc, Sektor, Regal) VALUES({0},{1},{2},{3},{4},{5},{6},{7},{8},{9})", itm.Nazwa_przedmiotu, itm.Kategoria, itm.Kod, itm.Ilosc_ogolna, itm.Ilosc_pozostala, itm.Ilosc_wypozyczona, itm.Wartosc, itm.Sektor, itm.Regal); db.SaveChanges(); } } catch (System.Data.Entity.Infrastructure.DbUpdateException) { ViewBag.ErrorMessage = "Istnieje już przedmiot o takiej nazwie i/lub kodzie!"; return View(); } catch (ArgumentOutOfRangeException) { ViewBag.ErrorMessage = "Ilość zakupiona i/lub wypożyczona nie mogą być mniejsze od zera!"; return View(); } } return View(); }
Well it passes to the Post function and adds all information to database and in the same time it show the same error I wrote before.
-24830030 0GLSurfaceView
is in the android.opengl
package, not android.view
.
Hence, in your XML layout file, change GLSurfaceView
to android.opengl.GLSurfaceView
.
The following provides a convenient way to add methods to a class at runtime:
imp_implementationWithBlock((void*) objc_unretainedPointer(^(id me, BOOL selected)
The method can then be added using class_addMethod(). Will these implementations eventually become cached and use the fast-track method dispatching system?
-8434690 0I don't think I've ever given a height to a tr, it just becomes as tall as the td within.
Also, you're defining a tr height of 192, but the td is 194, taking into account for the 2px border.
tr.banner { height:192px; max-height:192px; } td.banner { height:192px; max-height:192px; border-bottom:2px solid black; }
-15622090 0 You cannot have two dropdownlists with same ddlReminderMonth
.
Your controls appear and disappear after click, because of toggle. Toggle makes your code really confusing.
<div class="another"> <label for="rbPType"> Select One</label> <asp:RadioButtonList runat="server" ID="rbPType" ClientIDMode="Static"> <asp:ListItem Value="0" Text="1"></asp:ListItem> <asp:ListItem Value="1" Text="2"></asp:ListItem> <asp:ListItem Value="2" Text="3"></asp:ListItem> </asp:RadioButtonList> </div> <div id="remind"> <label for="ddlReminderMonth"> Remind Me</label> <asp:DropDownList runat="server" ID="ddlReminderMonth1" AppendDataBoundItems="true" AutoPostBack="false" /> </div> <div id="cc"> <label for="ddlReminderMonth"> Remind Me Two</label> <asp:DropDownList runat="server" ID="ddlReminderMonth2" AppendDataBoundItems="true" AutoPostBack="false" /> </div> <script> $('#rbPType').change(function () { var value = $('#rbPType input:checked').val(); if (value == '0') { $('#remind').fadeIn(); $('#cc').fadeOut(); } else if (value == '1') { // Show or hide } else { // value == '2' $('#remind').fadeOut(); $('#cc').fadeIn(); } }); </script>
-519912 0 If I am making changes to already written T-SQL, then I follow the already used convention (if there is one).
If I am writing from scratch or there is no convention, then I tend to follow your convention given in the question, except I prefer to use capital letters for keywords (just a personal preference for readability).
I think with SQL formatting as with other code format conventions, the important point is to have a convention, not what that convention is (within the realms of common sense of course!)
-40267867 0After understanding that what you want is to get one number at each press of the button and that each time you want to calculate the Min and Max I suggest:
private List<int> _numbers = new List<int>(); // Use List<int> to avoid having irrelevant 0 items private int _min; private int _max; private void Add_Data_Btn_Click(object sender, EventArgs e) { //Parse and add new number to collection (notice - this does not take care of invalid input.. var number = int.Parse(i_richTextBox1.Text); // If it is the first time iterating then this number is both the _min and _max if(_numbers.Count == 0) { _min = number; _max = number; } else { //Check if need to update _min or _max if(number < _min) _min = number; else if(number > max) _max = number; } _numbers.Add(number); }
Of course you can still use linq .Min
and Max
operations on the collection to check for the updated values but why do an o(2n)
when you can 2x o(n)
Answer before understanding latest comment:
To deal with the
0
problem:
You can use Linq Except
or check that the item isn't 0
when looking for Min and Max but I'd just suggest changing from an int[10]
to a List<int>
- That way you won't have those empty items.
If it is a list then each time the button is pressed:
private void Add_Data_Btn_Click(object sender, EventArgs e) { numberList.Add(int.Parse(i_richTextBox1.Text)); }
Getting Min and Max:
Use linq:
List<int> numbers = new List<int> {2, 5, 8, 7, 6 7}; var min = numbers.Min(); var max = numbers.Max();
Or if you want to do it in o(n)
instead of o(2n)
:
List<int> numbers = new List<int> {2, 5, 8, 7, 6 7}; int min = numbers[0]; int max = numbers[0]; foreach(item in numbers) { if(item > max) max = item; else if(item < min) min = item; }
Change way of getting numbers:
If you want to change the way you get the data from the TextBox
and get it all at once (instead of one number at a time) then use string.Split
:
string data = "2 5 8 7 6 7"; var numbers = data.Split(' ') .Select(int.Parse).ToList(); // Or if you might have more spaces: string data = "2 5 8 7 6 7"; var numbers = data.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries) .Select(int.Parse).ToList();
Actually it seems pretty OK, or at least I dont get the real problem. Take a look at the fiddle
I realized you had a missing } for your .priceWrap, maybe thats what cause your issues.
-4693073 0Give this a try:
_key_handler () { # by Dennis Williamson - 2011-01-14 # for http://stackoverflow.com/questions/4690695/remapping-keys-for-ksh-vi-mode # 2011-01-15 - added cursor color change typeset timeout=1 # whole seconds # the cursor color change sequences are for xterms that support this feature if [[ $TERM == *xterm*color* ]] then typeset color=true # change cursor color when chars are held # cursor colors - set them as you like typeset nohold="\E]12;green\a" hold="\E]12;red\a" else typeset color=false fi if [[ ${.sh.edmode} == $'\x1b' ]] # vi edit mode then case ${.sh.edchar} in j) if [[ $_kh_prevchar == j ]] then if (( $SECONDS < _kh_prevtime + timeout )) then .sh.edchar=$'\E' # remapped sequence _kh_prevchar='' $color && printf "$nohold" fi else _kh_prevchar=${.sh.edchar} .sh.edchar='' $color && printf "$hold" && # jiggle the cursor so the color change shows tput cuf1 && sleep .02 && tput cub1 fi _kh_prevtime=$SECONDS ;; *) if [[ -n $_kh_prevchar ]] then .sh.edchar=$_kh_prevchar${.sh.edchar} fi _kh_prevchar='' $color && printf "$nohold" ;; esac fi } trap _key_handler KEYBD set -o vi
Put it in a file, ~/.input.ksh
for example, and source it from your ~/.kshrc
or similar.
Pressing "j" will put it on hold. If the time runs out before pressing another "j", the first "j" will be output and the next one will be held. If another key besides "j" is pressed, the held "j" and the next character are output together. If a second "j" is pressed before time runs out, the remapped sequence will be output.
Example: Pressing "j", pause, then press "jj" will yield no response at first then "j<< Esc>>" all at once.
A difference between this and vim
is that vim
will go ahead and output the held character after the time runs out even if another key hasn't been pressed yet. Also, the timeout in this is in whole seconds, while in vim
it's in milliseconds.
I've only tested this a little and only with ksh93.
Edit: Added cursor color change.
-39506996 0Alright, so I got to work by adding the following to the Drupal settings.php:
$conf['reverse_proxy'] = TRUE; $base_url = 'https://whatever-your-domain-is.com'; $conf['reverse_proxy_addresses'] = array('internal_nginx_proxy_ip'); $conf['reverse_proxy_header'] = 'HTTP_X_FORWARDED_FOR';
This works for jwilder's nginx-proxy container(s) together with JrCs' letsencrypt companion container. The nginx container is handling the HTTPS/SSL (certificates) and talks HTTP with the Drupal-container internally. The Drupal container only needs to be run with the 3 ENV VARS VIRTUAL_HOST, LETSENCRYPT_HOST, LETSENCRYPT_EMAIL for everything to be set up and work its magic.
Only downside: The Drupal container's apache logs show the internal IP of the nginx proxy. But the nginx logs show the correct client IPs and Drupal apparently gets them right as well, so it's only a minor nuisance for me.
I guess the additions to the settings.php should also be applicable to custom/manual setups.
-23553224 0l is type of long ...
so you need to extract long instead of String like
videoLong = extras.getLong("videoId");
so the full implementation of second intent is
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final VideoView videoView; setContentView(R.layout.activity_play_video); Bundle extras; Long videoLong; if (savedInstanceState == null) { extras = getIntent().getExtras(); if (extras == null) { videoLong= null; } else { videoLong= extras.getLong("videoId"); System.out.println("video id intent 2 = " + videoLong); } }
-1350708 0 Android Layout Tricks
-32635870 0 R, ggplot2 add legend with different data frames (of different sizes)I'm trying to make a simple geom_point plot using ggplot2, but I cannot get a legend to appear. I have two data frames I am plotting from that are different lengths (~2000 rows vs ~6000 rows).
I have tried adding things like 'scale_shape_manual(values=c(21, 23)' to get it to pop up, but this has not worked. I have also tried adding 'shape = 21' into aes and 'shape = 23' into aes for their respective geom_point calls, but I got the error 'Error: Continuous value supplied to discrete scale'. Thanks for any help! See example of code below:
x1 = c(0, 1, 2, 3, 4) y1 = c(0.44, 0.64, 0.77, 0.86, 0.91) x2 = c(0, 1) y2 = c(0.42, 0.61) df1 = data.frame(x1, y1) df2 = data.frame(x2, y2) g<- ggplot(df1, aes(x = (df1[,1]), y = (df1[,2]*100))) + geom_point(colour = 'black', size = 5, fill = 'blue', shape = 21) + geom_point(data = df2, aes(x = df2[,1], y = (df2[,2]*100)), colour = 'black', size = 4, fill = 'white', shape = 23) + xlab("Consecutive Dry Years") + ylab("Percent") + ggtitle("Plot") + scale_y_continuous(limits=c(0, 100)) + scale_x_continuous(breaks=0:20) + scale_shape_manual(values=c(21, 23), name="My Legend", labels=c("Simulated", "Historical")) + # scale_fill_manual(values=c('blue', 'white'), # name="My Legend", # labels=c("Simulated", "Historical")) + # scale_colour_manual(values=c('black', 'black'), # name="My Legend", # labels=c("Simulated", "Historical")) + theme_bw() g
-18307596 0 How to check if two images are similar or not using openCV in java? I have to check if two images are similar or not in java using OpenCV, I am using OpenCV for that and using ORB
Here is my main class
System.out.println("Welcome to OpenCV " + Core.VERSION); System.loadLibrary(Core.NATIVE_LIBRARY_NAME);()); System.out.println(System.getProperty("user.dir")); File f1 = new File(System.getProperty("user.dir") + "\\test.jpg"); File f2 = new File(System.getProperty("user.dir") + "\\test2.jpg"); MatchingDemo2 m = new MatchingDemo2(); m.mth(f1.getAbsolutePath(), f2.getAbsolutePath());
And here is my MatchingDemo2.java file
public class MatchingDemo2 { public void mth(String inFile, String templateFile){ FeatureDetector detector = FeatureDetector.create(FeatureDetector.ORB); //Create descriptors //first image // generate descriptors //second image // generate descriptors System.out.println("size " + matches.size()); //HOW DO I KNOW IF IMAGES MATCHED OR NOT ???? //THIS CODE IS FOR CONNECTIONS BUT I AM NOT ABLE TO DO IT //feature and connection colors Scalar RED = new Scalar(255,0,0); Scalar GREEN = new Scalar(0,255,0); //output image Mat outputImg = new Mat(); MatOfByte drawnMatches = new MatOfByte(); //this will draw all matches, works fine Features2d.drawMatches(img1, keypoints1, img2, keypoints2, matches, outputImg, GREEN, RED, drawnMatches, Features2d.NOT_DRAW_SINGLE_POINTS); int DIST_LIMIT = 80; List<DMatch> matchList = matches.toList(); List<DMatch> matches_final = new ArrayList<DMatch>(); for(int i=0; i<matchList.size(); i++){ if(matchList.get(i).distance <= DIST_LIMIT){ matches_final.add(matches.toList().get(i)); } } MatOfDMatch matches_final_mat = new MatOfDMatch(); matches_final_mat.fromList(matches_final); for(int i=0; i< matches_final.size(); i++){ System.out.println("Good Matchs "+ matches_final.get(i)); } } }
But when i check the Good Matchs i get this
size 1x328 Good Matchs DMatch [queryIdx=0, trainIdx=93, imgIdx=0, distance=52.0] Good Matchs DMatch [queryIdx=1, trainIdx=173, imgIdx=0, distance=57.0] Good Matchs DMatch [queryIdx=2, trainIdx=92, imgIdx=0, distance=53.0] Good Matchs DMatch [queryIdx=3, trainIdx=80, imgIdx=0, distance=26.0] Good Matchs DMatch [queryIdx=5, trainIdx=164, imgIdx=0, distance=40.0] Good Matchs DMatch [queryIdx=6, trainIdx=228, imgIdx=0, distance=53.0] Good Matchs DMatch [queryIdx=7, trainIdx=179, imgIdx=0, distance=14.0] Good Matchs DMatch [queryIdx=8, trainIdx=78, imgIdx=0, distance=61.0] Good Matchs DMatch [queryIdx=9, trainIdx=166, imgIdx=0, distance=69.0] Good Matchs DMatch [queryIdx=10, trainIdx=74, imgIdx=0, distance=65.0] Good Matchs DMatch [queryIdx=11, trainIdx=245, imgIdx=0, distance=38.0] Good Matchs DMatch [queryIdx=12, trainIdx=120, imgIdx=0, distance=66.0] Good Matchs DMatch [queryIdx=13, trainIdx=244, imgIdx=0, distance=41.0] Good Matchs DMatch [queryIdx=14, trainIdx=67, imgIdx=0, distance=50.0] Good Matchs DMatch [queryIdx=15, trainIdx=185, imgIdx=0, distance=55.0] Good Matchs DMatch [queryIdx=16, trainIdx=97, imgIdx=0, distance=21.0] Good Matchs DMatch [queryIdx=17, trainIdx=172, imgIdx=0, distance=67.0] Good Matchs DMatch [queryIdx=18, trainIdx=354, imgIdx=0, distance=67.0] Good Matchs DMatch [queryIdx=19, trainIdx=302, imgIdx=0, distance=53.0] Good Matchs DMatch [queryIdx=20, trainIdx=176, imgIdx=0, distance=59.0] Good Matchs DMatch [queryIdx=21, trainIdx=60, imgIdx=0, distance=66.0] Good Matchs DMatch [queryIdx=22, trainIdx=72, imgIdx=0, distance=62.0] Good Matchs DMatch [queryIdx=23, trainIdx=63, imgIdx=0, distance=54.0] Good Matchs DMatch [queryIdx=24, trainIdx=176, imgIdx=0, distance=63.0] Good Matchs DMatch [queryIdx=25, trainIdx=49, imgIdx=0, distance=58.0] Good Matchs DMatch [queryIdx=26, trainIdx=77, imgIdx=0, distance=52.0] Good Matchs DMatch [queryIdx=27, trainIdx=302, imgIdx=0, distance=59.0] Good Matchs DMatch [queryIdx=28, trainIdx=265, imgIdx=0, distance=71.0] Good Matchs DMatch [queryIdx=29, trainIdx=67, imgIdx=0, distance=49.0] Good Matchs DMatch [queryIdx=30, trainIdx=302, imgIdx=0, distance=64.0] Good Matchs DMatch [queryIdx=31, trainIdx=265, imgIdx=0, distance=65.0] Good Matchs DMatch [queryIdx=32, trainIdx=73, imgIdx=0, distance=73.0] Good Matchs DMatch [queryIdx=33, trainIdx=67, imgIdx=0, distance=55.0] Good Matchs DMatch [queryIdx=34, trainIdx=283, imgIdx=0, distance=63.0] Good Matchs DMatch [queryIdx=35, trainIdx=145, imgIdx=0, distance=60.0] Good Matchs DMatch [queryIdx=36, trainIdx=71, imgIdx=0, distance=54.0] Good Matchs DMatch [queryIdx=37, trainIdx=167, imgIdx=0, distance=67.0] Good Matchs DMatch [queryIdx=38, trainIdx=94, imgIdx=0, distance=60.0] Good Matchs DMatch [queryIdx=39, trainIdx=88, imgIdx=0, distance=68.0] Good Matchs DMatch [queryIdx=40, trainIdx=88, imgIdx=0, distance=69.0] Good Matchs DMatch [queryIdx=41, trainIdx=179, imgIdx=0, distance=28.0] Good Matchs DMatch [queryIdx=42, trainIdx=64, imgIdx=0, distance=61.0] Good Matchs DMatch [queryIdx=43, trainIdx=223, imgIdx=0, distance=71.0] Good Matchs DMatch [queryIdx=44, trainIdx=80, imgIdx=0, distance=30.0] Good Matchs DMatch [queryIdx=45, trainIdx=196, imgIdx=0, distance=59.0] Good Matchs DMatch [queryIdx=46, trainIdx=52, imgIdx=0, distance=65.0] Good Matchs DMatch [queryIdx=47, trainIdx=93, imgIdx=0, distance=60.0] Good Matchs DMatch [queryIdx=48, trainIdx=187, imgIdx=0, distance=49.0] Good Matchs DMatch [queryIdx=49, trainIdx=179, imgIdx=0, distance=50.0] Good Matchs DMatch [queryIdx=50, trainIdx=283, imgIdx=0, distance=59.0] Good Matchs DMatch [queryIdx=51, trainIdx=171, imgIdx=0, distance=61.0] Good Matchs DMatch [queryIdx=52, trainIdx=302, imgIdx=0, distance=60.0] Good Matchs DMatch [queryIdx=53, trainIdx=67, imgIdx=0, distance=59.0] Good Matchs DMatch [queryIdx=54, trainIdx=15, imgIdx=0, distance=59.0] Good Matchs DMatch [queryIdx=55, trainIdx=173, imgIdx=0, distance=66.0] Good Matchs DMatch [queryIdx=56, trainIdx=302, imgIdx=0, distance=56.0] Good Matchs DMatch [queryIdx=57, trainIdx=47, imgIdx=0, distance=56.0] Good Matchs DMatch [queryIdx=58, trainIdx=187, imgIdx=0, distance=58.0] Good Matchs DMatch [queryIdx=59, trainIdx=344, imgIdx=0, distance=64.0] Good Matchs DMatch [queryIdx=60, trainIdx=164, imgIdx=0, distance=65.0] Good Matchs DMatch [queryIdx=61, trainIdx=125, imgIdx=0, distance=50.0] Good Matchs DMatch [queryIdx=62, trainIdx=77, imgIdx=0, distance=72.0] Good Matchs DMatch [queryIdx=63, trainIdx=22, imgIdx=0, distance=79.0] Good Matchs DMatch [queryIdx=64, trainIdx=82, imgIdx=0, distance=69.0] Good Matchs DMatch [queryIdx=65, trainIdx=93, imgIdx=0, distance=63.0] Good Matchs DMatch [queryIdx=66, trainIdx=241, imgIdx=0, distance=35.0] Good Matchs DMatch [queryIdx=67, trainIdx=80, imgIdx=0, distance=18.0] Good Matchs DMatch [queryIdx=68, trainIdx=179, imgIdx=0, distance=20.0] Good Matchs DMatch [queryIdx=69, trainIdx=242, imgIdx=0, distance=50.0] Good Matchs DMatch [queryIdx=70, trainIdx=80, imgIdx=0, distance=22.0] Good Matchs DMatch [queryIdx=71, trainIdx=179, imgIdx=0, distance=19.0] Good Matchs DMatch [queryIdx=72, trainIdx=92, imgIdx=0, distance=59.0] Good Matchs DMatch [queryIdx=73, trainIdx=94, imgIdx=0, distance=56.0] Good Matchs DMatch [queryIdx=74, trainIdx=173, imgIdx=0, distance=49.0] Good Matchs DMatch [queryIdx=75, trainIdx=94, imgIdx=0, distance=59.0] Good Matchs DMatch [queryIdx=76, trainIdx=94, imgIdx=0, distance=48.0] Good Matchs DMatch [queryIdx=77, trainIdx=92, imgIdx=0, distance=52.0] Good Matchs DMatch [queryIdx=78, trainIdx=80, imgIdx=0, distance=20.0] Good Matchs DMatch [queryIdx=80, trainIdx=119, imgIdx=0, distance=61.0] Good Matchs DMatch [queryIdx=81, trainIdx=228, imgIdx=0, distance=47.0] Good Matchs DMatch [queryIdx=82, trainIdx=179, imgIdx=0, distance=14.0] Good Matchs DMatch [queryIdx=83, trainIdx=227, imgIdx=0, distance=52.0] Good Matchs DMatch [queryIdx=84, trainIdx=84, imgIdx=0, distance=57.0] Good Matchs DMatch [queryIdx=85, trainIdx=245, imgIdx=0, distance=40.0] Good Matchs DMatch [queryIdx=86, trainIdx=58, imgIdx=0, distance=64.0] Good Matchs DMatch [queryIdx=87, trainIdx=14, imgIdx=0, distance=62.0] Good Matchs DMatch [queryIdx=88, trainIdx=187, imgIdx=0, distance=61.0] Good Matchs DMatch [queryIdx=89, trainIdx=185, imgIdx=0, distance=57.0] Good Matchs DMatch [queryIdx=90, trainIdx=178, imgIdx=0, distance=25.0] Good Matchs DMatch [queryIdx=91, trainIdx=220, imgIdx=0, distance=56.0] Good Matchs DMatch [queryIdx=92, trainIdx=205, imgIdx=0, distance=59.0] Good Matchs DMatch [queryIdx=93, trainIdx=60, imgIdx=0, distance=61.0] Good Matchs DMatch [queryIdx=94, trainIdx=44, imgIdx=0, distance=59.0] Good Matchs DMatch [queryIdx=95, trainIdx=16, imgIdx=0, distance=72.0] Good Matchs DMatch [queryIdx=96, trainIdx=157, imgIdx=0, distance=63.0] Good Matchs DMatch [queryIdx=97, trainIdx=135, imgIdx=0, distance=52.0] Good Matchs DMatch [queryIdx=98, trainIdx=60, imgIdx=0, distance=61.0] Good Matchs DMatch [queryIdx=99, trainIdx=344, imgIdx=0, distance=60.0] Good Matchs DMatch [queryIdx=100, trainIdx=77, imgIdx=0, distance=67.0] Good Matchs DMatch [queryIdx=101, trainIdx=95, imgIdx=0, distance=76.0] Good Matchs DMatch [queryIdx=102, trainIdx=72, imgIdx=0, distance=45.0] Good Matchs DMatch [queryIdx=103, trainIdx=134, imgIdx=0, distance=70.0] Good Matchs DMatch [queryIdx=104, trainIdx=154, imgIdx=0, distance=54.0] Good Matchs DMatch [queryIdx=105, trainIdx=208, imgIdx=0, distance=77.0] Good Matchs DMatch [queryIdx=106, trainIdx=73, imgIdx=0, distance=79.0] Good Matchs DMatch [queryIdx=107, trainIdx=72, imgIdx=0, distance=61.0] Good Matchs DMatch [queryIdx=108, trainIdx=64, imgIdx=0, distance=73.0] Good Matchs DMatch [queryIdx=109, trainIdx=72, imgIdx=0, distance=63.0] Good Matchs DMatch [queryIdx=110, trainIdx=365, imgIdx=0, distance=66.0] Good Matchs DMatch [queryIdx=111, trainIdx=148, imgIdx=0, distance=64.0] Good Matchs DMatch [queryIdx=112, trainIdx=81, imgIdx=0, distance=42.0] Good Matchs DMatch [queryIdx=113, trainIdx=56, imgIdx=0, distance=62.0] Good Matchs DMatch [queryIdx=114, trainIdx=162, imgIdx=0, distance=48.0] Good Matchs DMatch [queryIdx=115, trainIdx=56, imgIdx=0, distance=56.0] Good Matchs DMatch [queryIdx=116, trainIdx=120, imgIdx=0, distance=58.0] Good Matchs DMatch [queryIdx=117, trainIdx=72, imgIdx=0, distance=59.0] Good Matchs DMatch [queryIdx=118, trainIdx=92, imgIdx=0, distance=63.0] Good Matchs DMatch [queryIdx=119, trainIdx=131, imgIdx=0, distance=59.0] Good Matchs DMatch [queryIdx=120, trainIdx=72, imgIdx=0, distance=46.0] Good Matchs DMatch [queryIdx=121, trainIdx=74, imgIdx=0, distance=78.0] Good Matchs DMatch [queryIdx=122, trainIdx=94, imgIdx=0, distance=56.0] Good Matchs DMatch [queryIdx=123, trainIdx=72, imgIdx=0, distance=52.0] Good Matchs DMatch [queryIdx=124, trainIdx=134, imgIdx=0, distance=71.0] Good Matchs DMatch [queryIdx=125, trainIdx=72, imgIdx=0, distance=46.0] Good Matchs DMatch [queryIdx=126, trainIdx=15, imgIdx=0, distance=73.0] Good Matchs DMatch [queryIdx=127, trainIdx=72, imgIdx=0, distance=50.0] Good Matchs DMatch [queryIdx=128, trainIdx=93, imgIdx=0, distance=56.0] Good Matchs DMatch [queryIdx=129, trainIdx=68, imgIdx=0, distance=46.0] Good Matchs DMatch [queryIdx=130, trainIdx=205, imgIdx=0, distance=65.0] Good Matchs DMatch [queryIdx=131, trainIdx=187, imgIdx=0, distance=59.0] Good Matchs DMatch [queryIdx=132, trainIdx=72, imgIdx=0, distance=47.0] Good Matchs DMatch [queryIdx=133, trainIdx=220, imgIdx=0, distance=57.0] Good Matchs DMatch [queryIdx=134, trainIdx=289, imgIdx=0, distance=60.0] Good Matchs DMatch [queryIdx=135, trainIdx=82, imgIdx=0, distance=65.0] Good Matchs DMatch [queryIdx=136, trainIdx=93, imgIdx=0, distance=53.0] Good Matchs DMatch [queryIdx=137, trainIdx=244, imgIdx=0, distance=18.0] Good Matchs DMatch [queryIdx=138, trainIdx=244, imgIdx=0, distance=25.0] Good Matchs DMatch [queryIdx=139, trainIdx=92, imgIdx=0, distance=66.0] Good Matchs DMatch [queryIdx=140, trainIdx=244, imgIdx=0, distance=20.0] Good Matchs DMatch [queryIdx=141, trainIdx=93, imgIdx=0, distance=45.0] Good Matchs DMatch [queryIdx=142, trainIdx=93, imgIdx=0, distance=51.0] Good Matchs DMatch [queryIdx=143, trainIdx=94, imgIdx=0, distance=51.0] Good Matchs DMatch [queryIdx=144, trainIdx=94, imgIdx=0, distance=40.0] Good Matchs DMatch [queryIdx=145, trainIdx=93, imgIdx=0, distance=47.0] Good Matchs DMatch [queryIdx=146, trainIdx=244, imgIdx=0, distance=28.0] Good Matchs DMatch [queryIdx=147, trainIdx=172, imgIdx=0, distance=77.0] Good Matchs DMatch [queryIdx=148, trainIdx=170, imgIdx=0, distance=72.0] Good Matchs DMatch [queryIdx=149, trainIdx=261, imgIdx=0, distance=72.0] Good Matchs DMatch [queryIdx=150, trainIdx=228, imgIdx=0, distance=55.0] Good Matchs DMatch [queryIdx=151, trainIdx=179, imgIdx=0, distance=19.0] Good Matchs DMatch [queryIdx=152, trainIdx=227, imgIdx=0, distance=60.0] Good Matchs DMatch [queryIdx=153, trainIdx=107, imgIdx=0, distance=56.0] Good Matchs DMatch [queryIdx=154, trainIdx=174, imgIdx=0, distance=41.0] Good Matchs DMatch [queryIdx=155, trainIdx=283, imgIdx=0, distance=76.0] Good Matchs DMatch [queryIdx=156, trainIdx=254, imgIdx=0, distance=59.0] Good Matchs DMatch [queryIdx=157, trainIdx=185, imgIdx=0, distance=51.0] Good Matchs DMatch [queryIdx=158, trainIdx=178, imgIdx=0, distance=30.0] Good Matchs DMatch [queryIdx=159, trainIdx=278, imgIdx=0, distance=53.0] Good Matchs DMatch [queryIdx=160, trainIdx=91, imgIdx=0, distance=62.0] Good Matchs DMatch [queryIdx=161, trainIdx=148, imgIdx=0, distance=59.0] Good Matchs DMatch [queryIdx=162, trainIdx=157, imgIdx=0, distance=63.0] Good Matchs DMatch [queryIdx=163, trainIdx=373, imgIdx=0, distance=73.0] Good Matchs DMatch [queryIdx=164, trainIdx=226, imgIdx=0, distance=48.0] Good Matchs DMatch [queryIdx=165, trainIdx=278, imgIdx=0, distance=64.0] Good Matchs DMatch [queryIdx=166, trainIdx=283, imgIdx=0, distance=62.0] Good Matchs DMatch [queryIdx=167, trainIdx=196, imgIdx=0, distance=64.0] Good Matchs DMatch [queryIdx=168, trainIdx=344, imgIdx=0, distance=59.0] Good Matchs DMatch [queryIdx=169, trainIdx=157, imgIdx=0, distance=53.0] Good Matchs DMatch [queryIdx=170, trainIdx=144, imgIdx=0, distance=79.0] Good Matchs DMatch [queryIdx=171, trainIdx=154, imgIdx=0, distance=61.0] Good Matchs DMatch [queryIdx=172, trainIdx=211, imgIdx=0, distance=75.0] Good Matchs DMatch [queryIdx=173, trainIdx=279, imgIdx=0, distance=64.0] Good Matchs DMatch [queryIdx=174, trainIdx=211, imgIdx=0, distance=79.0] Good Matchs DMatch [queryIdx=175, trainIdx=220, imgIdx=0, distance=68.0] Good Matchs DMatch [queryIdx=176, trainIdx=218, imgIdx=0, distance=45.0] Good Matchs DMatch [queryIdx=177, trainIdx=289, imgIdx=0, distance=75.0] Good Matchs DMatch [queryIdx=178, trainIdx=223, imgIdx=0, distance=63.0] Good Matchs DMatch [queryIdx=179, trainIdx=57, imgIdx=0, distance=65.0] Good Matchs DMatch [queryIdx=180, trainIdx=36, imgIdx=0, distance=73.0] Good Matchs DMatch [queryIdx=181, trainIdx=111, imgIdx=0, distance=72.0] Good Matchs DMatch [queryIdx=182, trainIdx=93, imgIdx=0, distance=65.0] Good Matchs DMatch [queryIdx=183, trainIdx=137, imgIdx=0, distance=63.0] Good Matchs DMatch [queryIdx=184, trainIdx=157, imgIdx=0, distance=60.0] Good Matchs DMatch [queryIdx=185, trainIdx=72, imgIdx=0, distance=61.0] Good Matchs DMatch [queryIdx=186, trainIdx=172, imgIdx=0, distance=47.0] Good Matchs DMatch [queryIdx=187, trainIdx=279, imgIdx=0, distance=69.0] Good Matchs DMatch [queryIdx=188, trainIdx=72, imgIdx=0, distance=55.0] Good Matchs DMatch [queryIdx=189, trainIdx=96, imgIdx=0, distance=61.0] Good Matchs DMatch [queryIdx=190, trainIdx=220, imgIdx=0, distance=68.0] Good Matchs DMatch [queryIdx=191, trainIdx=93, imgIdx=0, distance=48.0] Good Matchs DMatch [queryIdx=192, trainIdx=279, imgIdx=0, distance=54.0] Good Matchs DMatch [queryIdx=193, trainIdx=157, imgIdx=0, distance=54.0] Good Matchs DMatch [queryIdx=194, trainIdx=91, imgIdx=0, distance=65.0] Good Matchs DMatch [queryIdx=195, trainIdx=278, imgIdx=0, distance=66.0] Good Matchs DMatch [queryIdx=196, trainIdx=220, imgIdx=0, distance=57.0] Good Matchs DMatch [queryIdx=197, trainIdx=74, imgIdx=0, distance=63.0] Good Matchs DMatch [queryIdx=198, trainIdx=93, imgIdx=0, distance=34.0] Good Matchs DMatch [queryIdx=199, trainIdx=81, imgIdx=0, distance=53.0] Good Matchs DMatch [queryIdx=200, trainIdx=93, imgIdx=0, distance=45.0] Good Matchs DMatch [queryIdx=201, trainIdx=90, imgIdx=0, distance=52.0] Good Matchs DMatch [queryIdx=202, trainIdx=93, imgIdx=0, distance=52.0] Good Matchs DMatch [queryIdx=203, trainIdx=94, imgIdx=0, distance=42.0] Good Matchs DMatch [queryIdx=204, trainIdx=93, imgIdx=0, distance=35.0] Good Matchs DMatch [queryIdx=205, trainIdx=94, imgIdx=0, distance=44.0] Good Matchs DMatch [queryIdx=206, trainIdx=90, imgIdx=0, distance=72.0] Good Matchs DMatch [queryIdx=207, trainIdx=179, imgIdx=0, distance=54.0] Good Matchs DMatch [queryIdx=208, trainIdx=92, imgIdx=0, distance=48.0] Good Matchs DMatch [queryIdx=209, trainIdx=91, imgIdx=0, distance=61.0] Good Matchs DMatch [queryIdx=210, trainIdx=119, imgIdx=0, distance=77.0] Good Matchs DMatch [queryIdx=211, trainIdx=227, imgIdx=0, distance=66.0] Good Matchs DMatch [queryIdx=212, trainIdx=186, imgIdx=0, distance=56.0] Good Matchs DMatch [queryIdx=213, trainIdx=96, imgIdx=0, distance=69.0] Good Matchs DMatch [queryIdx=214, trainIdx=77, imgIdx=0, distance=52.0] Good Matchs DMatch [queryIdx=215, trainIdx=372, imgIdx=0, distance=67.0] Good Matchs DMatch [queryIdx=216, trainIdx=334, imgIdx=0, distance=69.0] Good Matchs DMatch [queryIdx=217, trainIdx=278, imgIdx=0, distance=67.0] Good Matchs DMatch [queryIdx=218, trainIdx=325, imgIdx=0, distance=61.0] Good Matchs DMatch [queryIdx=219, trainIdx=188, imgIdx=0, distance=60.0] Good Matchs DMatch [queryIdx=220, trainIdx=340, imgIdx=0, distance=56.0] Good Matchs DMatch [queryIdx=221, trainIdx=72, imgIdx=0, distance=64.0] Good Matchs DMatch [queryIdx=222, trainIdx=278, imgIdx=0, distance=69.0] Good Matchs DMatch [queryIdx=223, trainIdx=221, imgIdx=0, distance=72.0] Good Matchs DMatch [queryIdx=224, trainIdx=339, imgIdx=0, distance=74.0] Good Matchs DMatch [queryIdx=225, trainIdx=155, imgIdx=0, distance=66.0] Good Matchs DMatch [queryIdx=226, trainIdx=278, imgIdx=0, distance=56.0] Good Matchs DMatch [queryIdx=227, trainIdx=165, imgIdx=0, distance=78.0] Good Matchs DMatch [queryIdx=228, trainIdx=279, imgIdx=0, distance=71.0] Good Matchs DMatch [queryIdx=229, trainIdx=355, imgIdx=0, distance=65.0] Good Matchs DMatch [queryIdx=231, trainIdx=69, imgIdx=0, distance=80.0] Good Matchs DMatch [queryIdx=232, trainIdx=278, imgIdx=0, distance=65.0] Good Matchs DMatch [queryIdx=233, trainIdx=65, imgIdx=0, distance=71.0] Good Matchs DMatch [queryIdx=234, trainIdx=93, imgIdx=0, distance=79.0] Good Matchs DMatch [queryIdx=235, trainIdx=203, imgIdx=0, distance=78.0] Good Matchs DMatch [queryIdx=236, trainIdx=159, imgIdx=0, distance=70.0] Good Matchs DMatch [queryIdx=237, trainIdx=93, imgIdx=0, distance=45.0] Good Matchs DMatch [queryIdx=238, trainIdx=172, imgIdx=0, distance=58.0] Good Matchs DMatch [queryIdx=239, trainIdx=374, imgIdx=0, distance=67.0] Good Matchs DMatch [queryIdx=240, trainIdx=278, imgIdx=0, distance=59.0] Good Matchs DMatch [queryIdx=241, trainIdx=223, imgIdx=0, distance=55.0] Good Matchs DMatch [queryIdx=242, trainIdx=365, imgIdx=0, distance=58.0] Good Matchs DMatch [queryIdx=243, trainIdx=91, imgIdx=0, distance=62.0] Good Matchs DMatch [queryIdx=244, trainIdx=238, imgIdx=0, distance=57.0] Good Matchs DMatch [queryIdx=245, trainIdx=299, imgIdx=0, distance=62.0] Good Matchs DMatch [queryIdx=246, trainIdx=289, imgIdx=0, distance=63.0] Good Matchs DMatch [queryIdx=247, trainIdx=93, imgIdx=0, distance=41.0] Good Matchs DMatch [queryIdx=249, trainIdx=5, imgIdx=0, distance=56.0] Good Matchs DMatch [queryIdx=250, trainIdx=93, imgIdx=0, distance=53.0] Good Matchs DMatch [queryIdx=251, trainIdx=93, imgIdx=0, distance=34.0] Good Matchs DMatch [queryIdx=252, trainIdx=97, imgIdx=0, distance=34.0] Good Matchs DMatch [queryIdx=253, trainIdx=93, imgIdx=0, distance=37.0] Good Matchs DMatch [queryIdx=254, trainIdx=174, imgIdx=0, distance=55.0] Good Matchs DMatch [queryIdx=255, trainIdx=91, imgIdx=0, distance=72.0] Good Matchs DMatch [queryIdx=256, trainIdx=81, imgIdx=0, distance=59.0] Good Matchs DMatch [queryIdx=257, trainIdx=92, imgIdx=0, distance=57.0] Good Matchs DMatch [queryIdx=258, trainIdx=212, imgIdx=0, distance=76.0] Good Matchs DMatch [queryIdx=259, trainIdx=119, imgIdx=0, distance=67.0] Good Matchs DMatch [queryIdx=260, trainIdx=228, imgIdx=0, distance=73.0] Good Matchs DMatch [queryIdx=261, trainIdx=119, imgIdx=0, distance=68.0] Good Matchs DMatch [queryIdx=263, trainIdx=266, imgIdx=0, distance=74.0] Good Matchs DMatch [queryIdx=264, trainIdx=319, imgIdx=0, distance=72.0] Good Matchs DMatch [queryIdx=265, trainIdx=157, imgIdx=0, distance=76.0] Good Matchs DMatch [queryIdx=266, trainIdx=365, imgIdx=0, distance=65.0] Good Matchs DMatch [queryIdx=267, trainIdx=341, imgIdx=0, distance=76.0] Good Matchs DMatch [queryIdx=268, trainIdx=303, imgIdx=0, distance=63.0] Good Matchs DMatch [queryIdx=269, trainIdx=313, imgIdx=0, distance=69.0] Good Matchs DMatch [queryIdx=271, trainIdx=350, imgIdx=0, distance=62.0] Good Matchs DMatch [queryIdx=272, trainIdx=313, imgIdx=0, distance=68.0] Good Matchs DMatch [queryIdx=278, trainIdx=267, imgIdx=0, distance=69.0] Good Matchs DMatch [queryIdx=280, trainIdx=223, imgIdx=0, distance=71.0] Good Matchs DMatch [queryIdx=281, trainIdx=267, imgIdx=0, distance=71.0] Good Matchs DMatch [queryIdx=283, trainIdx=334, imgIdx=0, distance=72.0] Good Matchs DMatch [queryIdx=284, trainIdx=313, imgIdx=0, distance=63.0] Good Matchs DMatch [queryIdx=285, trainIdx=78, imgIdx=0, distance=76.0] Good Matchs DMatch [queryIdx=286, trainIdx=312, imgIdx=0, distance=73.0] Good Matchs DMatch [queryIdx=287, trainIdx=271, imgIdx=0, distance=68.0] Good Matchs DMatch [queryIdx=288, trainIdx=170, imgIdx=0, distance=64.0] Good Matchs DMatch [queryIdx=289, trainIdx=278, imgIdx=0, distance=64.0] Good Matchs DMatch [queryIdx=290, trainIdx=282, imgIdx=0, distance=70.0] Good Matchs DMatch [queryIdx=291, trainIdx=91, imgIdx=0, distance=65.0] Good Matchs DMatch [queryIdx=292, trainIdx=334, imgIdx=0, distance=67.0] Good Matchs DMatch [queryIdx=293, trainIdx=80, imgIdx=0, distance=72.0] Good Matchs DMatch [queryIdx=294, trainIdx=92, imgIdx=0, distance=47.0] Good Matchs DMatch [queryIdx=295, trainIdx=301, imgIdx=0, distance=44.0] Good Matchs DMatch [queryIdx=297, trainIdx=220, imgIdx=0, distance=78.0] Good Matchs DMatch [queryIdx=298, trainIdx=374, imgIdx=0, distance=76.0] Good Matchs DMatch [queryIdx=300, trainIdx=329, imgIdx=0, distance=74.0] Good Matchs DMatch [queryIdx=302, trainIdx=285, imgIdx=0, distance=77.0] Good Matchs DMatch [queryIdx=305, trainIdx=271, imgIdx=0, distance=80.0] Good Matchs DMatch [queryIdx=307, trainIdx=350, imgIdx=0, distance=76.0] Good Matchs DMatch [queryIdx=308, trainIdx=320, imgIdx=0, distance=71.0] Good Matchs DMatch [queryIdx=309, trainIdx=163, imgIdx=0, distance=76.0] Good Matchs DMatch [queryIdx=310, trainIdx=170, imgIdx=0, distance=73.0] Good Matchs DMatch [queryIdx=311, trainIdx=357, imgIdx=0, distance=65.0] Good Matchs DMatch [queryIdx=312, trainIdx=320, imgIdx=0, distance=62.0] Good Matchs DMatch [queryIdx=314, trainIdx=342, imgIdx=0, distance=75.0] Good Matchs DMatch [queryIdx=315, trainIdx=162, imgIdx=0, distance=72.0] Good Matchs DMatch [queryIdx=316, trainIdx=239, imgIdx=0, distance=74.0] Good Matchs DMatch [queryIdx=317, trainIdx=171, imgIdx=0, distance=56.0] Good Matchs DMatch [queryIdx=318, trainIdx=244, imgIdx=0, distance=61.0] Good Matchs DMatch [queryIdx=319, trainIdx=369, imgIdx=0, distance=77.0] Good Matchs DMatch [queryIdx=320, trainIdx=346, imgIdx=0, distance=67.0] Good Matchs DMatch [queryIdx=322, trainIdx=158, imgIdx=0, distance=78.0] Good Matchs DMatch [queryIdx=325, trainIdx=92, imgIdx=0, distance=73.0] Good Matchs DMatch [queryIdx=326, trainIdx=236, imgIdx=0, distance=76.0] Good Matchs DMatch [queryIdx=327, trainIdx=162, imgIdx=0, distance=70.0]
The number of matches that i get is same for the same image as well as for different images I am really confused ? Can you one explain how to compare two images and tell if they are similar or not using OpenCV
Here is somewhat that i am trying to achieve
-14387562 0As is often the case for maintaining the state of a table view cell, the right answer is to keep the state in your model. In other words, if tempArray is your model containing a collection of objects that describe the table's contents, add a BOOL attribute to those objects meaning something like userAdded
.
Then your "cell was inserted" pseudo-code can become:
MyModelClass *modelElement = [tempArray objectAtIndex:indexPath.row]; if (modelElement.userAdded) { cell.mylabel.textColor = [UIColor redColor]; } else { cell.mylabel.textColor = [UIColor blackColor]; }
-26896972 0 I am receiving a php parse error that seems to point to nothing. I uploaded this form page to my web server and it gives this error:" Parse error: syntax error, unexpected '{' in /nfs/c02/h05/mnt/28472/domains/aurorainnovations.org/html/SS/form_data.php on line 1"
This only happens on web server, on my local host everything works fine and loads correctly.
-Here is my code relative to the error.
<?php if(isset($_POST['submit'])) { require_once('recaptchalib.php'); $privatekey = "6LcwTP0SAAAAAIkWtjMa26s4Fsu8VICktkrP7ble"; $resp = recaptcha_check_answer ($privatekey,$_SERVER["REMOTE_ADDR"],$_POST["recaptcha_challenge_field"],$_POST["recaptcha_response_field"]); if (!$resp->is_valid) { die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." . "(reCAPTCHA said: " . $resp->error . ")"); } else { $your_email ='austin@aurorainnovations.com,samplerequest@aurorainnovations.com'; session_start(); $errors = ''; $name = 'Sample Request'; $email = ''; $how = $_POST['how-did-you-hear-about']; $soilbrand = $_POST['soilbrand']; $hydrobrand = $_POST['hydrobrand']; $organic = $_POST['full-partial-syntheticsonly-grower']; $localstore = $_POST['what-store-doyou-purchase']; $currentbrand = $_POST['what-brand-of-nutrients-use']; $productrequest = $_POST['productrequest']; $newproducts = $_POST['where-do-you-find-new-products']; $email = $_POST['email']; $shipto = $_POST['shipto']; if(empty($name)||empty($email)) { $errors .= "\n Name and Email are required fields. "; } if(empty($errors)) { $to = $your_email; $subject="Sample Request"; $from = $email; $ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : ''; $body = "The Following sample request was submitted\n\n". "1. HOW DID YOU HEAR ABOUT AURORA INNOVATIONS?\n". "$how\n\n". "2. WHAT BRAND OF SOIL DO YOU USE?\n". "$soilbrand\n\n". "3. IF YOU GROW HYDROPONICALLY WHAT TYPE AND BRAND OF MEDIA DO YOU USE?\n ". "$hydrobrand\n\n". "4. ARE YOU A 100% ORGANIC GROWER, PARTIAL ORGANIC GROWER OR SYNTHETICS ONLY?\n". "$organic\n\n". "5. WHAT STORE DO YOU PURCHASE GARDENING SUPPLIES AT?\n". "$localstore\n\n". "6. WHAT BRAND OF NUTRIENTS DO YOU CURRENTLY USE?\n". "$currentbrand\n\n". "7. IS THERE A SPECIFIC AURORA PRODUCT SAMPLE YOU WOULD LIKE TO TRY?\n". "$productrequest\n\n". "8. WHERE DO YOU FIND NEW PRODUCTS TO TRY?\n". "$newproducts\n\n". "9. PLEASE PROVIDE YOUR EMAIL ADDRESS.\n". "$email\n\n". "10. PLEASE PROVIDE YOUR SHIPPING ADDRESS.\n". "$shipto\n\n". "11.This request was sent from the following IP Address. Note this to prevent scammers!\n". "IP: $ip\n"; $headers = "From: $from \r\n"; $headers .= "Reply-To: $visitor_email \r\n"; mail($to, $subject, $body,$headers); header('Location: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=UADAYLDTGP4SE'); } } function IsInjected($str) { $injections = array('(\n+)', '(\r+)', '(\t+)', '(%0A+)', '(%0D+)', '(%08+)', '(%09+)' ); $inject = join('|', $injections); $inject = "/$inject/i"; if(preg_match($inject,$str)) { return true; } else { return false; } } } ?>
-8331117 0 Never parse XML with regular expressions.
Use SimpleXML
or DOMDocument
instead. Below reimplements all your code with SimpleXML
.
$url = 'http://rss.sonibyte.com/rssfeed/56.xml'; $rss = simplexml_load_file($url); $items = $rss->channel->item; // first item is this: $items[0]; // first title: $items[0]->title; // first url: $items[0]->enclosure['url']; $data = array(); foreach ($items as $item) { $data[] = array( 'title' => (string) $item->title, 'mp3' => (string) $item->enclosure['url'], ); } $jsdata = json_encode($data);
Your javascript:
$(document).ready(function(){ var playerdata = <?php echo htmlspecialchars($jsdata, ENT_NOQUOTES, 'utf-8');?>; new jPlayerPlaylist({ jPlayer: "#jquery_jplayer_1", cssSelectorAncestor: "#jp_container_1" }, playerdata, { swfPath: "js", supplied: "mp3, oga", wmode: "window" }); });
-40867029 0 How to remove defalult text when using RAF eg(Ad 1 of 1) I am working on RAF(Roku Advertising Framework) using bright script. On above image we seeing (Ad 1 of 1) when playing ads. Please give me suggestions to solve this issue, Any help much appreciated.
I am working on $metadata of Outlook.com and parsing EntityType for the specific entity. I would like to know, Why attribute ContainsTarget has "true" value for all NavigationProperty.?
Attaching the snippet for Message entity where NavigationProperty has ContainsTarget attribute.
<EntityType Name="Message" BaseType="Microsoft.OutlookServices.Item"> <Property></property> . . <Property></property> <NavigationProperty Name="Attachments" Type="Collection(Microsoft.OutlookServices.Attachment)" ContainsTarget="true"> </NavigationProperty> </EntityType>
-22964818 0 select query not work for get column using id i want to select row where driverid=903"
and get column which date is lessthen or equal to my date see screen shots
but query return me all columns what do i do? help me
SELECT * FROM driverlisence WHERE driverid='903' OR motexpiry <='2014/04/12' OR mot2expiry <='2014/04/12' OR PHCVEHICLEEXPIRY <='2014/04/12' OR insurancexpiry <='2014/04/12' OR phcdriverexpiry <='2014/04/12' OR licenseexpiry <='2014/04/12'
-16650923 0 The 960 Grid uses classes like .grid_2 .grid_3 ... .grid_n
CSS
.grid_1, .grid_2, .grid_3, .grid_4, .grid_5, .grid_6, .grid_7, .grid_8, .grid_9, .grid_10, .grid_11, .grid_12 { display: inline; float: left; margin-left: 10px; margin-right: 10px; }
Take a look on http://960.gs/demo.html
-16690820 0You have to define a JUnit task in your ant script.
<junit> <test name="my.test.TestCase"/> </junit>
See JUnit Task for documentation.
-18822469 0Your css:
<div id="featureListPanel" class="b0t70b-haAclf" style="display: block; width: 280px; z-index: 0; position: absolute; left: 0px; top: 18px;">
Change:
display: block;
To:
display: none;
-20979618 0 Unsigned integral types in C++ obey the rules of modular arithmetic, i.e. they represent the integers modulo 2N, where N is the number of value bits of the integral type (possibly less than its sizeof
times CHAR_BIT
); specifically, the type holds the values [0, 2N).
So when you multiply two numbers, the result is the remainder of the mathematical result divided by 2N.
The number N is obtainable programmatically via std::numeric_limits<T>::digits
.
Traditional EF questions starts with: My models are
public class Ingredient { public int IngredientID { get; set; } public virtual RequestedIngredient RequestedIngredient { get; set; } // other stuff } public class RequestedIngredient { [Key] string BlahBlahBlah { get; set; } public int? IngredientID { get; set; } public virtual Ingredient Ingredient { get; set; } }
Somewhere in dbContext...
modelBuilder.Entity<Ingredient>() .HasOptional<RequestedIngredient>(e => e.RequestedIngredient) .WithOptionalPrincipal(e => e.Ingredient) .Map(e => e.MapKey("IngredientID")) .WillCascadeOnDelete(false);
But I get Schema specified is not valid. Errors: (195,6) : error 0019: Each property name in a type must be unique. Property name 'IngredientID' was already defined.
If I remove IngredientID from RequestedIngredient, the db will be created just as I want to. But I have no access to IngredientID. How can I set this up to have access to foreign key?
-22840742 0 Web deploy package doesn't include databaseWhen I publish via web deploy directly from Visual Studio into IIS, the databases I configured in the project package/Publish SQL are deployed the SQL Server.
However, when I publish a Web Deploy Package
from the same project, the package does not appear to include the the database and does not deploy any db to SQL Server when either imported into IIS or when the package .cmd is run.
What am I missing?
-23698380 0You can use a webview and load a base64 string:
protected String base64Str = "+wL00h2L...."; wv1.loadData(base64Str, "text/html; charset=utf-8", "base64");
-32901345 0 You are not creating a queue of object you are just shadowing the same objects and pushing it again into the speaks array, so you will get the last version of your object several times inside the array.
If you want to create an async behavior you should try callbacks instead of a simple for
loop.
It would be better do something like this:
var speak = [ { utter: "What do they call a quarter pounder with cheese in Paris?", speaker: true }, { utter: "They don't call it a quarter pounder with cheese?", speaker: false, time: 3 }, { utter: "They got the metric system. They call it a Royale with cheese", speaker: true } ];
Then you can use array methods like filter
and map
to handle the data you need.
Finally, you can use events to trigger each speaking when something in you application happens.
-5432527 0Sharekit provides a generic sharing mechanism but also exposes individual services. For instance, if you were to share a URL on twitter, you could write the following code:
#import "ShareKit/Core/SHK.h" #import "ShareKit/Sharers/Services/Twitter/SHKTwitter.h" ... SHKItem *item = [SHKItem URL:url title:@"A title"]; [SHKTwitter shareItem:item];
This is all explained in the documentation, but don't fear exploring the header files of the individual services.
-22954616 0 Android app is not running on device[2014-04-09 11:50:19 - Dex Loader] Unable to execute dex: java.nio.BufferOverflowException. Check the Eclipse log for stack trace. [2014-04-09 11:50:19 - audiomediaplayer1] Conversion to Dalvik format failed: Unable to execute dex: java.nio.BufferOverflowException. Check the Eclipse log for stack trace.
-388397 0 Could you give some more detail?
I didn't think you could map an object via a stored proc, maybe I am misreading it.
Perhaps you want to make the sp related properties "transient", like your 'status' -so that nhibernate will leave them alone.
-27379582 0 limit the character to 10 for filter text-field - ngTableI have created an application using angularjs and ngTable with filer feature, the application is working fine also the filtering, but the filtering text-field should accept only 10 characters according to my requirement
Can anyone please tell me how to limit the character to 10 for that text-field, my code is as given below:
script
$scope.tableParams = new ngTableParams({ page: 0, count: 0 }, { total: 0, counts:[], getData: function ($defer, params) { // use build-in angular filter var orderedData = params.filter() ? $filter('filter')(data, params.filter()) : data; $defer.resolve(orderedData); } });
html
<div ng-app="main" ng-controller="DemoCtrl"> <table ng-table="tableParams" show-filter="true" class="table"> <tr ng-repeat="user in $data"> <td data-title="'Name'" filter="{ 'name': 'text' }">{{user.name}}</td> <td data-title="'Age'">{{user.age}}</td> </tr> </table> </div>
-5093337 0 jqGrid clientArray I am trying to use jqGrid clientArray to submit multiple updates at once. (I am trying to update multiple rows in one go).
onSelectRow: function(id){ if (id && id !== lastsel) { jQuery('#fnlusetaxlistings').saveRow(lastsel, true, 'clientArray'); jQuery('#fnlusetaxlistings').editRow(id, true, null, null); lastsel = id; } },
This works fine, but I have no idea that how to retrieve clientArray and send it to the server? If anyone can post an example of sending clientArray to server, it will be very helpful.
Thanks, Ashish
-39770467 0 Expandable listview group header color changesI have set the two color for alternate group header in exapandable listview. But when I click multiple times to expand or collapse the color changes to any group row.
Here is my code,
if (convertView == null) { LayoutInflater infalInflater = (LayoutInflater) this._context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = infalInflater.inflate(R.layout.list_group, null); if(groupPosition % 2 == 1) { convertView.setBackgroundColor(Color.parseColor("#3C3C3C")); }else { convertView.setBackgroundColor(Color.parseColor("#000000")); } }
This is happening after scrolling list. I have also tried this one
private int[] colors = new int[] { Color.parseColor("#000000"), Color.parseColor("#3C3C3C") }; int colorPos = groupPosition % colors.length; convertView.setBackgroundColor(colors[colorPos]);
-38804624 0 Firebase Android: enabling users during registration I'm using Firebase 9.4.0 to register and login users in my app.
I have a registration form, and I wish the administrator can enable or disable (via code, from his account inside the app) a user when asked to register.
In other words, I would like that the registration of a user can be approved (via code, not using the Firebase console) by a administrator before become effective.
How can I get this? I did not found sufficiently complete answer to this question.
Thanks!
-30915871 0 Connection timed out only for wikmedia api on server but works on localFollowing piece of code was working for the last three years, but all of a sudden it throws connection timed out only in server, but works as intended in localhost. Any comments ?
public String getWikiContent(String query) { StringBuilder builder = new StringBuilder(); String path = "https://en.wikipedia.org/w/api.php?action=query&prop=extracts&exintro=1&explaintext=1&titles=" + query + "&format=json&redirects"; try { URL url = new URL(path); HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); urlConn.setRequestProperty("Content-Type", "application/json"); if (urlConn.getResponseCode() != 200) { throw new IOException(urlConn.getResponseMessage()); } InputStream is = urlConn.getInputStream(); BufferedReader buff = new BufferedReader(new InputStreamReader(is)); String line; while ((line = buff.readLine()) != null) { builder.append(line); } }catch (IOException e){ e.printStackTrace(); } return builder.toString(); }
-23707326 0 How to fix this bizarre ConfigurationSection exceptions? I was tasked with making this third party software run on our server, but we only have partial access to the code, the rest exists only as pre-compiled libraries. One of those libraries throws enigmatic exceptions and I can't figure out why. I am completely oblivious to Visual Studio and C#, and this is making no sense at all to me.
What I initially get is:
Unhandled Exception:
Unhandled Exception: System.TypeInitializationException: The type initializer for 'GroupsImporter.Program' threw an exception. --->
System.Configuration.ConfigurationErrorsException: Configuration system failed to initialize --->
System.Configuration.ConfigurationErrorsException: Unrecognized configuration section ThirdPartyCompany.Framework.Core.Configuration.v1.2. (Y:\path-to-executable\GroupsImporter.exe.Config line 67)
at System.Configuration.ConfigurationSchemaErrors.ThrowIfErrors(Boolean ignoreLocal)
at System.Configuration.BaseConfigurationRecord.ThrowIfParseErrors(ConfigurationSchemaErrors schemaErrors)
at System.Configuration.ClientConfigurationSystem.EnsureInit(String configKey)
--- End of inner exception stack trace ---
The configuration file looks like this:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="AdWordsApi" type="System.Configuration.DictionarySectionHandler"/> <section name="AdWords.Common.Configuration" type="AdWords.Common.Configuration.AdWordsConfiguration, AdWords.Common"/> </configSections> <appSettings> ... </appSettings> <AdWords.Common.Configuration Budget ="xxx" CPC="xxx" EstoqueMinimo="x"> ... </AdWords.Common.Configuration> <AdWordsApi> ... </AdWordsApi> <system.web> ... </system.web> <system.net> ... </system.net> <ThirdPartyCompany.Framework.Core.Configuration.v1.2> ... </ThirdPartyCompany.Framework.Core.Configuration.v1.2> </configuration>
In turn if I remove the section it is complaining about, I get this:
Unhandled Exception: System.TypeInitializationException: The type initializer for 'GroupsImporter.Program' threw an exception. --->
System.Configuration.ConfigurationException: Configuraton section ThirdPartyCompany.Framework.Core.Configuration.v1.2 could not be found.
at ThirdPartyCompany.Framework.Core.Guard.Against[TException](Boolean assertion, String message)
at ThirdPartyCompany.Framework.Core.Configuration.ConfigurationSection.GetConfiguration()
at ThirdPartyCompany.Framework.Core.IoCContainerWrapper.Implementation.IoCThirdPartyCompanyContainer.loadRegisterConfiguration()
//And the stack goes on...
I have no idea on how to solve this issue. I don't have access to the code where the ServiceConfig class is implemented or where the config is consumed. Any ideas about what is going on, and how to fix this issue?
Edit: It was supposedly working on the company's server exactly as provided.
-3758572 0 Loading sprites 1 time, or many times?I'm wondering, if i'm doing this:
<div style="width:50px;height:50px;background: transparent url(sprite.png) 0px 0px no-repeat;">555</div> <div style="width:50px;height:50px;background: transparent url(sprite.png) -56px 0px no-repeat;">666</div> <div style="width:50px;height:50px;background: transparent url(sprite.png) -109px 0px no-repeat;">666</div>
Is this going to download the image 3 times ?
or is it going to download the image 1 time, and show different parts of it in the web page ?
-9936812 0 Is there a maximum to the number of elements in std::bitset?Is there a maximum to the number of elements in an std::bitset
?
In my code (VC++2010) 1<<20
crashes with a stack overflow, but 1<<19
works.
(I'm dealing with huge inputs.)
-40976333 0Python < 3:
filter(lambda x: x == dict_to_match, list_of_dict)[0]
Python 3 :
list(filter(lambda x: x == dict_to_match, list_of_dict))[0]
-4753654 0 validating controls in tabs winforms Im implementing application which has main window and in this second window which has a lot of tabs in tabcontrol.
On each tab I have a lot of control which values may be edited by user, some of them has to be filled, some need to has values between x and y and so on.
Main windows has got save button. Point is that if in any tab control isnt validated then saving shouldnt be possible and appropriate tab should be opened and validation shown. Could you please tell me any advice of how to create such mechanism ? Maybe any generic methods ?
thanks for help
-10857964 0Others have given you the probability calculation, but I think you may be asking the wrong question.
I assume the reason you're asking about the probability of the priorities being unique, and the reason for choosing n^3 in the first place, is because you're hoping they will be unique, and choosing a large range relative to n seems to be a reasonable way of achieving uniqueness.
It is much easier to ensure that the values are unique. Simply populate the array of priorities with the numbers 1 .. n and then shuffle them with the Fisher-Yates algorithm (aka algorithm P from The Art of Computer Programming, volume 2, Seminumerical Algorithms, by Donald Knuth).
The sort would then be carried out with known unique priority values.
(There are also other ways of going about getting a random permutation. It is possible to generate the nth lexicographic permutation of a sequence using factoradic numbers (or, the factorial number system), and so generate the permutation for a randomly chosen value in [1 .. n!].)
-5397752 0You could just use Tagsoup (http://ccil.org/~cowan/XML/tagsoup/), which is an xml parser which can read from html, even if badly formatted (doesn't need to be xhtml or even conform).
You then can just remove all object tags using xpath.
This is much safer than a regex, which is difficult to maintain if you want to master all edge cases.
-34645521 0 Git commits always rejected when pushing commit with file added from other branchI have two branches that diverge more than they should.
Since this has been marked as duplicate, let me clarify my question.
I already know that I can just do git push -f
to force the merge. That's what I've done already several times. My question is more about the inner workings of git. If I add a new file to my branch B, I can commit it and push it without any problem. But if I git checkout branch-A somefile.txt
and then git add
and git push
, I get the error below. Why does this kind of commit seem to always result in that error when pushing?
End edit.
To reconcile them to a common ancestor, I have to copy some files from one branch to the other. These are files that should actually have been there but got lost somehow in the process. Every time I do that using git checkout branch-A somefile.txt
, commit, and push, the origin gives me this error:
"Updates were rejected because the tip of your current branch is behind its remote counterpart. Integrate the remote branches before pushing again."
Why is that?
More detail, if needed: The two branches diverged before we started using git. Now I'm trying to sew them together. I am making sure both branches are correct and all files are identical that should be, so that I can then create a merge point that actually makes sense. They are each a branch of the same repo. In finding their common point of ancestry, I've noticed some files that should have been on both branches are missing from one or the other ( probably the result of some mistake I made when putting them under git). To fix that, I simply git checkout branch-A missingfile.txt
into branch B, git add
, git commit
, and git push
. But for some reason every time I push, I get the "out of date" error and have to do a force push. Which is fine if I know I only changed one file, but if I've changed/copied a bunch, then I always have to double check to make sure there isn't some error.
I get an error when fetching data from a MySQL database using PHP.
Undefined variable: result in C:\wamp\www\mbdb\Biomarkerresult1.php on line 20 mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in C:\wamp\www\mbdb\Biomarkerresult1.php on line 20
My dropdown list coding:
<select name="names" value="name"> <option value="Biomarker">Select a Biomarker</option> <option value="Diagnostic">Diagnostic</option> <option value="Prognsotic">Prognostic</option> <option value="Predictive">Predictive</option>
Here is displaying data:
<?php $con=mysqli_connect('localhost','root','','mbdb'); if(mysqli_errno($con)) { echo "Can't Connect to mySQL:".mysqli_connect_error(); } if(isset($_POST['names'])) { $name = $_POST['names']; $fetch="SELECT * FROM metabolites WHERE Biomarker_Category = '".$name."'"; $result = mysqli_query($con,$fetch); } while($row=mysqli_fetch_array($result)) { //----- }
Can anyone help me with this?
-18845096 0Making some assumptions and, asserting that joining on the millisecond is nonsensical, fiddle here.
CREATE TABLE Withdrawl ( Timestamp TIMESTAMP PRIMARY KEY, Amount Decimal(60, 4) ); CREATE TABLE Deposit ( Timestamp TIMESTAMP PRIMARY KEY, Amount Decimal(60, 4) ); SELECT Timestamp, -Amount FROM Withdrawl UNION ALL SELECT Timestamp, Amount FROM Deposit ORDER BY Timestamp ASC;
how about this,
SELECT Timestamp, Amount, NULL FROM Withdrawl UNION ALL SELECT Timestamp `time stamp`, NULL `amount withdrawal`, Amount `amount deposits` FROM Deposit ORDER BY Timestamp ASC;
-5765378 0 Your current search function doesn't actually do anything. I'm assuming this is homework so, no free lunch ;)
The simplest approach would be to have two recursive functions:
public boolean findStart(String word, int x, int y)
This will do a linear search of the board looking for the first character in word
. If your current location doesn't match, you call yourself with the next set of coords. When it finds a match, it calls your second recursive function using word
, the current location, and a new, empty 4x4 matrix:
public boolean findWord(String word, int x, int y, int[][] visited)
This function first checks to see if the current location matches the first letter in word
. If it does, it marks the current location in visited
and loops through all the adjoining squares except ones marked in visited
by calling itself with word.substring(1)
and those coords. If you run out of letters in word
, you've found it and return true. Note that if you're returning false, you need to remove the current location from visited
.
You can do this with one function, but by splitting out the logic I personally think it becomes easier to manage in your head. The one downside is that it does do an extra comparison for each first letter in a word. To use a single function you would need to keep track of what "mode" you were in either with a boolean or a depth counter.
Edit: Your longest word should only be 16
. Boggle uses a 4x4 board and a word can't use the same location twice. Not that this really matters, but it might for the assignment. Also note that I just did this in my head and don't know that I got it 100% right - comments appreciated.
Edit in response to comments:
Here's what your iterative locate
would look like using the method I outline above:
public boolean locate(String word) { for (int row = 0; row < 4; row++) { for (int col =0; col < 4; col++) { if (word.charAt(0) == letters[row][col]) { boolean found = findWord(word, row, col, new boolean[4][4]); if (found) return true; } } } return false; }
The same thing recursively looks like the following, which should help:
public boolean findStart(String word, int x, int y) { boolean found = false; if (word.charAt(0) == letters[x][y]) { found = findWord(word, x, y, new boolean[4][4]); } if (found) return true; else { y++; if (y > 3) { y = 0; x++; } if (x > 3) return false; } return findStart(word, x, y); }
So here's findWord()
and a helper method getAdjoining()
to show you how this all works. Note that I changed the visited
array to boolean
just because it made sense:
public boolean findWord(String word, int x, int y, boolean[][] visited) { if (letters[x][y] == word.charAt(0)) { if (word.length() == 1) // this is the last character in the word return true; else { visited[x][y] = true; List<Point> adjoining = getAdjoining(x,y,visited); for (Point p : adjoining) { boolean found = findWord(word.substring(1), p.x, p.y, visited); if (found) return true; } visited[x][y] = false; } } return false; } public List<Point> getAdjoining(int x, int y, boolean[][] visited) { List<Point> adjoining = new LinkedList<Point>(); for (int x2 = x-1; x2 <= x+1; x2++) { for (int y2 = y-1; y2 <= y+1; y2++) { if (x2 < 0 || x2 > 3 || y2 < 0 || y2 > 3 || (x2 == x && y2 == y) || visited[x2][y2]) { continue; } adjoining.add(new Point(x2,y2)); } } return adjoining; }
So now, after you get input from the user as a String
(word), you would just call:
boolean isOnBoard = findStart(word,0,0);
I did this in my head originally, then just went down that path to try and show you how it works. If I were to actually implement this I would do some things differently (mainly eliminating the double comparison of the first letter in the word, probably by combining the two into one method though you can do it by rearranging the logic in the current methods), but the above code does function and should help you better understand recursive searching.
-28088799 0You can do the same thing using the OAuth Playground.
See How do I authorise a background web app without user intervention? (canonical ?)
Step 11 will be different. Instead of pasting the refresh token into your server app (which you don't have), you'll paste the access token into your JS in the same way as you are doing in your answer.
-6185136 0The two clauses: NewCount is Count + 1
and increment(NewCount,Count)
basically have the same meaning. You didn't make clear that Count
is an input variable and it has a base case of 1
, so Prolog didn't know where to start unifying values for it. For example, you should use Count
as an input argument as follows (it doesn't change much if compared with your version):
order([],[], _). order([Head|Tail],[(Count,Head)|NewTail], Count):- NewCount is Count + 1, order(Tail, NewTail, NewCount). order(List, Result ):- order(List, Result, 1).
-10423256 0 There are several ways to achieve this. You can track pitch (lower pitch values will be male, otherwise female). Or try to build a GMM (Sphinx cannot do this, but HTK can), with one model for male, other for female and another to children.
-21697688 0 String.Format: join two value in one paddingHow can I do something like
string.Format("({{0}{1},10})", "ABC", "DEF) // ( ABCDEF) string.Format("({{0} {1},10})", "ABC", "DEF) // ( ABC DEF)
I have to solve tihs operation with format. And I do not have a chance to combine elsewhere.
So is not it possible to do something like.
Console.WriteLine(string.Format("({0,10})", "ABC" + " DEF"));
I cant use join or concat or a + b methods
Why i want only format pattern? Because of usage like this.
//Dummy metod for example public static string applyFormat(String format, String values, Object object ) { member1 = reflect from object by named extracted string member2 = reflect from object by named extracted string or members[]= exploded string return String.Format(format, member1, member2); or return String.Format(format, members); }
Usage example
Console.WriteLine(applyFormat("({ {0}{1},-10})", "Member1,Member2", object)); // "({ {0}{1},-10})": Reflect and Join Member1 and Member2 and apply padding joined value
Thanks
-2152448 0No. Section 9.6 on RFC 2616 states that the URI is of the resource to be put, and the web server must not use it towards any other resource. So, while technically you may be able to construct a server process/script that would, you should not depend on any server allowing that.
-39168456 1 Raspberry PI GPIO mutli-threading KegeratorI wanted to consult with minds that were more familiar with Python.
The back story is I have a Kegerator with multiple taps (always a difficult decision when you want a drink). I have several flow sensors wired into it, and I am using the RPI for logging the data to my server.
At the moment the code I am using works if only 1 flow sensor is being used. However if multiple beers (flow sensor ticks) it combines the results.
Now I believe I need multiple classes defined for each kegerator, and create functions for each keg, but I wanted to confirm that with you guys.
http://pythonfiddle.com/flowmeter-app
http://pythonfiddle.com/flowmeter-class
Any help would be appreciated. If you are in the Boston area, there could be a beer in it for you.
-29770274 0Using regular expressions
SELECT * from table where id REGEXP '^(1+|2+|3+|4+|5+|6+|7+|8+|9+)$';
-37580722 0 Bash relative path from current directory I'm interested in finding the the relative path between two directories. The script is run in a directory which is a child (or descendant) of some specified folder. I want to get and output the relative path from that parent directory to the current directory. If the specified directory is not an ancestor of the current directory,\ I will output some sort of error.
Thanks
-9868323 0 Is there a convention to name collection in MongoDb?I would like to know if there is a convention for db collections such as
PageVisit
or page_visit
.
Are there any advantages/disadvantages for these notations ?
-16354457 0You can't detect the hash parameter of the URL in PHP, you would need to use JavaScript.
You could make a jquery call to php which passes the hash data (window.location.hash
) to a PHP script as a URL parameter and return TRUE/FALSE though.
Simply add a "&mt=12" to existing iTunes Store Links. This redirects queries to the Mac AppStore App instead of itunes.
Example for a search query in the MAS:
https://search.itunes.apple.com/WebObjects/MZSearch.woa/wa/search?q=equinux&mt=12
-37330319 0 properties hibernate.cfg.xml how i can load properties from hibernate.cfg.xml
as String to my java program?
I want to create IDataBaseTester
with this properties or tell me another way for create IDataBaseTester
from hibernate.cfg.xml
HibernateUtil
for create session
public class HibernateUtil { private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() { try { // Create the SessionFactory from hibernate.cfg.xml return new AnnotationConfiguration().configure().buildSessionFactory(); } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } public static void shutdown() { // Close caches and connection pools getSessionFactory().close(); } }
-3105308 0 A while back someone posted an mpl::string to the boost groups. I think it may actually have gotten into the library. If that is the case you could implement something like this by providing your template string as a template parameter (an mpl::string) and then using some pretty profound meta-programming skills to parse the formatting bits in it. Then you'd use this information to chose an implementation that has the appropriate argument count and types.
No, I'm not going to do it for you :P It would be quite difficult. However, I do believe it would be possible.
-37631953 0 Php print format or print php value to html scopehello i am new in php and im trying to print some values from my sql table to an article in html i use article because this is the structure i need . as you will see bellow i basically want to take the path and the username from my sql table and print them to my article any suggestions?
<html > <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Corporate 1</title> <link href="css/bootstrap.min.css" rel="stylesheet"> <link href="css/custom.css" rel="stylesheet"> </head> <body> <!-- Navigation --> <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation"> <div class="container"> <!-- Logo and responsive toggle --> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#"> <span class="glyphicon glyphicon-fire"></span> Logo </a> </div> <!-- Navbar links --> <div class="collapse navbar-collapse" id="navbar"> <ul class="nav navbar-nav"> <li class="active"> <a href="#">Home</a> </li> <li> <a href="#">About</a> </li> <li> <a href="#">Products</a> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Services <span class="caret"></span></a> <ul class="dropdown-menu" aria-labelledby="about-us"> <li><a href="#">Engage</a></li> <li><a href="#">Pontificate</a></li> <li><a href="#">Synergize</a></li> </ul> </li> </ul> <!-- Search --> <form class="navbar-form navbar-right" role="search"> <div class="form-group"> <input type="text" class="form-control"> </div> <button type="submit" class="btn btn-default">Search</button> </form> </div> <!-- /.navbar-collapse --> </div> <!-- /.container --> </nav> <div class="jumbotron feature"> <div class="container"> <h1><span class="glyphicon glyphicon-equalizer"></span><font color="#F0FFFF" style="Impact">Welcome to Aegean Community</font></h1> <p><font color="#E9967A">Community for hope</font></p> <p><a class="btn btn-default" href="LogIn.php">Engage Now</a></p> </div> </div> <!-- Content --> <div class="container"> <!-- Heading --> <div class="row"> <div class="col-lg-12"> <h1 class="page-header">Superior Collaboration <small>Visualize Quality</small> </h1> <p>Proactively envisioned multimedia based expertise and cross-media growth strategies. Seamlessly visualize quality intellectual capital without superior collaboration and idea-sharing. Holistically pontificate installed base portals after maintainable products.</p> </div> </div> <!-- /.row --> <!-- Feature Row --> <div class="row"> <!-- Feature Row --> <?php $servername = "localhost"; $username = "root"; $password = ""; $dbname = "some"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "SELECT * FROM information order by Ranking desc LIMIT 3 "; $result = $conn->query($sql); if ($result->num_rows > 0) { // output data of each row while ($row = $result->fetch_assoc()) { ?> <article class="col-md-4 article-intro"> <a href="#"> <img class="img-responsive img-rounded" src=" <?php echo $row['imgagePath'] ?>" alt=""> </a> <h3> <a href="#"> <?php echo $row['username'] ?></a> </h3> </article> <?php } ?> </div> </div> </body> </html>
-39277761 0 ChartKick.js: Error Loading Chart: t.canvas is undefined I'm using chartkick.js to integrate a multi line graph into my site (it's a rails app, but I'm using the chartkick.js file rather than the chartkick gem, if that makes any difference). On the page load, I populate the "data" array with the default values of input fields so that this:
data = [ {"name": "With interest", "data": {} }, {"name": "No Interest", "data": {} }];
Becomes something like this:
data = [ {"name": "With interest", "data": {1: "100", 2: "200", 3: "400"} }, {"name": "No Interest", "data": {1: "100", 2: "200", 3: "400"} }];
And thus, renders the the chart with all the values on the page.
I also have a click listener block which listens for "calculate" on a click event that takes in changed values for all of those input fields. At the end of the click listener block
At the very end of my document I declare chartkick like so:
new Chartkick.LineChart("savings-chart", data);
-30504174 0 Now, I access with the client and it shows the old data, I mean the database without the new row. Even if I 'update' a field in the admin, I won't see that 'update' with the client app.
The only thing that could cause this is if you don't COMMIT.
You must commit after DML changes to make sure the changes are permanent.
INSERT INTO sae_scenario_type ( id, name, description, locked ) VALUES ( SEQ_SAE_SCENARIO_TYPE.nextVAL, 'Direct_SQL_Insertion_1', 'Direct SQL Insertion from RfoAdmin 1', 'N' ); COMMIT; --> you are missing this
From documentation,
-19065266 0COMMIT
Purpose
Use the COMMIT statement to end your current transaction and make permanent all changes performed in the transaction. A transaction is a sequence of SQL statements that Oracle Database treats as a single unit. This statement also erases all savepoints in the transaction and releases transaction locks.
You can use Microsoft.Office.Interop.Excel
assembly to process excel files.
Add reference
. Add the Microsoft.Office.Interop.Excel assembly. using Microsoft.Office.Interop.Excel;
to make use of assembly.Here is the sample code:
using Microsoft.Office.Interop.Excel; //create the Application object we can use in the member functions. Microsoft.Office.Interop.Excel.Application _excelApp = new Microsoft.Office.Interop.Excel.Application(); _excelApp.Visible = true; string fileName = "C:\\sampleExcelFile.xlsx"; //open the workbook Workbook workbook = _excelApp.Workbooks.Open(fileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); //select the first sheet Worksheet worksheet = (Worksheet)workbook.Worksheets[1]; //find the used range in worksheet Range excelRange = worksheet.UsedRange; //get an object array of all of the cells in the worksheet (their values) object[,] valueArray = (object[,])excelRange.get_Value( XlRangeValueDataType.xlRangeValueDefault); //access the cells for (int row = 1; row <= worksheet.UsedRange.Rows.Count; ++row) { for (int col = 1; col <= worksheet.UsedRange.Columns.Count; ++col) { //access each cell Debug.Print(valueArray[row, col].ToString()); } } //clean up stuffs workbook.Close(false, Type.Missing, Type.Missing); Marshal.ReleaseComObject(workbook); _excelApp.Quit(); Marshal.FinalReleaseComObject(_excelApp);
-11774763 0 You have to use .filter
[docs]:
$('img').filter(function() { return this.src === $(this).attr('rel'); });
Note that rel
is not a valid attribute for img
elements. Therefore you might want to use data-*
attributes to store the additional information.
Additional note: this.src
will return the absolute URL, even if the src
attribute contains a relative URL. If you want to get the actual value of the attribute, you have to use $(this).attr('src')
.
You didn't set the tag of alertView. so if (alertView.tag == 1)
will be false
You can set alertViewStyle = PlainTextInput
, the it will have a Textfield
About alertViewStyle, check the document you will get:
enum UIAlertViewStyle : Int { case Default case SecureTextInput case PlainTextInput case LoginAndPasswordInput }
So change as below, your code should work:
@IBAction func Alert(sender: UIButton) { var alertView:UIAlertView = UIAlertView() alertView.title = "Alert!" alertView.message = "Greg is Cool" alertView.delegate = self alertView.addButtonWithTitle("OK") alertView.addButtonWithTitle("Okay") alertView.tag = 1 alertView.alertViewStyle = .PlainTextInput alertView.show() } func alert(alertView: UIAlertView!, clickedButtonAtIndex buttonIndex: Int) { switch buttonIndex { default: if (alertView.tag == 1) { NameLabel.text = "I get it!" } } }
-11332818 0 Specify a batch-size
on the Category.ChildCategories
mapping. That will cause NHibernate to fetch children in batches of the specified size, not one at a time (which will alleviate the N+1 problem).
If you are using .hbm
files, you can specify the batch-size
like this:
<bag name="ChildCategories" batch-size="30">
or using fluent mapping
HasMany(x => x.ChildCategories).KeyColumn("ParentId").BatchSize(30);
See the NHibernate documentation for more info.
EDIT
Ok, I believe I understand your requirements. With the following configuration
HasManyToMany<Item>(x => x.ChildCategories) .Table("CategoryLink") .ParentKeyColumn("ParentId") .ChildKeyColumn("CategoryID") .BatchSize(100) .Not.LazyLoad() .Fetch.Join();
you should be able to get the entire hierarchy in one call using the following line.
var result = session.CreateCriteria(typeof(Category)).List();
For some reason, retrieving a single category like this
var categoryId = 1; var result = session.Get<Category>(categoryId);
results in one call per level in the hierarchy. I believe this should still significantly reduce the number of calls to the database, but I was not able to get the example above to work with a single call to the database.
-10803323 0 Nivo slider: Click first slide to startNivo Slider for jQuery: I'm sure I'm missing something, but is there a way to have the slider start and loop by clicking on the first image? I have a series of 8 images that I'm replacing an SWF with, but the first slide says "Click to start". I know I can turn on the manual option, but that's not what I need. I just need the slider to start it's loop when the first image is clicked.
-32195933 0You may consider changing your approach, especially if you are doing a lot of GUI updates from your background threads. Reasons:
What I prefer is to do polling the background thread data instead. Set up GUI timer for say 300ms, then check if there is any data ready to be updated, then do quick update with proper locking.
Here is code example:
private string text = ""; private object lockObject = new object(); private void MyThread() { while (true) { lock (lockObject) { // That can be any code that calculates text variable, // I'm using DateTime for demonstration: text = DateTime.Now.ToString(); } } } private void timer_Tick(object sender, EventArgs e) { lock(lockObject) { label.Text = text; } }
Note, that while the text variable is updated very frequently the GUI still stays responsive. If, instead, you update GUI on each "text" change, your system will freeze.
-4051603 0 How should I prepare my 32-bit Delphi programs for an eventual 64-bit compiler?Possible Duplicate:
How to also prepare for 64-bits when migrating to Delphi 2010 and Unicode
Since I believe that 64bit Delphi compiler will appear soon, I am curious if anybody knows what kind of programs that are now 32bit will compile and work without any changes when using 64bit compiler.
And if there is a general rule what kind of changes should we systematically make in our old programs to be compiled as 64bit?
It is good to be prepared when the 64bit compiler will suddenly be here...
Any suggestion will be much appreciated.
-39122911 0you can also check status of response you are getting after hitting the API , like, means there is some problem in API
if(status!=200){
// do something
}
-3785336 0 PHP 5.2 and 5.3 togetherI have XAMPP with PHP 5.2, but my new projects need PHP 5.3 How to have PHP 5.2 and 5.3 together?
I have winXP.
-20036644 1 Python 3: check if the entire list is inside another listLet's say I have 2 lists:
a = [6,7,8,9,10]
b = [1,3,4,6,7,8,9,10]
I have a function that is used to find out if list a can be found in list b. If it is found, then it returns True. In my case it should return True because list a can be found at the end of list b. List a never changes and always contains the same numbers, whereas list b accepts numbers from the user and then uses sorted()
method to sort numbers in ascending order. I should also add that the order does matter.
I have searched around and could find a subset method, which looks like this: set(a).issubset(set(b)))
as well as using in
method. Both of them did not work for me.
UPDATE: Using set(a).issubset(set(b)))
for some reason always returns True. For example, if a = [1,1]
and b = [0,1,2,3,4,5]
then using subset method returns True, even though 1,1 cannot be found in b. I'm not looking if 1 is inside the list, I'm looking if 1,1 is inside the list.
Using in
method when
a = [6,7,8,9,10]
b = [1,3,4,6,7,8,9,10]
returns False.
You have an open transaction. That means SQL Server needs to preserve the state of the table, and any changes you are in the process of making are "dirty" and uncommitted.
If you SELECT
from a table that is currently being altered with an open (explicit) transaction, the SELECT
will wait until the table is in a stable state and the transaction has been either committed or rolled back.
To get around this, you can alter the transaction isolation level on the SELECT
query.
No, because the only reference you can register in your GitHub repo would be a submodule one.
(as in "Using someone else's repo as a Git Submodule on GitHub")
And a submodule is all about referencing a fixed commit, not "the latest".
You could work with subtree merging, but:
I want to convert a video file of mp4
format to audio file of mp3
format. It is simple through command line but i cannot find how can i convert it through jni
. Not sure which library and which function to call. Any help regarding this issue would be much appreciated.
If using the Gradle Wrapper you can set DEFAULT_JVM_OPTS
in gradlew
like this:
DEFAULT_JVM_OPTS="-Xmx512m"
Set it in a similar fashion in gradlew.bat
if you're on Windows:
set DEFAULT_JVM_OPTS=-Xmx512m
The Gradle Wrapper task can also be modified to include this automatically. This is how the Gradle developers have solved it:
wrapper { gradleVersion = '1.8' def jvmOpts = "-Xmx512m" inputs.property("jvmOpts", jvmOpts) doLast { def optsEnvVar = "DEFAULT_JVM_OPTS" scriptFile.write scriptFile.text.replace("$optsEnvVar=\"\"", "$optsEnvVar=\"$jvmOpts\"") batchScript.write batchScript.text.replace("set $optsEnvVar=", "set $optsEnvVar=$jvmOpts") } }
-9164039 0 FYI for anyone else that stumbles on this:
We ended up taking a different direction. It seems that iPad/Safari get to choose what happens to your PDF. We ended up taking the route of minimizing links in PDFs instead. The closest we got to an actual solution was hacks that some PDF readers use to change the protocol: eg ghttp:// for url that opens in GoodReader. Did not find this to be an acceptable approach.
-7044298 0Anyways I am not sure of the OVImap API but I am guessing it will pass its own event object to you to the handler method. see if that gives you the right values.
your listener function will be something like:
myClickableThing.addListener('click', function(event){this._clickFunction(event)});
Hope this helps.
On a side note wEll we ran into a similar issue on google maps and one particular browser where in the evt variable was not scoped correctly or something of that sort.
I am not sure if that is your problem.
-20802422 0 Parallel Issue: Cross-thread operation not valid: Control accessed from a thread other than the thread it was created onI have this simple code:
Parallel.Invoke( () => picturebox_1.Refresh(), () => picturebox_2.Refresh());
and I'm getting this:
Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on.
How can I resolve this issue? I just want to run the refresh in parallel, the refresh method runs the Paint Event which has code to render an image...
Thanks!
-30818251 0 using -sort in linuxI want to sort the input of the user with sort
in a case (and function). But I never used this before. Do I have to use an array or something?
For example the user does:
bash test.sh 50 20 35 50
Normally in my script this would happen:
ping c -1 "192.168.0.$i"
That results in
192.168.0.50 192.168.0.20 192.168.0.35 192.168.0.50
Now I want that the last numbers are sorted and also pinged from smallest to the biggest number like this: 20 35 50 and also that if you have 2 times the same number, the script only pings that number one time.
SortNumbers(){ } ... case -sort ) SortNumbers;; esac
-13417057 0 $('select').change(function(){ var sum = 0; $('select :selected').each(function() { sum += Number($(this).val()); }); $("#sum").html(sum); });
-24749150 0 iOs 8, start playing sound when in the background, alarm clock app I know there are many questions on SOF, but this is the "newest" one. The thing is, I'm trying to create and alarm app, and I know for a fact that there are alarm apps out there that works perfectly ( somehow ), even if the app is not running and is in the background.
My question is: how do you start playing sound after your app is already in the background ??
UILocalNotification is great, but you'll only get application:(_:didReceiveLocalNotification:)
after the user has already clicked on your notification, so playing sound using AVAudioPlayer didn't work, i want to play sound regardless weather the user clicks on it or doesn't. Of course with Required background modes: App plays audio or streams audio/video using AirPlay
in info.plist
already set. Once the music starts playing, it keeps playing even if i go to the background.
I don't want to use UILocalNotificaation sound coz it's limited to 30 secs and only the able to play the sounds that are bundled with the application.
Any insights ? thoughts ??
Sample code:
var notif = UILocalNotification() notif.fireDate = self.datePicker.date notif.alertBody = "test" UIApplication.sharedApplication().scheduleLocalNotification(notif)
the above code gets called when the user selects and alarm and clicks save.
and here's what's happening in AppDelegate:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool { NSLog("launched") application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Sound | UIUserNotificationType.Alert | UIUserNotificationType.Badge, categories: nil )) AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil) AVAudioSession.sharedInstance().setActive(true, error: nil) self.sound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("sound", ofType: "caf")) self.audioPlayer = AVAudioPlayer(contentsOfURL: sound, error: nil) return true } func application(application: UIApplication!, didReceiveLocalNotification notification: UILocalNotification!){ audioPlayer.play() NSLog("received local notif") }
You need to hold a strong reference to the AVAudioPlayer
btw, so it won't get released, and the audioplayer.play()
won't do anything...
try: rotate = [0, 0, 0]
Which is a rotation abound 3 axis for geographic projections
A trie (or prefix tree) sounds right up your alley. It can do the search on a prefix string of length m in O(m) I believe.
-4929939 0The best place to create your form elements is to override the init()
method, eg
class App_forms_ItemEditor extends Zend_Form { public function init() { $email = $this->createElement('text', 'email'); $email->setLabel('Your email address:'); $email->setRequired(TRUE); $email->addValidator(new Zend_Validate_EmailAddress()); $email->addFilters(array( new Zend_Filter_StringTrim(), new Zend_Filter_StringToLower() )); $email->setAttrib('size', 40); $this->addElement($email); } }
If you hijack Zend_Form::__construct()
, you should at least accept the same arguments and pass them on using parent::__construct()
Also, I'm a little unsure about the lowercase "f" in your class name's "form" part. From memory, the module autoloader translates a "Form" name part to a "forms" directory in your module.
I do note however that you're not using the module autoloader (or at least, you haven't shown that you are)
Regarding module autoloaders...
The bootstrap process registers a module autoloader using the configured appnamespace
value (usually "Application") with base path "application".
A module autoloader automatically registers some class name / path mappings for classes starting with the configured namespace (eg "Application_"). This includes forms.
Basically, it means you can create forms under application/forms/MyForm.php
with classname Application_Form_MyForm
and the autoloader will find it.
Open up `Zend_Application_Module_Autoloader" to see the full list.
-35049740 0Recursion means that each function call stays on the stack, hence you eventually will run out of memory leading to the RecursionError
. In other There are ways around this using "tail-call recursion", almost like you've done - except Python will never support this.
The best way to run this is to modify your code to have an infinite loop:
def get_status(last_media_type, last_state): pass # your method here # except for the recursive call return state, media_type last_state = None last_media_type = 'sensible_default' while True: state, media_type = get_status(last_media_type, last_state) pass # do what you need to compare them here if last_state != state and last_media_type != media_type: print "they aren't equal!" last_state, last_media_type = state, media_type
The loop itself (while True:
) will consume practically no memory, and now instead of storing every single past state, you just have the last one.
Additionally, any information in the method call is garbage collected as it loses scope when your method returns - this is a direct improvement over your code, as in the recursive call nothing ever loses scope so nothing cal ever be collected.
-18070363 0 Find maximum value between specified date rangeI have a range of daily dates in column G and a range of stock prices in column H. I would like to find a rolling 52 week high, i.e. the highest stock price in column H between the current date and the same date 1 year prior.
I am using the following formula:
MAX(IF($G$5:$G$10757>=EDATE(G5,-12),IF($G$5:$G$10757<=G5,$H$5:$H$10757)))
So, the IF conditions specify the date range as being in between G5 and G5 less 12 months, and is looking for the corresponding value in column H.
After I type the formula, I press CTRL+SHIFT+ENTER
. It seems to work for the first calculation, but I cannot fill the formula down for the entire range of dates. I just get the same value repeating over and over again.
Strongly opinionated answer ahead:
I have tried a few different approaches to binding in WinForms (over many years), and it ends up being really easy to get 80% of what you want, and it requires significant hacking to make the other 20% work. Also, usually 3rd party controls come with their own quirks.
Your list there illustrates the pitfalls fairly well. Unfortunately, WinForms just doesn't have the binding power of, say, WPF.
My current approach to data binding is to do not use any of the binding objects and do everything manually. The approach I usually take is just make the form a passive view and pass the Form a ViewModel object encapsulating all the data that should be displayed on the form and set all the properties on the form from that object. Which means you lose all the 'magic' of binding, but it's not a black box anymore and it's easier to debug.
Good question, I look forward to other answers and being proved wrong.
-21879741 0I think you're working with windows form...
And I think the problem is that you want the listbox to be populated with the first item of the combobox when you load for the first time the winform
So, in the form_load event you should select the index in the combobox
private void EmployeeAttendence_Load(object sender, EventArgs e) { try { table = dbOperation.select("employs.emp_id, employs.emp_name, employs.emp_fname, designation.name from employs inner join designation on designation.id = employs.designation"); listView1.Items.Clear(); foreach (DataRow row in table.Rows) { listView1.Items.Add(row[0].ToString()); listView1.Items[listView1.Items.Count - 1].SubItems.Add(row[1].ToString()); listView1.Items[listView1.Items.Count - 1].SubItems.Add(row[2].ToString()); listView1.Items[listView1.Items.Count - 1].SubItems.Add(row[3].ToString()); listView1.Items[listView1.Items.Count - 1].SubItems.Add("P"); } table = dbOperation.select("* from designation"); comboBox1.Items.Clear(); comboBox1.DataSource = table; comboBox1.DisplayMember = "name"; comboBox1.ValueMember = "id"; comboBox1.SelectedIndex = 0; //this should raise the event comboBox1_SelectedIndexChanged(object sender, EventArgs e) and the listbox will be populated } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
-40781618 0 A questions about angular2 route Here is the official example of angular-router. https://angular.io/docs/ts/latest/guide/router.html#!#browser-url-styles https://angular.io/resources/live-examples/router/ts/plnkr.html
If I have requirements like this:When user did not log in,He can not see the top bar(menu list in the second row of the picture should be hidden),only after he logged in,the top bar is visible,I thought a lot about this but can not find the solution.I dont know how to use canActive hook to control it,anyone has an idea please tell me,thank u.
import { Component } from '@angular/core'; @Component({ selector: 'my-app', template: ` <h1 class="title">Angular Router</h1> <nav> <a routerLink="/crisis-center" routerLinkActive="active">Crisis Center</a> <a routerLink="/heroes" routerLinkActive="active">Heroes</a> <a routerLink="/admin" routerLinkActive="active">Admin</a> <a routerLink="/login" routerLinkActive="active">Login</a> </nav> <router-outlet></router-outlet> ` }) export class AppComponent { }
Let me be more clear about my question.When user loading page of structure like this.Where should I get and record the login status to achieve my goal,from route or somewhere else?
-34670429 0 Can we create Multiple HttpSessionListeners in a web applicationI aplication is already having a HttpSessionListener
in which some logic is performed in session created events.
Is it possible to create one more HttpSessionListener
where I can have some other logic in the same application. ?
I've wired up the CompletionData no problem, inserting etc into the Avalon Edit control.
The challenge is the searching algorithm.
In the example below, I want new-obj to "match" New-Object* in the list and not do a partial find on New-DataObject.
Is there a flag I can set? Or do I need to override the search and implement my own?
Thank you
Doug
How to display the latest updated data in select option? when i use update query to update this field, this customer name field did updated in the database but not update on the page itself? any way to solve this?
<td width="20%"> Customer Name. </td> <td width="40%" > <select onchange="loadaddress()" style="width:400px" id="custname" name="custname" > <option disabled>----------------------FJ----------------------</option>'; <?php for($i=0; $i<=odbc_fetch_row($result); $i++){ $id = odbc_result($result, 1); $name = odbc_result($result, 2); echo '<option value="'.$id.' '.$name.'"><b>'. $id. " ". $name.'</b></option>'; } echo '<option disabled>----------------------FJL----------------------</option>'; for($i=0; $i<=odbc_fetch_row($result2); $i++){ $id = odbc_result($result2, 1); $name = odbc_result($result2, 2); echo '<option value="'.$id.' '.$name.'"><b>'. $id. " ". $name.'</b></option>'; } echo '<option disabled>----------------------FJW----------------------</option>'; for($i=0; $i<=odbc_fetch_row($result5); $i++){ $id = odbc_result($result5, 1); $name = odbc_result($result5, 2); echo '<option value="'.$id.' '.$name.'"><b>'. $id. " ". $name.'</b></option>'; } ?> </select> </td> </tr>
-15292788 0 make sure you load your jquery script first and the dataTables js script later...
for sorting
Using the aaSorting initialization parameter, you can get the table exactly how you want to present the information.
$('#example').dataTable( { "aaSorting": [[ 4, "desc" ]] });
you can go thorugh the documentation here
-27408607 0We have solved the issue by raising a PMR with IBM. They provided us with an update for Eclipse kepler containing the fix for the BB authentication and with 32 extra fixes.
-17836843 0Try this :
$string = "'Hello world' 'green apples' 'red grapes'"; preg_match_all("/'[\w\s]+'/",$string,$match); echo "<pre>"; print_r($match[0]);
Ref: http://www.php.net/manual/en/function.preg-match-all.php
Output :
Array ( [0] => 'Hello world' [1] => 'green apples' [2] => 'red grapes' )
-20821035 0 About the gap under the image, it's displayed inline :
img { display: block; /* this will fix bottom gap */ width: 100%; }
About your images size :
Just use images of the same size will fix your situation. Otherwise try forcing them with css
figure img {width:1280px;height:960px;margin-right:15%;margin-left:15%;}
About i can i do the transition and more ... well, not to sound arsh or nothing, but .. keep studying. You are quite asking too much in a single question.
-40640833 0Looks to me very much like a caching issue. Some of the JavaScript or CSS from before the update may still be stored in the user's browser cache.
To resolve this, clear Chrome's browser cache. You can access the relevant dialog via ctrl+shift+del.
-27743941 0Trigger is not going to execute for each Row
. Change your trigger like this.
CREATE TRIGGER trig_INVOICE ON INVOICE after INSERT, UPDATE AS BEGIN UPDATE a SET AMOUNT = QUANTUM * p.price FROM INVOICE a JOIN inserted b ON a.PRODUCTID = b.PRODUCTID JOIN PRODUCT p ON a.PRODUCTID = p.PRODUCTID END
-4998920 0 for iis7 and iis7.5, handlers are registered in system.webserver. the httphandlers and httpmodules in system.web are ignored and are used for IIS 6 and classic mode.
i hope this was helpful!
-19937854 0 Count Function in Access SQL QueryList the guests by name and the number of times each has reserved a room at one of our hotels. Arrange the list in order from most-frequent to least-frequent guest.
I'm keep getting aggregate function for Firstname and LastName
So Far i have this code
SELECT FirstName, LastName, Count(ResNum) AS TotalReservations FROM RESERVATION, GUEST Where GUEST.GuestNo = RESERVATION.GuestNo ORDER BY RESERVATION.GuestNo
And here is the link for the RelationShip Table
View Relationship Table <--- LINK
-11448125 0 Entity Framework - how to save entity without saving related objectsIn my Entity Framework, I have three related entities 'Client', 'ClientAddress' and 'LookupAddressType'. "LookupAddressType" is a master class specifying the type of available address type, like business address, residential address etc. ClientAddress depend on LookupAddresstype and Client. While saving a Client entity with relevant ClientAddress data, i'm getting following error.
"Violation of PRIMARY KEY constraint 'PK_LookupAddressType'. Cannot insert duplicate key in object 'dbo.LookupAddressType'. The statement has been terminated.
I do not need LookupAddressType to be inserted. Here I just need the relevant lookupAddressTypeId to be inserted in clientAddress entity.
The Saving code is like this:
Add(Client); _objectContext.SaveChanges();
how can i do this?
The Load Code is below:
private void LoadClientDetails(EFEntities.Client _Client) { EFEntities.LookupClientStatu clientStatus; var clientAddressList = new List<ClientAddress>(); if (_Client == null) { return; } //Assign data to client object _Client.ClientName = rtxtName.Text; _Client.Alias = rtxtAlias.Text; _Client.ClientCode =Int32.Parse(rtxtClientCode.Text); _Client.TaxPayerID = rtxtTaxPayerId.Text; if (rcboStatus.SelectedIndex != 0) { clientStatus = new EFEntities.LookupClientStatu { ClientStatusID = (Guid) (rcboStatus.SelectedValue), ClientStatusDescription = rcboStatus.Text }; _Client.LookupClientStatu = clientStatus; } //_Client.Modified = EnvironmentClass.ModifiedUserInstance.Id; _Client.EffectiveDate = rdtEffectiveDate.Value; if (rdtExpDate.Value != rdtExpDate.MinDate) { _Client.ExpirationDate = rdtExpDate.Value; } else { _Client.ExpirationDate = null; } _Client.StartDate = DateTime.Now; EFEntities.ClientAddress clientAddress = null; // Iesi.Collections.Generic.ISet<ClientAddress> clientAddress = new HashedSet<ClientAddress>(); foreach (var cAddress in _clientController.client.ClientAddresses) { clientAddress = cAddress; break; } if (clientAddress == null) { clientAddress = new EFEntities.ClientAddress(); } clientAddress.Address1 = rtxtClientAdd1.Text; clientAddress.Address2 = rtxtClientAdd2.Text; clientAddress.Address3 = rtxtClientAdd3.Text; // Address type details if (rcboClientAddType.SelectedIndex != -1) { clientAddress.LookupAddressType = new EFEntities.LookupAddressType { AddressTypeID = (Guid) (rcboClientAddType.SelectedValue), AddressTypeDescription = rcboClientAddType.Text }; //clientAddress.AddressType.Id = Convert.ToByte(rcboClientAddType.SelectedValue); } clientAddress.City = rtxtClientCity.Text; clientAddress.Client = _Client;
\
_Client.ClientAddresses.Add(clientAddress); }
-4102462 0 I've used: Firebird, MySql, SQLite, Oracle and even Postgres long long ago.
-4592453 0I think your id column is varchar it schould be int
but maybe did can help you
http://support.microsoft.com/kb/209632
to order string as numeric
-30009395 0 PCA computation on 2D vectors of type doubleI am trying to run PCA on a dataset which I have stored into a 2D vector from a file as follows:
std::vector<std::vector<double> > tmpVec; while(std::getline(file, numStream)) { std::istringstream buffer(numStream); std::vector<double> line((std::istream_iterator<double>(buffer)), std::istream_iterator<double>()); tmpVec.push_back(line); i++; }
Now I need to run PCA on this for which according to my understanding I need to convert this to type cv::Mat. This is being done as follows:
cv::Mat dst(row, col, CV_64F, &tmpVec);
And thrn i run PCA on it as:
cv::PCA pca(dst, cv::Mat(), CV_PCA_DATA_AS_ROW, 2);
When I try printing it out on screen after PCA computation i end up with garbage values. I just need to figure out how to run PCA on a 2D double vector. Any help with this or pointing me in the right direction would be great. Thanks in advance.
-22680993 0 processMessage runs twiceThere is a MessageListener listening to processMessage say from user A and when sendMsg is sent form another user to User A , I see processMessage getting invoked twice:
public void sendMsg(message){ Message msg = new Message(); mess.setBody(message); // userid is the userid to whom the message will be sent to and chmanage is an instance of Chat Manager Chat chat = chmanage.createChat(<userid>, new CListener()); chat.sendMessage(msg); } class CListener implements MessageListener{ @Override public void processMessage(Chat chat, Message message) { ... //this gets called twice } }
Any reasons for this? Should I use something else like create a PacketCollector or PacketListener?
-38751957 0The hint to a solution is here https://github.com/spring-projects/spring-hateoas/issues/155#issuecomment-36487869
The way the method-to-link functionality works is by creating a proxy for the return type of the method to be able to inspect the previous invocation. As String is a final class it cannot be proxied by definition.
Checked the method signature:
@RequestMapping(value = "/topology/{environmentId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public String environmentTopology(@PathVariable("environmentId") String environmentId, ...
Since it returns a String, you need to wrap it in a class that is proxy-able, like ResponseEntity
@RequestMapping(value = "/topology/{environmentId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public ResponseEntity<String> environmentTopology(@PathVariable("environmentId") String environmentId,
The ResponseEntity
wraps your String
response allowing the test mechanism to work.
Is it possible to add mysql user into a database as column?
Lets say we have a following table:
CREATE TABLE message( id INT AUTO_INCREMENT NOT NULL, title VARCHAR(255), message TEXT, last_edited TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (id) ) ENGINE=INNODB;
and we want to add 'editor' column which would get the current mysql user and insert it there and also updates it automatically similar to the behaviour of the TIMESTAMP datatype. Can this be done and if so what sort of datatype should I use (is there such a type as USER or should I use simple varchar) and what kind of syntax is involved?
-11380576 0 how to write the mongodb code in delphiThis is the original code I tried:
obj = { sentence: "this is a sentece", tags: [ "some", "indexing", "words"] }
and
findOne({tags: "words"}).name);
I used the TMongWire as the wrapper of MongoDB for Delphi and I wrote this:
//var // d:IBSONDocument; d:=BSON([ 'id',mongoObjectID, 'sentence', 'this is a sentece', 'tags','["some", "indexing", "words"]' ]); FMongoWire.Insert(theCollection,d);
it seem the codes above do the work
but when I query with the 'tags', it seems to not work for me
//var //q:TMongoWireQuery; //qb:IBSONDocument qb:=BSON(['tags', '"words"']); //*** q:=TMongoWireQuery.Create(FMongoWire); q.Query(mwx2Collection, qb); //***
How do I write the two lines with * asterisks?
-37493718 0You should print values of x
and y
in your hopper
function. Since chips2
contains indices in the matrix with value 2, then the index [9][9]
will be contained in chips2
implying x = 9
or y = 9
at some point.
Therefore matrix[x+1][y+1]
would mean matrix[10][10]
which does not exist. You should review your code.
you should do:
if x < 8: if matrix[x+1][y+1] != 0 and matrix[x+2][y-2] == 0: #up + right . . .
In that way, you don't perform a check on an index that is out of range
-26356540 0 Montserrat font isn't displayed on IE 10 and 11In this website http://themescreators.com/ela/ I am using some google fonts. All of them work well on Chrome, FF.. but on IE 10 and 11 on Windows 7, "Montserrat" font doesn't display. I have really not idea about what can be the issue, is IE incompatible with some google fonts?
If you visit the site on windows 7 you will see clearly the issue, all "Montserrat" h1, h2... aren't visible.
Thanks in advance!
-25100976 0 How to rerun controllers after global data is resolved?I resolve data on application load in a run block...
.run(function($rootScope, $q, teams, schools, news, games){ // go out and grab all the relevant data $rootScope.showSplash = true; $q.all([ $rootScope.school = schools.get({id:1}), $rootScope.teams = teams.query({id:1}), $rootScope.news = news.query({id:1}), $rootScope.games = games.query({id:1}) ]).then(function(){ setTimeout(function(){ $rootScope.showSplash = false; $rootScope.$digest(); }, 1000); }) })
I have a controller whose scope should clone the data via $rootScope...
.controller('NewsDetailCtrl', function ($scope, $routeParams) { $scope.newss = $scope.news.filter(function(news){ return news.id == $routeParams.id; }).shift(); });
If the user is on the new-detail.html page, no data is present because the $scope clones an empty array. Is it possible to rerun the controllers when that information is received?
-17399553 0 Filter xml in .Net with paramI am trying to filter an xml file in a .Net application I am developing. Some sample xml below, obviously not the proper xml, but near enough :-)
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <Row A1="1" A2="AMS"> <Name>Ashley</Name> <Team>Team B</Team> <Date>3/25/2012</Date> <Value>511681.15</Value> </Row> <Row A1="2" A2="AMS"> <Name>Kylie</Name> <Team>Team A</Team> <Date>9/28/2010</Date> <Value>408438.47</Value> </Row> <Row A1="3" A2="AMS"> <Name>Gianna</Name> <Team>Team B</Team> <Date>40004</Date> <Value>109709.22</Value> </Row> <Row A1="4" A2="AMS"> <Name>Chase</Name> <Team>Team F</Team> <Date>40152</Date> <Value>279018.79</Value> </Row>
The stylesheet has a param that is set by XsltArgumentList in the application. The param is passed into the stylesheet, but does not filter the xml. I have tried using the ms node-set and exsl node-set but only get the top level root returned. Stylesheet below:
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:exsl="http://exslt.org/common" extension-element-prefixes="exsl" xmlns:msxsl="urn:schemas-microsoft-com:xslt"> <xsl:output method="xml" indent="yes" encoding="UTF-8" /> <xsl:decimal-format name="NN" NaN="0" /> <xsl:param name="Filter" /> <xsl:template match="/"> <Root> <xsl:for-each select="exsl:node-set($Filter)"> <Row> <xsl:attribute name="A1"> <xsl:value-of select="@A1" /> </xsl:attribute> <xsl:attribute name="A2"> <xsl:value-of select="@A2" /> </xsl:attribute> <Team> <xsl:value-of select="Team"/> </Team> </Row> </xsl:for-each> </Root> </xsl:template>
The filter i am trying to pass could be using any of the combination of the xml elements. The filter is am currently attempting is below
<xsl:param name="Filter" select="//Row[Team='Team A']" />
But this is just returns
<?xml version="1.0" encoding="utf-8"?> <Root> <Row A1="" A2=""> <Team></Team> </Row> </Root>
Any help or pointers would be appreciated!
Thanks
-25420424 0This library should do the trick. https://github.com/Pkmmte/PkRSS
It automatically handles all your RSS loading and parsing so you don't need to worry about it.
-28180848 0This question has not answer.
You try to match searching of content with backslash on names of columns.
Your (a bit general) query
SELECT * FROM tableName WHERE columnName LIKE '%\\%'
will give you any result if content of any column will contain backslash. In this case your query is correct. But you cannot match name of any column.
I looked into some books I have and all they say the same: this will select all records written in column of chosen name that are containing backslash. But columns have to be chosen exactly (they cannot be selected by name with using of SQL query).
-6066385 0If the thread that runs SwingUtilities.invokeLater
is already the swing event thread and you run in this while loop, yup, your application will hang.
Get rid of the while loop.
-21932568 0I found one possible solution-
cut -d "[" -f2 | cut -d "]" -f1
so the exact solution is
# cat /sys/block/sdb/queue/scheduler | cut -d "[" -f2 | cut -d "]" -f1
-18398742 0 TYPO3 error: "Declaration of tx_ttnews_categorytree::getTree() should be compatible with t3lib_treeView::getTree" I copied a TYPO3 site from the server to localhost, TYPO3 version 4.5. I set db credentials in localconf and when I launch the site I got this error.
Runtime Notice: Declaration of tx_ttnews_categorytree::getTree() should be compatible with t3lib_treeView::getTree($uid, $depth = 999, $depthData = '', $blankLineCode = '', $subCSSclass = '')
I found same problem with Google but no solution, or in a language I was not able to understand.
I tried to delete every cache I was able to find, both from files and from db.
EDIT
So I'm working on a website and I need a drawer on the left side and on the right side. First, I've made the left one and it seems to be working great so I've decided to copy it and change the names and the CSS in order to make the same one appear on the right side, but it isn't showing at all.. I might've made a small mistake, I might've made a big one, but I can not find it. Hopefully some of ya'll could help me out with this. It's practically an X in the left corner of the window which slides in the drawer with info and the same thing should be for the right side as well.
$(document).ready(function() { $(".trigger-left").click(function() { $(".panel-slide-left").toggle("fast"); $(this).toggleClass("active"); return false; }); }); $(document).ready(function() { $(".trigger-right").click(function() { $(".panel-slide-right").toggle("fast"); $(this).toggleClass("active"); return false; }); });
.panel-slide-right { position: absolute; right: 0; display: none; background-color: #edf2f4; width: 330px; height: 100%; padding-left: 50px; padding-top: 50px; } .panel-slide-left p { margin: 0 0 15px; padding: 0; color: #ccc; } .panel-slide-right p { margin: 0 0 15px; padding: 0; color: #ccc; } .panel-slide-left a:hover, .panel-slide-left a:visited:hover { margin: 0; padding: 0; color: #fff; text-decoration: none; border-bottom: 1px solid #fff; } .panel-slide-left a:hover, .panel-slide-left a:visited:hover { margin: 0; padding: 0; color: #fff; text-decoration: none; border-bottom: 1px solid #fff; } a.trigger-left { position: absolute; text-decoration: none; top: 50px; left: 0; font-size: 16px; letter-spacing: -1px; font-family: verdana, helvetica, arial, sans-serif; color: #fff; padding-left: 20px; font-weight: 700; display: block; } a.trigger-right { position: absolute; top: 50px; right: 0; top: 50px; left: 0; font-size: 16px; letter-spacing: -1px; font-family: verdana, helvetica, arial, sans-serif; color: #fff; padding-left: 20px; font-weight: 700; display: block; } a.trigger-left:hover { position: absolute; text-decoration: none; top: 50px; left: 0; font-size: 16px; letter-spacing: -1px; font-family: verdana, helvetica, arial, sans-serif; color: #fff; padding-left: 20px; font-weight: 700; display: block; height: 50px; } a.trigger-right:hover { position: absolute; text-decoration: none; top: 50px; right: 0; font-size: 16px; letter-spacing: -1px; font-family: verdana, helvetica, arial, sans-serif; color: #fff; padding-left: 20px; font-weight: 700; display: block; height: 50px; } a.active.trigger-left { color: #fff; } a.active.trigger-right { color: #fff; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="panel-slide-left"> <div style="clear:both;"></div> <div class="columns"> <div class="colcenter"> <div class="checkbox"> <label> <input type="checkbox" value=""> <h5>Broadcast Language English</h5> </label> </div> <div class="checkbox"> <label> <input type="checkbox" value=""> <h5>Stream Language English</h5> </label> </div> </div> </div> <div style="clear:both;"></div> </div> <a class="trigger-left" href="#">X</a> <div class="panel-slide-right"> <div style="clear:both;"></div> <div class="columns"> <div class="colcenter"> <div class="checkbox"> <label> <input type="checkbox" value=""> <h5>Broadcast Language English</h5> </label> </div> <div class="checkbox"> <label> <input type="checkbox" value=""> <h5>Stream Language English</h5> </label> </div> </div> </div> <div style="clear:both;"> </div> <a class="trigger-right" href="#">X</a>
figured it out. I need to learn more about git.
running git add .
before my git commit fixed it.
This is a big subject indeed. When moving into microservices, you need to remember that a lot of your headaches are going to be operational (devops oriented) rather than "code".
Also, there's so much out there that at some point you will just need to make a decision, regardless if it's optimal. Things will change along the way in any case. Make the best decision you can at the moment, go with it, and tweak later.
Regarding your questions, REST is a common practice. There are also other options (WCF, Avro, whatever). Give yourself a timeline for a decision. If you know REST and feel comfortable with REST, take the decision. Try to see if you can build it so you can change / add other protocols later, but don't make it delay you too much.
Like Udi said, some architecture considerations are if you need to call this service sync or async (via a message bus). Also, yes, think about service discovery. There are several options (zookeeper, consul).
For some background and overview, try going through some of the resources:
http://blog.arkency.com/2014/07/microservices-72-resources/
This also gives a quick overview of microservices patterns:
http://microservices.io/patterns/microservices.html
But again, there's a lot of information and ways of doing things, don't get swamped.
-33849885 1 Selenium Python - Getting the current URL of web browser?I have this so far:
from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Chrome('C:\Users\Fan\Desktop\chromedriver.exe') url = driver.current_url print url
It keeps saying that line 4 "driver" is an invalid syntax. How would I fix this?
Also is there a way I can get all the current tabs open, and not just a single one?
EDIT: the above code works now; But I have another problem!
The code now opens a new tab, and for some reason the URL bar has "data;" in it, and it outputs data; as the print.
But I want it to take the existing URL from existing web browser already opened, how do I solve this?
-34438622 0This is an open-ended question and there is no clear answer with different tradeoffs.. I'm not a PHP programmer, but something like the following should work.
# THESE PARAMETERS CONTROL THE RANKING ALGORITHM. $rescale = 0; $spread = 1; function rescore ($n) { return log($n) + $rescale; } function rank ($scores) { return 100 / (1 + exp(- $spread * array_sum(array_map("rescore", $scores)))); }
You should choose $rescale
so that the average score rescores to something close to 0. And play around with $spread
until you're happy with how much your scores spread out.
The idea is that log
turns a wide range of scores into numbers in a comparable range that can be positive or negative. Add a bunch of rescored scores together and you get an arbitrary real number. Then throw that into a logistic function (see https://en.wikipedia.org/wiki/Logistic_function for details) to turn that into a number in your desired range.
I have questions with below code snippet, not sure if I correctly understand the codes.
template <typename R, typename... Args> class RunnableAdapter<R(*)(Args...)> { public: typedef R (RunType)(Args...); explicit RunnableAdapter(R(*function)(Args...)) : function_(function) { } R Run(Arg... args) { return function_(args...); } private: R (*function_)(Args...); };
<R(*)(Args...)>
is a "type of function pointer"and blink space between R and (*) is not necessarily required?
and what could instanciation of RunnableAdapter be? I assume it is like below.
void myFunction(int i){ // }; RunnableAdfapter<(void)(*)(int)> ra(MyFunction); ra.Run(1); //which calls MyFunction(1)
I'm doing a program in Python that multiplies two matrices of the dimension that the user enters. The problem I have is that the user must enter the values for each line in the input and my program can only obtain a value for each input. I've tried using .split () but when it does the multiplication sends me this error:
TypeError : can not multiply sequence by non -int of type 'list'.
My code is:
matriza=[] matrizb=[] matrizc=[] orden=int(input("Ingresa el orden de las matrices: ")) #Para obtener la primer matriz for i in range(0,orden): matriza.append([0]*orden) for j in range(0,orden): matrizb.append([0]*orden) for k in range(0,orden): matrizc.append([0]*orden) for i in range(0,orden): for j in range(0,orden): matriza[i][j]=int(input("entrada renglon para la primer matriz")) print "La primer matriz que introdujiste fue:" "\n" ,matriza, "\n" #Para obtener la segunda matriz for i in range(0,orden): for j in range(0,orden): matrizb[i][j]=int(input("entrada renglon para la segunda matriz")) print "La segunda matriz que introdujiste fue:" "\n" ,matrizb, "\n" #Para la multiplicación de las dos matrices for i in range(0,orden): for j in range(0,orden): for k in range(0,orden): matrizc[i][j]+=matriza[i][k]*matrizb[k][j] print "La matriz que resulta de multiplicar las matrices que introdujiste es:" "\n" ,matrizc
-39226234 0 It has not been mentioned yet, so I will point out that OpenCV has functions for scaling and rotating images, as well as an enormous number of other utilities. It may contain many features that are not relevant to the question, but it is very easy to setup and use for a library of its kind.
You can try to implement transformations like this manually, but the simple approach to scaling and rotating will generally result in a significant loss of detail.
Using OpenCV, scaling can be done like so:
float scaleFactor = 0.68f; cv::Mat original = cv::imread(path); cv::Mat scaled; cv::resize(original, scaled, cv::Size(0, 0), scaleFactor, scaleFactor, cv::INTER_LANCZOS4); cv::imwrite("new_image.jpg", scaled);
This scales the image down by a factor of 0.68 using Lanczos interpolation.
I am not as familiar with rotations, but here's part of an example from one of the tutorials on the OpenCV website that I have edited down to the relevant parts. (The original had skew and translation in it also...)
/// Compute a rotation matrix with respect to the center of the image Point center = Point(original.size().width / 2, original.size().height / 2); double angle = -50.0; double scale = 0.6; /// Get the rotation matrix with the specifications above Mat rot_mat( 2, 3, CV_32FC1 ); rot_mat = getRotationMatrix2D(center, angle, scale); /// Rotate the image Mat rotated_image; warpAffine(src, rotated_image, rot_mat, src.size());
They have some very nice documentation too.
-40678906 0There is no special reason in this simplest case. But if you go further in development - it will become absolutely clear: you'll need to abstract from implementation and separate out an interface, e.g. just to mock Student in a unit test. So, in long terms you'll rather need interfaces and properties and it is just a habit to write it in a mockable and testable manner from the very beginning
public interface IStudent { int StudentId { get; set; } string StudentName { get; set; } string Address { get; set; } } public class Student : IStudent { public int StudentId { get; set; } public string StudentName { get; set; } public string Address { get; set; } }
-23656502 0 text = (text.replaceAll( "(?i)(<a[^>]*?\\stestexpression\\s*)=\"", "" )); return text.replaceAll("}\"\\shref.+</a>", "}");
But still looking for 1 line solution .
-8877735 0No, you can't skip phases. The mvn phase-x
command always means "run all phases until phase-x, inclusive". Some plugins, however can detect if there have been changes since their last execution and decide (on their own) not to run — the subsequent build is faster.
I'm not sure what exactly you want to achieve — perhaps you could take a look at Maven assembly plugin?
-25754243 0You could define a lambda function which calls your static function. Or simply store function name as a string in that variable. You would also have to implement a handler code for the class that calls a function from variable.
Resources: http://php.net/manual/en/function.forward-static-call-array.php
http://ee1.php.net/manual/en/function.func-get-args.php
Example for anonymous function:
<?php $function = new function(){ return forward_static_call_array(['class', 'function'], func_get_args()); }; ?>
Testes this, works flawlessly.
-33727246 0Select the item you want to replace (double-click it, or CTRL-F to find it)...
Then do a (Ctrl - Apple - G) on Mac (aka. "Quick Find All"), to HIGHLIGHT all occurrences of the string at once.
Now just TYPE your replacement text directly... All selection occurrences will be replaced as you type (as if your cursor was in multiple places at once!)
Very handy...
-20672083 0I think it has something to do with javascript happening AFTER php happens.
Why not switch it with
include('http://www.website.com/file/index.php');
if your hiding that div you could just use javascript to show / hide the div based on what ever happens. Dont try to lead the php file when its hovered or clicked or w/e. Load it first and just display it with js.
-12163369 0Try putting the js in a separate file, and then:
var MeteoPanel = require("panel").Panel({ width:740, height:350, contentURL: data.url("test.html"), contentScriptFile: data.url("yourJSFile.js"), //Add this line allow:true });
Seems like contentScriptFile
accepts an array too, so you could change its value to [data.url("file1.js"),data.url("file2.js")]
if you need for instance to add 2 source files.
I have just found out the error in my script. The 1st script works fine after correcting the error. I should have used th for the header row as I did in the html and not td. Also I have added the missing .hide() The 2nd script though hides the columns but will still show a space for any column it hides. Note that the correct script had been posted earlier but with toggle buttons, check box etc which didn't suite my desire. This script works fine without checkbox or toggle button.
<script> function finish(){ var sdtbl = document.getElementById('sdtbl'); var x = sdtbl.rows[0].cells.length; var y = sdtbl.rows.length; //Hide unused Bonus & Deduction payroll headers for (var i = 0; i < x; i++) { var hdr = sdtbl.rows[0].getElementsByTagName('th')[i]; var val = hdr.innerHTML; if (val === "") { $('#sdtbl tr').eq(0).find('th').eq(i).hide(); for (var j = 1; j < y; j++) { $('#sdtbl tr').eq(j).find('td').eq(i).hide(); } } } } </script>
-9040430 0 try this:
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSDate *now = [NSDate date]; NSDateComponents *components = [gregorian components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:now]; NSDateFormatter* df = [[NSDateFormatter alloc]init]; [df setDateFormat:@"MM/dd/yyyy HH:mm:ss.SSS"]; NSLog(@"%@",[df stringFromDate:[gregorian dateFromComponents:components]]);
-2146254 0 While the exact naming is a convention, the difference between the treatment of header files and source files is not -- header files are not compiled into object files, but included in source files (collectively forming translation units). Moreover they may be included in multiple source files, so that multiple source files share the same definitions. The semantics of the files may be the same, but the compiler treats them differently, because of their usage.
As far as naming goes, personally I've seen at least these -- *.h
, *.H
(ugh), *.hpp
, *.hxx
, *.hh
, *.inl
(for normal headers, not just inlined code -- yuck). Usually accompanied by a matching object file extension.
Note that standard library headers don't have an extension -- e.g. string.
So it's all a matter of taste and conventions -- what you will #include
, that will be included.
Use array_push:
$array1 = array( array(1, '12-19-2014', 1113, 'credit', 50000) ); $array2 = array(1, '12-19-2014', 1111, 'debet', 50000); array_push($array1, $array2); print_r($array1);
-30982321 0 It will call the didReceiveRemoteNotification method. The "background app refresh" turn off is stop the background processes of you app. But the "remote notification" is handled by the APNS server. That will not stop your push notifications.
-2872422 0I know that it's not the Qt way, but this can be realized with Symbian SDK like this:
TInt fontFileID; TInt fontErr = CEikonEnv::Static()->ScreenDevice()->AddFile( _L("c:\\system\\apps\\<APPID>\\customFont.ttf"), fontFileID);
Here is the full link. Hope it helps.
-2066028 0Short answer - yes. In two words view just named select (without order by of course).
-4367111 0 Rails: Retrieve all records that have the same variable value in a columnI've been asked to right a report of users that have the same billing address. Of course, I don't have a list of addresses to compare against, so is there a way to return all records that share an address with another record?
Thanks!
-32487089 0 PasswordBox weird behaviour in Windows 10I am trying to use a PasswordBox
in my Windows 10 universal application. The problem that I am facing is that if I am pre-populating a PasswordBox
with some text before the user has any chance to type in it, the reveal button is not shown anymore. This does not happen if I am populating the PasswordBox
while the app is running. I also tried with/without the recommended PasswordRevealMode
and the deprecated IsPasswordRevealButtonEnabled
, but no luck.
This is a small snippet to demonstrate the problem:
<StackPanel> <TextBlock Text="Pre-populated:"/> <PasswordBox x:Name="PrePopulatedPasswordBox" PasswordRevealMode="Peek" Password="123456" /> <TextBlock Text="Type to populate"/> <PasswordBox x:Name="PopulatedWhenRunningPasswordBox"/> </StackPanel>
I don't think that this is the intended behaviour (as far as I understood from here: https://msdn.microsoft.com/en-uS/office/office365/windows.ui.xaml.controls.passwordbox.aspx)
-19873153 0can i deploy database and java web service in different server?
Yes you can, database and web-server are not dependent on each other installation. Just make sure you have the connectivity between the two machines, firewall allows connection on the desired port.
-21255447 0You miss-spelled data-toggle
in your dropdown triggering link, you wrote it data-toogle
. Change it to data-toggle
and it will work.
Quite often there is the chance that protractor test specs throws a timeout exception.
To make debugging and troubleshooting easier, I would like to stop protractor just after a timeout exception and prevent it to continue running test.
But trying to catch timeout exception at each promise looks quite ugly to do.
Is there any other way to stop protractor when it throws a timeout exception?
-25608124 0The short answer is no. If you really know nothing of the format, then you are stuck. You might see some "obvious" text, in some language, but beyond that, it's pretty much impossible. Your Hex editor reads the file as a group of bytes, and displays, usually, ASCII equivalents beside the hex values. If a byte is not a printable ASCII character, it usually displays a .
So, text aside, if you see a value $31 in the file, you have no way of knowing if this represents a single character ('1'), or is part of a 2 byte word, or a 4 byte long, or indeed an 8 byte floating point number.
-24776880 0You can create a custom converter that tries to read an array of integers, and returns an empty array if the data isn't correct:
class MyCustomInt32ArrayConverter : JsonConverter { public override object ReadJson( JsonReader reader, Type objectType, Object existingValue, JsonSerializer serializer) { var array = serializer.Deserialize(reader) as JArray; if (array != null) { return array.Where(token => token.Type == JTokenType.Integer) .Select(token => token.Value<int>()) .ToArray(); } return new int[0]; } public override void WriteJson( JsonWriter writer, Object value, JsonSerializer serializer) { serializer.Serialize(writer, value); } public override bool CanConvert(Type objectType) { return objectType == typeof(int[]); } }
Just apply the converter to the property using the JsonConverterAttribute
attribute :
[JsonConverterAttribute(typeof(MyCustomInt32ArrayConverter))] [JsonProperty("my_test_property_json_key", NullValueHandling = NullValueHandling.Ignore)] public int[] MyTestProperty{ get; set; }
-24129705 0 Try making the background transparent and making the view not opaque
[_spinner setOpaque:NO]; [_spinner setBackgroundColor:[NSColor clearColor]];
-11782310 0 The problem is that you can only switch on one known type.
In your case you are trying to switch across multiple possible types which is flawed in itself. (How can users be expect to add to your code here?)
What you need is an interface
interface Sensor { void sense(); } enum PhoneSensor implements Sensor { A, B; @Override public void sense() { System.out.println(this); } } public <E extends Enum<E> & Sensor> void registerSensor(EnumSet<E> eSet) { for (E e : eSet) { System.out.print("value is "); e.sense(); } }
This way users can add any enum which implements Sensor and they can do whatever they want without having to change your code.
-5716135 0 Does Ruby on Rails have a standard mechanism of adding a param to current URL and removing one?That is, if the current URL of the page is
http://www.foo.com/products/?q=fruit&order=ascending
then a way to link to a URL without the order
param, and a way to link to a URL with an added param, such as page=2
(note that we can't just append &page=2
to it, because what if the current URL has no ?
, then adding the &
like that won't work)
I have done an iOS app to get location every 10 minutes and to update the location to the server through web service. I have used setKeepAliveTimeout method to do with VOIP configuration. I didn't use any stream. It works well. But when I reboot my mobile. It does not call a particular method after 10 minutes automatically. Only when I reopen the app again, It gets updated.
Here is my code:-
[[UIApplication sharedApplication] setKeepAliveTimeout:600 handler:^{ //call update method }];
Please help me with this. Thanks in Advance.
-26729116 0I just made cache:false
in ajax and code worked.
It was as follows:
$.ajax({ type: "POST", url: "/Company/validateForm", cache:false, dataType: "json", data: { 'txtCompanyName': txtCompanyName, 'txtCompanyContactPerson': txtCompanyContactPerson, 'txtCompanyPhone': txtCompanyPhone, 'txtCompanyFax': txtCompanyFax, 'txtCompanyEmail': txtCompanyEmail, 'txtCompanyWebsite': txtCompanyWebsite, 'txtZipcode': txtZipcode, 'txtCountry': txtCountry, 'txtAddress1': txtAddress1, 'txtAddress2': txtAddress2, 'txtCompanyRegNo': txtCompanyRegNo } , success: function (responceMessage) { if (responceMessage != "0") { alert(responceMessage); } else { saveCompanyInformation(); } }, error: function () { alert('failure'); } });
-35505766 0 The best way around this would be a redesign, if at all possible.
You can even implement this retrospectively by adding a new column to replace the schema, for example: Profile
, then merge all tables from each schema into one in a single schema (e.g. dbo
).
Then your procedure would appear as follows:
create procedure dbo.usp_GetDataFromTable1 @profile int, @userid bigint as begin select a.EmailID from dbo.Table1 a where a.ID = @user_id and a.Profile = @profile end
I have used an int
for the profile column, but if you use a varchar
you could even keep your schema name for the profile value, if that helps to make things clearer.
You can use the Environment.GetFolderPath
method and Combine
it into a real path:
String subPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),"Reports");
-41074129 0 Facebook native ad won't click: Android I am creating a native ad on android using audience network. The problem is that the ads are shown but do not click.Whenever I click on any of the views I registered for clicking the ad, nothing happens. I am loading the ads into a custom listView with a custom adapter:
static StaticListView turning_up_lv; //My custom listview private static void showNativeAd() { nativeAd = new NativeAd(context, AD_ID); nativeAd.setAdListener(new AdListener() { @Override public void onError(Ad ad, AdError error) { } @Override public void onAdLoaded(Ad ad) { if (ad != nativeAd) { return; } isAdLoaded = true; if ((turning_up_lv.getAdapter()) != null && turning_up_lv.getCount() > 3) { ((MyAdapter) turning_up_lv.getAdapter()).addNativeAd(ad, false); } } @Override public void onAdClicked(Ad ad) { } }); nativeAd.loadAd(NativeAd.MediaCacheFlag.ALL); }
Here is the code for the custom listview:
public class StaticListView extends ListView { public StaticListView(Context context) { super(context); } public StaticListView(Context context, AttributeSet attrs) { super(context, attrs); } public StaticListView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(MEASURED_SIZE_MASK, MeasureSpec.AT_MOST)); getLayoutParams().height = getMeasuredHeight(); }
}
And finally here is the part where I load the ad into the adapter. Note that I have removed some irrelevant parts since the adapter is so long
@Override public View getView(final int position, View convertView, final ViewGroup parent) { View row = convertView; MyViewHolder holder; if (row == null) { LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); row = inflater.inflate(R.layout.turning_up_item, parent, false); holder = new MyViewHolder(row); row.setTag(holder); } else { holder = (MyViewHolder) row.getTag(); } if (position == AD_INDEX && ad != null) { inflateAd((NativeAd) ad, holder, row); } else { //Load other listview items } }
Here is the code for inflating the ad:
private void inflateAd(final NativeAd nativeAd, MyViewHolder holder, final View view) { // Create native UI using the ad metadata. // Setting the Text holder.time_tv.setText("Sponsored"); holder.native_ad_social_context.setText(nativeAd.getAdSocialContext()); holder.native_ad_call_to_action.setText(nativeAd.getAdCallToAction()); holder.native_ad_call_to_action.setVisibility(View.VISIBLE); holder.un_tu.setText(nativeAd.getAdTitle()); holder.comment_or_caption_tv.setText(nativeAd.getAdBody()); // Downloading and setting the ad icon. NativeAd.Image adIcon = nativeAd.getAdIcon(); NativeAd.downloadAndDisplayImage(adIcon, holder.ad_iv); // Downloading and setting the cover image. NativeAd.Image adCoverImage = nativeAd.getAdCoverImage(); int bannerWidth = adCoverImage.getWidth(); int bannerHeight = adCoverImage.getHeight(); DisplayMetrics metrics = context.getResources().getDisplayMetrics(); int mediaWidth = holder.native_ad_media.getWidth() > 0 ? holder.native_ad_media.getWidth() : metrics.widthPixels; holder.native_ad_media.setLayoutParams(new LinearLayout.LayoutParams( mediaWidth, Math.min( (int) (((double) mediaWidth / (double) bannerWidth) * bannerHeight), metrics.heightPixels / 3))); holder.native_ad_media.setAutoplay(AdSettings.isVideoAutoplay()); holder.native_ad_media.setNativeAd(nativeAd); addLoadedToMediaView = true; final ArrayList<View> clickableViews = new ArrayList<>(); clickableViews.add(holder.native_ad_media); clickableViews.add(holder.native_ad_social_context); clickableViews.add(holder.native_ad_call_to_action); nativeAd.registerViewForInteraction(view, clickableViews); }
-29689471 0 How to integrate a native Android navigation drawer in a Hybrid MobileFirst Platform app I'm building a hybrid mobile app for Android with IBM MobileFirst Platform Foundation 7. Yesterday I created a side menu using native code. It works well but when I try to integrate it with the hybrid app - to load the local file the side menu does not work. I am following this Android Slide Menu tutorial.
I inserted the following code into the onCreate
function:
WL.createInstance(this); WL.getInstance().showSplashScreen(this); WL.getInstance().initializeWebFramework(getApplicationContext(), this);
Can anyone help me on how to integrate the native android slide menu to the app?
My project: https://github.com/nguyengiangdev/HybridApp
-29329425 1 DataStax OpsCenter 5.1.0 fails to start due to python 'ImportError'Trying to start a tarball installation of OpsCenter 5.1.0 on Ubuntu 14.04 64-bit by running ./opscenter in /opt/opscenter-5.1.0/bin fails with the following error:
Traceback (most recent call last): File "./bin/twistd", line 28, in <module> from twisted.scripts.twistd import run ImportError: cannot import name run
My version of python is 2.7.6:
$ python --version Python 2.7.6
And trying to import twisted results in:
$ python -c "import twisted; print twisted" Traceback (most recent call last): File "<string>", line 1, in <module> ImportError: No module named twisted
The value of PYTHONPATH from opscenter looks as follows:
PYTHONPATH: ./src:/usr/lib/python2.7/site-packages:./src/lib/python2.7/site-packages:./lib/python2.7/site-packages:./lib/py:./lib/py-debian/2.7/amd64::
What is going wrong here and can someone suggest a workaround that is worth trying to a Python newbie?
-40017075 0Try giving this xpath instead of that.
IWebElement downloadElement = driver.FindElement(By.XPath("/html/body/div[2]/div/main/section[1]/div/div/ul/li[1]/a/strong"));
Sometimes their is some problems with IE11 selenium is not able to work as expected. so i use double click instead of click in certain scenarios.
Actions action = new Actions(driver); action.moveToElement(driver.findElement(By.xpath("/html/body/div[2]/div/main/section[1]/div/div/ul/li[1]/a/strong"))).doubleClick().perform();
try using both, hope it will helps
-20052054 0 Adjust size of window according to screen size/resolutionI am designing a window where I have a scroll viewer, but do not want to enable it on a large screen (say on a 22"). I want the scroll bar to be enabled only when the screen size/ resolution is small (maybe on a 15" when the dialog wont fit inside it). So I cannot use the following:
Window.SizeToContent = "WidthAndHeight"
Also, my windows are made up of multiple user controls (so I cannot use the "SizeToContent" in individual User Controls either), hence the size of the window is dynamic (based on user selection).
How do I achieve this? Thanks!
-37277341 0 Check if all tuples in a list are different (ECLiPSe)I have a list with tuples like this:
[(1,2),(5,3),(6,7)]
I'm trying to write a predicate that checks if all tuples in a list are different. The following line works for a list with integers but not for a list with tuples:
all_diff(L) :- \+ (select(X,L,R),member(X,R)).
member/2
works fine to check if a tuple is in a list but it is the select/3
that has problems with tuples. It gives a type error.
How do I check if all tuples are different?
-8671587 0From the OAuth 2.0 Spec:
The authorization code provides a few important security benefits such as the ability to authenticate the client, and the transmission of the access token directly to the client without passing it through the resource owner's user-agent, potentially exposing it to others, including the resource owner.
So, basically - the main reason is to limit the # of actors getting the access token.
"token" response is intended primarily for clients that live in the browser (e.g.: JavaScript client).
-8372277 0A remote webpage can't access local files. (The URL you're using is to a file in your bundle.)
Can you host the CSS elsewhere? Otherwise, you might just load the CSS from the file yourself and insert it into the DOM in a style element.
-32924525 0This problem is very complicated, so I recommend to use Picasso
(http://square.github.io/picasso/) to handle image problems. It handles ImageView recycling and download cancelation in an adapter.
And there is also an official guide on how to handle concurrency problems when loading images in a list: http://developer.android.com/training/displaying-bitmaps/process-bitmap.html. This solution, which is based on AsyncTask
, works too.
For OOM problems, try to downsample the images before they are loaded in memory. Check this: http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
-17280104 0 Difference between DESede and TripleDES for cipher.getInstance()I am trying to get TripleDES encryption working in Java. From the Wikipedia article under Keying Options
, I want to use option 1, where All three keys are independent
.
From the Cipher docs it says to go to the reference guide here, but it still isn't clear to me.
I am working on getting examples running, and use both of these lines in different projects:
Cipher c = Cipher.getInstance("DESede"); Cipher cipher = Cipher.getInstance("TripleDES/ECB/PKCS5Padding");
Both compile fine, so what's the difference? Should I be using one over the other? Do both of these work for using three separate keys?
-28305124 0How about using an anonymous inner class instead of a lambda expression?
IntegerProperty property = new SimpleIntegerProperty(); InvalidationListener listener = new InvalidationListener() { @Override public void invalidated(Observable observable) { //TODO do something property.removeListener(this); } }; property.addListener(listener);
The answer was partly in the comments so I'll add my [brian] solution here.
public void someMethod(){ for(Spec spec : specs){ spec.myProperty().addListener(listener); } } ChangeListener<Number> listener = new ChangeListener<Number>() { public void changed(ObservableValue<? extends Number> obs, Number ov, Number nv) { Spec spec = (Spec)((SimpleLongProperty)obs).getBean(); spec.myProperty().removeListener(this); } };
Note, when I create myProperty in the Spec class I use the full constructor to specify the bean. new SimpleLongProperty(this, "myProperty", 0l);
Even doing this you still can't use a lambda to remove this
.
The Microsoft project "Roslyn" may be the key term you're looking for here. It's a C# and VB.NET compiler that will allow you to extend the language if that's what you'd like to experiment with.
The .NET Compiler Platform ("Roslyn") provides open-source C# and Visual Basic compilers with rich code analysis APIs.
The source code can be found on GitHub here: https://github.com/dotnet/roslyn
Doing a quick google, I found this blog post which goes through an example (albeit, this was an old post, so things may have changed).
-3140877 0 Refactoring some code with 'instanceof' to overloaded method solution in JavaI have this piece of code from GWT in Action:
public void processOperator(final AbstractOperator op) { System.out.println("Wordt deze ooit aangeroepen?"); if (op instanceof BinaryOperator) { if ((data.getLastOperator() == null) || (data.isLastOpEquals())) { data.setBuffer(Double.parseDouble(data.getDisplay())); data.setInitDisplay(true); } else { data.getLastOperator().operate(data); } data.setLastOperator(op); } else if (op instanceof UnaryOperator) { op.operate(data); } data.setLastOpEquals(false); }
I want to eliminate the 'instanceof' part by using method dispatching:
public void processOperator(final BinaryOperator op) { if ((data.getLastOperator() == null) || (data.isLastOpEquals())) { data.setBuffer(Double.parseDouble(data.getDisplay())); data.setInitDisplay(true); } else { data.getLastOperator().operate(data); } data.setLastOperator(op); data.setLastOpEquals(false); } public void processOperator(final UnaryOperator op) { op.operate(data); data.setLastOpEquals(false); }
But now I run into trouble in the code below from class ButtonOperator. The following code has AbstractOperator as a type in the constructor. The code for the types UnaryOperator and BinaryOperator would look exactly the same, so it feels a little cumbersome having to make special constructors for them containing the exact same code. What is a better approach?
public ButtonOperator(final CalculatorController controller, final AbstractOperator op) { super(op.label); this.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { controller.processOperator(op); } }); this.setStyleName(CalculatorConstants.STYLE_BUTTON); }
-18698549 0 once again it was threading problem. core data objects are not thread safe!
-15521135 0You could use one of the Delegate.CreateDelegate overloads to achieve this. But you need to know the target object (the object, which contains the method you want to get called when the event raises)
An example (pseudo code):
public void TextBox1_Validating(object sender, CancelEventArgs args) { // handle the event } public void RegisterEvent() { CancelEventHandler handler = (CancelEventHandler)Delegate.CreateDelegate( typeof(CancelEventHandler), this, "TextBox1_Validating"); textBox1.Validating += handler; }
You can also read this MSDN article, which shows some other ways: How to: Hook Up a Delegate Using Reflection
-3650499 0 Draggable has been droppped and cloned, but the clone isn't draggableBit of a cryptic title there, hopefully you can help :)
When I drag one of the Draggables, it clones itself but doesn't drop on the droppables :(
any ideas?
My code:
<!DOCTYPE HTML> <html> <head> <title>jQi</title> <script type="text/javascript" language="javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script> <script type="text/javascript" language="javascript" src="jquery-ui-1.8.4.custom.min.js"></script> <script type="text/javascript"> $(document).ready(function() { var i = 0; var a = 250; var b = 19; //append board $('body').append('<ul id="jQiBoard"></ul>'); while (i < b*b) { $('ul#jQiBoard').append('<li class="jQiNode"></li>'); i++; } //init mouseover $('li.jQiNode').stop().mouseover(function() { $(this).animate({ opacity: 0.65 }, a); }); $('li.jQiNode').stop().mouseout(function() { $(this).animate({ opacity: 1.00 }, a); }); //append stones $('body').append('<ul id="jQiStones"></ul>'); $('ul#jQiStones').append('<li class="jQiWhite"></li>'); $('ul#jQiStones').append('<li class="jQiBlack"></li>'); $('li.jQiWhite').draggable({ snap: 'li.jQiNode', helper: 'clone', zIndex: 100, stop: function(event, ui) { } }); $('li.jQiBlack').draggable({ snap: 'li.jQiNode', helper: 'clone', zIndex: 100, stop: function(event, ui) { alert(ui.draggable); } }); $('li.jQiNode').droppable({ accept: 'li.jQiNode' }); }); </script> <style type="text/css"> ul#jQiBoard { width: 570px; height: 570px; float: left; margin: 0; padding: 0; border: 2px solid black; } li.jQiNode { display: block; width: 30px; height: 30px; float: left; list-style-type: none; border: 0px solid silver; background-color: #ae996f; background-image: url(jQiNode.gif); } ul#jQiStones { padding: 10px; border: 1px solid silver; float: left; margin: 0; padding: 0; } li.jQiWhite { width: 30px; height: 30px; background-color: transparent; list-style-type: none; background-image: url(jQiWhite.gif); } li.jQiBlack { width: 30px; height: 30px; background-color: transparent; list-style-type: none; background-image: url(jQiBlack.gif); } </style> </head> <body> </body> </html>
-30928096 0 Capybara::ElementNotFound radio by id I understand the syntax for Capybara choosing a radio button is the following
choose("Label Name")
I am running into an issue with doing this for a label that has its default name changed to an #id
.
Here is my HTML
<label for="school_application_I_20"> Do you require an I-20 Form?</label> <br> <label for="school_application_I_20_true">Yes</label> <input id="i-20-1" name="school_application[I_20]" type="radio" value="true" /> <label for="school_application_I_20_false">No</label> <input id="i-20-2" name="school_application[I_20]" type="radio" value="false" /> <br>
When I try to do the old method of choosing the element with
choose('school_application_I_20_true')
I get
Capybara::ElementNotFound: Unable to find radio button "school_application_I_20_true"
When I change the choose to use the element ID I get the same error but for the ID. Is there a way to select a radio button by ID?
-9510775 0So, in actuality, the upload script that I found on the web had is not using the a variable which it purports to be using, which is why I received no error error message. Turns out the files were being saved, just to a different directory. I had to tweak the code in a few places but it runs now. Thanks.
-35259843 0You don't. And you're mixing up pretty unrelated things.
To enable the heap verification ("PageHeap") you set the configuration you want using the GFlags utility, either using the GUI or passing it the approporiate command-line arguments (See GFlags and PageHeap). Either way, this setting it global for all binaries with the name you define.
To run the program under the debugger each and every time it starts you'd probably want to use the Debugger setting under Image File Execution Options. You can set it too using GFlags. Tick the Debugger checkbox in the Image File tab (after specifying the EXE name and hitting tab) and enter the path to the debugger.
The way this mechanism works is that (somewhere) inside CreateProcess
there's a test whether or not IFEO\Debugger is set for the program you're trying to run, and if it is set, whatever set in the Debugger value is executed **and it is passed the original command line*.
So if you set
HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\foo.exe\Debugger
to be C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\windbg.exe
and then try to execute C:\Users\d_blk\Desktop\foo.exe -param 1 -param 2
, Windows runs
C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\windbg.exe C:\Users\d_blk\Desktop\foo.exe -param 1 -param 2
and WinDbg passes everything after foo.exe
to the target program (as noted here).
So you see, there's no need to set the command-line arguments to the program you're debugging anywhere but wherever you're running it.
The only connection between PageHeap and IFEO\Debugger is that you can control both of them through the GFlags utility.
Note all the usual caveats for using IFEO\Debugger. For example:
CreateProcess
a handle to WinDbg, not the target process (and process ID, etc.).STARTUPINFO
argument applies to WinDbg, not the target process. Same for lpEnvironment
I guess.If that doesn't affect you great. If it does, an alternative might be adding an unhandled exception at the beginning of your program, and setting WinDbg as the post-mortem debugger (AeDebug
)
You cannot do what you want (because you ruled out dynamic allocation), and your "solution" does not work in general, even if you avoid the problems with compiler-generated special member functions which others mentioned. One problem is that types not only have a size, but also an alignment. For example, your real class contains an int
, however your replacement class contains only a char
array. Now on most platforms, int
has alignment 4 (i.e. an int
must be located at a 4 byte boundary), while char
has aligment 1 (it cannot have any other alignment without violating the standard). That is, as soon as you try to create an object with your replacement definition, you risk getting it misaligned, which in the best case will cause a massive slowdown, in the worst case a crash of your program (and in the absolutely worst case, it will work in your tests, but fail when actually used).
This appears to be a defect in the dotnet dnx tools but in my case I was able to work around the defect. I expect a fix will will be in place by RTM as this was an RC build of dot net core.
The Nuget.HttpSource constructor assigns the credentials as follows when the environment variable "http_proxy" is in the simple (non-username) format:
UriBuilder builder = new UriBuilder(environmentVariable); WebProxy proxy = new WebProxy(environmentVariable); if (string.IsNullOrEmpty(builder.UserName)) { proxy.Credentials = CredentialCache.DefaultCredentials; }
DefaultCredentials is set to an immutable set of empty Credentials:
SystemNetworkCredential.s_defaultCredential = new SystemNetworkCredential(); private SystemNetworkCredential() : base(string.Empty, string.Empty, string.Empty) {}
Since SetProxyOptions() checks the credential using:
if (credential != null) { if (string.IsNullOrEmpty(credential.UserName)) throw ...
And the UserName is Empty it will always throw an exception.
If instead it were to check using:
if (credential != null && !string.IsNullOrEmpty(credential.UserName)) // do cred work
Then all would be well. Null or default credentials (e.g. SystemDefaultCredentials which are immutably empty) would be treated as "no credentials".
Otherwise Microsoft could change the DNX tool to leave the credentials null instead of using the SystemDefaultCredentials. This is a simple case of the caller and callee disagreeing on the protocol for specifying a lack of credentials (null ref vs. ref with empty strings).
In my case the workaround I used was to fill in a bogus credential so that the dnx tool wouldn't throw. Luckily my proxy server didn't complain about the unwanted and invalid credential.
-9289460 0You should extends Canvas class.
Override OnDraw() Method and create point's zone for your image.
Point[][] points = new Point[5][5] Then lay it(use relation layout) to your screen.
Get zone where you touch it. if(points[i][j] == your Touch(get coordinates)){
}
-8189287 0I think what you may be seeing is:
http://servername.domain.com/virtualdirectoryname/applicationname
If you have named your virtual directory the same name as your application then I could see how that could confuse you. If you had no virtual directory and just your application at the root of the Default Web Site you'd be seeing:
http://servername.domain.com/applicationname
Is your virtual directory the same name as your application name? If so, that is why you see this.
-980322 0Colon. Space + Underscore is used to split a single statement over multiple lines.
-206899 0 What's the best way to truncate a URL so that it fits within a layoutWhat is the best way to truncate a URL when displaying it within a web page? I don't mean a link but literally displaying the URL as a value to the user, assuming that the text might be in a container of fixed width and you don't want to wrap or run outside of the container?
Is it better to truncate from the end, favouring the early part of the url:
eg. http/really.long/urlthaticantf...ere.html
Or place the '...' in the middle to favour the start and end of the link as the most value in terms of giving context:
eg. http/really.long/ur...aticantfithere.html
Also what is a good rule of thumb when choosing how long to make the truncated url? Should you be pessimistic and pick a likely wide character such as capital 'M' and see how many of these fit in the layout? This tends to give really short URLs in general as most characters are much narrower than 'M'.
Or should you be optimistic and use a truncation that generally gives a good length but risk overrunning when the URL contains many large characters?
-22690456 0 Can't check if more than 1 post data isset in the same if statementI'm trying to validate data but I'm having trouble.
The problem is I am checking if certain post data is set. Problem is it's either always set or not, i think it's because I am trying to check for multiple things in an incorrect format in my if statement?
I think it's only this line that is incorrect but I am having some sort of mental block.
I understand it is probably something quite trivial but I can't think of a way to word it to find a solution via Google.
if ((!isset($_POST['first_name'])) || (!isset($_POST['contact_no'])) || (!isset($_POST['device'])) || (!isset($_POST['fault']))) { echo 'no Name, contact number, device or fault given.'; }
I know i could check in separate if's but I would really like to refresh how i check multiple items in the same statement..
After trying suggestions, without any luck, adding more information:
if (isset($_POST['posted']) == 'TRUE') { $error = array(); if( !isset($_POST['first_name']) ){ $error[] = 'no Name given.'; } elseif( !isset($_POST['contact_no']) ){ $error[] = 'no contact number given.'; } elseif( !isset($_POST['device']) ) { $error[] = 'no Device given.'; } elseif( !isset($_POST['fault']) ) { $error[] = 'no fault given.'; } if( count($error)!==0){ echo 'Error(s) occured:<br />'.implode('<br />', $errors); } else { $db->query("INSERT INTO repairs (r_oem, r_device, r_mod, r_reserve, r_price, r_s_date, r_e_date, r_notes, rc_fname, rc_lname, rc_email, rc_contactno, rc_return, rc_status, rc_status_2, rc_status_txt, rc_status_txt_2, booked_by, passcode) VALUES( '$make', '$device', '$model', '$fault', '$price', '$date', '$date2', '$notes', '$fname', '$lname', '$email', '$cno', '','$status', '', '', '', '$bookedby', '$pass')"); $get_id = $db->query("SELECT LAST_INSERT_ID()"); $print_id = $db->fetch_row($get_id); $last_r_id_insterted = $db->query("SELECT * FROM `repairs` ORDER BY `repairs`.`r_id` DESC LIMIT 1"); $plrid = $db->fetch_row($last_r_id_insterted); echo '<br />'; echo <<<EOF <script> alert("Successfully created record for {$fname} {$lname}\'s {$make} {$device} {$model}. Job Reference: {$plrid['r_id']}"); </script> EOF; print "<span style='float: left; margin-left:25px;'><a class='button positive' 'href=\"print_label.php?ref={$plrid['r_id']}\" target=\"_blank\">Printable Sticky Label.</a></span><span class='fright'><a class='button positive' href=\"print_card.php?ref={$plrid['r_id']}\" target=\"_blank\">Printable Customer Card.</a></span><br /><br />"; if (isset($_POST['item1'])) { $db->query("UPDATE repairs SET part1id={$_POST['item1']} WHERE r_id={$plrid['r_id']}"); $db->query("UPDATE stock SET commited=commited+1, s_count=s_count-1 WHERE id={$_POST['item1']}"); } if (isset($_POST['item2'])) { $db->query("UPDATE repairs SET part2id={$_POST['item2']} WHERE r_id={$plrid['r_id']}"); $db->query("UPDATE stock SET commited=commited+1, s_count=s_count-1 WHERE id={$_POST['item2']}"); } if (isset($_POST['item3'])) { $db->query("UPDATE repairs SET part3id={$_POST['item3']} WHERE r_id={$plrid['r_id']}"); $db->query("UPDATE stock SET commited=commited+1, s_count=s_count-1 WHERE id={$_POST['item3']}"); } if (isset($_POST['item4'])) { $db->query("UPDATE repairs SET part4id={$_POST['item4']} WHERE r_id={$plrid['r_id']}"); $db->query("UPDATE stock SET commited=commited+1, s_count=s_count-1 WHERE id={$_POST['item4']}"); } if (isset($_POST['item5'])) { $db->query("UPDATE repairs SET part5id={$_POST['item5']} WHERE r_id={$plrid['r_id']}"); $db->query("UPDATE stock SET commited=commited+1, s_count=s_count-1 WHERE id={$_POST['item5']}"); } else { print "No Parts Selected<br />"; } } }
-21769708 0 Your issue is not with Array
, your question really involves escape sequences for special characters in strings. As the \
character is special, you need to first prepend it (escape it) with a leading backslash, like so.
"\\"
You should also re-read your link and the section on escape sequences.
-37433536 0I think because MainActivity was already started before so no new intents is being passed to it.
Try destroying the main activity before you go to list activity. See if this works
-15846134 0You probably want to declare fields, and get the values of the parameters in the constructor, and save the parameters to the fields:
public static class TCP_Ping implements Runnable { // these are the fields: private final int a; private final String b; // this is the constructor, that takes parameters public TCP_Ping(final int a, final String b) { // here you save the parameters to the fields this.a = a; this.b = b; } // and here (or in any other method you create) you can use the fields: @Override public void run() { System.out.println("a: " + a); System.out.println("b: " + b); } }
Then you can create an instance of your class like this:
TCP_Ping ping = new TCP_Ping(5, "www.google.com");
-39851526 0 is it as simple as sitting in branchB and doing:
git merge branchA
Yes, git has power in its simplicity.
or do i need to do a:
git pull origin branchA
What's the difference here?
The only difference here refers to using a remote repository. If you're pushing code to a remote, like Github, from another machine (or working with another person) then you would want to fetch any updates from there. If all changes are just on your local machine, then a pull will provide no new information.
Doesn't pull do an implicit merge?
Yes, it's shorthand for git fetch
and then git merge
Does
git merge branchName
do an implicit pull on the branchName?
Nope. Merge only uses your local branch. So, not to confuse you further, but your remotes have local "tracking branches" that you could merge like:
git merge remote/branchName
-16416701 0 There is a simple method of serving a folder over HTTP with WEBrick.
And as for Rack, it by itself doesn't deal with serving files. You have to read the file you want to serve over HTTP and give Rack the contents of the file and for that you could try this quick-and-dirty solution:
def call(env) contents = File.open("index.html") { |f| f.read } return [200, {"Content-Type" => "text/html"}, [contents]] end
-40987224 0 It's definitely possible, in your ActiveAdmin model just add :
controller do def update_resource(object, attributes) attributes.first[:your_attribute] = ... object.send(:update_attributes, *attributes) end
Hope it helps!
-27249662 0You can do it by using the animate function like this:
$('#square').on('mousedown', function(e) { $(this).animate({height:-200},2500); });
Updated code to create a "curtain raising" like animation:-
$('#square').on('mousedown', function(e) { $(this).animate({height:-200},2500); $(this).children().animate({"margin-top":"-400px"},2500, function() { $(this).css({"margin-top":0}) }); });
CSS:
`#square{ overflow:hidden; }`
-8808044 0 The Cortex M3 has excellent fault handling features that will make your life easier. On hitting a fault, it automatically stacks several registers like PC and LR, and fault status registers will tell you things like address of bus fault, etc.
You should implement a good fault handler (for example, the hard fault handler here: http://blog.frankvh.com/2011/12/07/cortex-m3-m4-hard-fault-handler/) to print out the stacked registers and debug fault status registers.
You should use the UART for printing, just write your own simple custom version of printf for use from your fault handler that doesn't depend on interrupts. Just write bytes directly to uart Tx data register and poll for byte completion.
-14091509 0 Error inflating row layout in a listviewI'm trying to implement flowtextview into bauerca / drag-sort-listview but I'm getting an error inflating a row. Could you help me?
Error line is in (ResourceDragSortCursorAdapter.java (Bauerca)):
@Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return mInflater.inflate(mLayout, parent, false); }
Eclipse says:
Ecipse says "FATAL EXCEPTION: main android.view.InflateException: Binary XML file line #8: Error inflataing class com.pagesuite.flowtext.FlowTextView"
The row layout is:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="67dp" android:orientation="horizontal"> <com.pagesuite.flowtext.FlowTextView android:id="@+id/nuevo_ingr_row_text" android:layout_width="fill_parent" android:layout_height="wrap_content" > <ImageView android:id="@id/drag_handle" android:layout_width="wrap_content" android:layout_height="67dp" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:padding="10dip" android:background="@drawable/ic_move" /> <ImageView android:id="@id/click_remove" android:layout_width="67dp" android:layout_height="67dp" android:layout_alignParentRight="true" android:layout_marginTop="400dip" android:padding="10dip" android:background="@drawable/ic_close" /> </com.pagesuite.flowtext.FlowTextView> </LinearLayout>
-7565103 0 Try to set an @Produces("text/plain") and return a String (cast from your char)
Likewise, an @Consumes should do the same trick for input.
(Having said that, you should probably emphasize the payload more. Just having chars as input/output is an indicator that your resource design is flawed)
-18449819 0 what are the necessary steps to transfer the mastership of the clearcase stream to different location?I created one stream and now I would like to know the procedure to transfer the mastership of the stream in a different location? what are the steps should I follow?
Any help will be appreciated.
Thanks !!
-25980520 0Hint: Since you are using C++, look up the hex
I/O Manipulator:
http://en.cppreference.com/w/cpp/io/ios_base/fmtflags
If you want to use the C style I/O, look up the printf
modifier, %x
, as in "0x%02X "
.
Edit 1:
To save in a variable, using C style functions:
char hex_buffer[256]; unsigned int i; for (i = 0; i < size; i++) { snprintf(hex_buffer, sizeof(hex_buffer), "%x ", buffer[i]); }
Using C++, lookup the std::ostringstream
:
std::ostring stream; for (unsigned int i = 0; i < size; ++i) { stream << hex << buffer[i] << " "; } std::string my_hex_text = stream.str();
-4774562 0 Uninitialized memory allocated by new
won't behave nice with strlen()
.
It'd be better if one wrote:
memset(szBuf, 0, MAX_MSG * sizeof *szBuf);
You could also skip sizeof *szBuf
since it's guaranteed to be 1, but it doesn't hurt.
To add to other answers (obviously GDB...), LLDB is BSD-style licensed which is more permissive. It is part of the LLVM Compiler Infrastructure. is very similar to GDB (see a comparison).
Following your edit: it is not ready for windows yet but efforts are under way so it should be soon.
-3312852 0 How do you add image file to a image list in code?I have an image list and would like to add a directory of images to the image list in my code. How would I do this? When I run the code:
'Load all of the items from the imagelist For Each path As String In Directory.GetFiles("Images\LanguageIcons\") imlLanguagesIcons.Images.Add(Image.FromFile(path)) Next
I get an out of memory exception. Currently there is only 14 images so there really shouldn't be a problem. Any Help?
-3348263 0 DJANGO allow access to a certain view only from a VPN NetworkI am trying to specify the access to a certain django view only to a client calling from a VPN IP (10.8.0.3 )
My django server is supported by apache using the following .conf
<VirtualHost *> ServerAdmin webmaster@demo.cl DocumentRoot /home/project/virtualenvs/env1 ServerName client1.project.cl ServerAlias www.client1.project.cl ErrorLog /var/log/apache2/error.log CustomLog /var/log/apache2/access.log combined <Location "/"> SetHandler python-program PythonHandler virtualhandler SetEnv DJANGO_SETTINGS_MODULE project.settings PythonOption django.root SetEnv SITE_CLIENT_ID client1 PythonDebug On PythonPath "['/home/project/virtualenvs/env1/django-site','/home/project/virtualenvs/env1/bin'] + sys.path" </Location> Alias /media "/home/project/virtualenvs/env1/lib/python2.6/site-packages/django/contrib/admin/media/" <Location /media> SetHandler None </Location> <Location /nodesaccess > order Deny,Allow Deny from all Allow from 10.8.0.3 SetHandler python-program PythonHandler virtualhandler SetEnv DJANGO_SETTINGS_MODULE project.settings PythonOption django.root SetEnv SITE_CLIENT_ID client1 PythonDebug On PythonPath "['/home/project/virtualenvs/env1/django- site','/home/project/virtualenvs/env1/bin'] + sys.path" </Location> </VirtualHost>
This previous configuration allows to create many django applications depending of the url, I recover the env variable and then apache load a certain setting.py which is exclusive and depends of the subdomain. Very interesting
Everything works fine (my applications) except that the access can not be denied using the "Allow from 10.8.0.3"
Any ideas?
Thank you
-30101110 0use if statement inside the click event
$("#primary-menu").on('click',function(){ if ($(window).width() <= 1024) { //.......... }else{ //.......... } });
-40119102 0 FosElastica populate and index I have 2 problems in using fosElastica:
1) When I run this command: php bin/console fos:elastica:populate
, it makes all mapped field of all indexed docs to null.
"hits": [ { "_index": "app", "_type": "article", "_id": "/cms/content/foo", "_score": 1, "_source": { "title": null, "body": null } }, { "_index": "app", "_type": "article", "_id": "/cms/content/bar", "_score": 1, "_source": { "title": null, "body": null } } ]
But later if I update a doc manually fields indexed.
2) I want to strip html tags but my custom analyzer doesn't work.
FosElastica Config:
fos_elastica: clients: default: { host: localhost, port: 9200 } indexes: app: settings: index: analysis: analyzer: my_analyzer: type: custom tokenizer: standard char_filter: [html_strip] types: article: mappings: title: ~ body: {analyzer: my_analyzer} persistence: driver: phpcr model: AppBundle\Document\Article provider: ~ listener: ~ finder: ~
-940648 0 eclipse plugin not loading dll due to long path I am building an eclipse plugin (a notes plugin, but its a eclipse plugin in the end). One of the plugins my plugin depends on needs to load a native dll.
The problem is, that fails depending on where in the disk such dll is. If it is longer than a certain threshold I get the error below
java.lang.UnsatisfiedLinkError: nlsxbe (The filename or extension is too long. ) at java.lang.ClassLoader.loadLibraryWithPath(ClassLoader.java:952) at java.lang.ClassLoader.loadLibraryWithClassLoader(ClassLoader.java:921) at java.lang.System.loadLibrary(System.java:452) at lotus.domino.NotesThread.load(Unknown Source) at lotus.domino.NotesThread.checkLoaded(Unknown Source) at lotus.domino.NotesThread.sinitThread(Unknown Source) at com.atempo.adam.lotus.plugin.views.TopicView.createPartControl(TopicView.java:609)
I have added the path to Path env var, and also registered the dll to no avail. My env is Ms vista profesional, java1.5, eclipse3.4 (and lotus 8)
Anyone out there have a clue?
Many thanks in advance.
-36231293 0 must implement method doInBackground (params)I have a class extending AsyncTask which has to implement doInBackground method. I have the method defined below , still I have an error saying the class has to implement method.
public class MyDownloadJsonAsyncTask extends AsyncTask<Void , String, Bitmap> { private final WeakReference<RecyclerView_Adapter> adapterReference; MovieDataJson movieData; public MyDownloadJsonAsyncTask(RecyclerView_Adapter adapter) { adapterReference = new WeakReference<RecyclerView_Adapter>(adapter); } @Override protected MovieDataJson doInBackground(String... urls) { MovieDataJson threadMovieData = new MovieDataJson(); for (String url : urls) { threadMovieData.downloadMovieDataJson(url); } return threadMovieData; } @Override protected void onPostExecute(MovieDataJson threadMovieData) { movieData.moviesList.clear(); for(int i=0;i<threadMovieData.getSize();i++) { movieData.moviesList.add(threadMovieData.moviesList.get(i)); } if(adapterReference!=null) { final RecyclerView_Adapter adapter= adapterReference.get(); if(adapter!=null) adapter.notifyDataSetChanged(); } }
}
and at @Override for each method above says method does not override method from its superclass
-33858298 0Use String.format() to zero pad your seconds
to make sure it is always two digits:
timerText.setText(minutes + ":" + String.format("%02d", seconds));
-16129410 0 In case with real device try remove from manifest file:
<uses-library android:name="com.google.android.maps" />
Use:
$('.container .post .like').not('.liked').on('click', function() { // this gets fired even if the element has class "liked" });
Or,
$('.container .post .like :not(".liked")').on('click', function() // ^^^ space between not selector { // this gets fired even if the element has class "liked" });
-14003771 0 as you can see here, IE 9 does not support drag'n'drop.
as you can see here, IE 10 supports it.
so unless you use IE 10 you are not able to use drag'n'drop in vanilla IE.
-8003733 0 OpenGL ES get Coordinates of ObjectI am trying to make an android application, but to do so I am trying to figure out how to get the (x, y, z) coordinates of an object. How do I do this?
I am really new to OpenGL, so use simple lingo. Thanks!
-29315082 0 List optimizes erraticallyIf I execute the below code and do not press any key on the console
class Program { static void Main(string[] args) { List<Test> list = new List<Test>(1) {new Test()}; Console.ReadKey(); GC.KeepAlive(list); var x = list[0]; Console.WriteLine((x.ToString())); } } class Test { public override string ToString() { return "Empty object"; } }
Then upon analyzing the array in windbg I see the list do not contain the test object I added.
The element in the 0'th position is something else which i am not sure of
However if i add a string property to my Test class like so
class Test { public string Name = "Rohit"; public override string ToString() { return "Empty object"; } }
Then this time windbg reveals the object
Can someone please help explain what is going on? I test the above using Visual Studio 2015 (.net 4 compatability mode) on x64 windows 7
Aside: Even though i requested for the list size to be one (for my test), i see it is going with the default size of 128. So basically the initial capacity is based on some heuristics etc?
-8240048 0Short answer: You cannot: AFAIK, currently there is no way to do it from sqlalchemy
directly.
Howerever, you can use sqlalchemy-migrate for this if you change your model frequently and have different versions rolled out to production. Else it might be an overkill and you may be better off generating the ALTER TABLE ...
scripts manually.
The issue is that when a UIimageView is subclassed and called from the storyboard a different method is called for the init.
-(id)initWithCoder:(NSCoder *)aDecoder { // As the subclassed UIImageView class is called from storyboard the initWithCoder is overwritten instead of init NSLog(@"%s",__PRETTY_FUNCTION__); self = [super initWithCoder:aDecoder]; if (self) { [self setupView]; } return self; }
This resolves the issue of the rounded profile view not being called.
-6625258 0 how do I build a Facelets site at build-time?I want to use Facelets to build a static HTML prototype. This prototype will be sent out to people who do not have a running web application server such as Tomcat. Is there some way to compile a Facelets site at build-time (using Ant etc) into a set of flat HTML files?
In the simplest case we have two facelets like this:
<!-- layoutFacelet.xhtml --> <ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets"> <ui:insert name="content" /> </ui:composition> <!-- implementationFacelet.xhtml --> <ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" template="layoutFacelet.xhtml"> <ui:define name="content"> HELLO WORLD </ui:define> </ui:composition>
The output would be a single html (e.g. "implementationFacelet.output.html") like:
HELLO WORLD
In other words, Facelets is running at build-time rather than render-time, in order to produce static flat-file prototypes.
-23202916 0 Characters not properly displayed in serial monitor in arduinoCan anyone tell me why the characters are not getting printed properly in the serial monitor of Arduino? I am pasting the arduino code.
#include <SoftwareSerial.h> #include <LiquidCrystal.h> // initialize the library with the numbers of the interface pins LiquidCrystal lcd(12,11,5,4,3,2); int bluetoothTx = 15; int bluetoothRx = 14; SoftwareSerial bluetooth(bluetoothTx, bluetoothRx); int incomingByte; void setup() { pinMode(53, OUTPUT); Serial.begin(9600); lcd.begin(16, 2); lcd.clear(); bluetooth.begin(115200); // The Bluetooth Mate defaults to 115200bps delay(320); // IMPORTANT DELAY! (Minimum ~276ms) bluetooth.print("$$$"); // Enter command mode delay(15); // IMPORTANT DELAY! (Minimum ~10ms) bluetooth.println("U,9600,N"); // Temporarily Change the baudrate to 9600, no parity bluetooth.begin(9600); // Start bluetooth serial at 9600 lcd.print("done setup"); } void loop() { lcd.clear(); Serial.print("in loop"); //Read from bluetooth and write to usb serial if(bluetooth.available()) { Serial.print("BT here"); char toSend = (char)bluetooth.read(); Serial.print(toSend); lcd.print(toSend); delay(3000); }delay(3000); }
Can anyone take a look into it. It does not print the character that I provide instead it prints something else like 'y' with 2 dots on top etc. Tried almost all the available solution.
-13611882 0 HighchartsJS Click Event on iOS 6After the release of iOS6, the Highchart bar graphs we've been using in our site stopped responding to click events on iOS devices. Although the graphs render correctly, the click function simply does not fire when clicking data points within.
Oddly, I discovered that the function does fire on click in iOS if it's attached to the mouseOut event, instead. I.E. If I define events: { mouseOut: function(){ //dosomething } }
and then click the datapoint in the graph, iOS device will perform the function. (It is possible this is always the case with iOS device mouseOut, as there is no analogous touch event; the point, however, is that some events are firing in this context.)
I have created a very basic set of graphs in a flat HTML page to test the basic functionality of Highcharts in iOS 6, and that seems to work as expected for click events attached to data points.
I am happy to post the code (or a Fiddle link) with the specifics of the graph data, but I am more interested in knowing whether anyone else has seen a problem like this in iOS 6 with Highcharts JS.
Thanks so much for any insight you can offer. (As I said, the basic charts I created using the objects and data our site generates seem to work fine from a flat HTML page, so I don't think code would be terribly helpful in answering questions. But, I'm willing to post that code if someone thinks that would help them come to a conclusion.)
-36835788 0 Webdesign: Wrapping table suppresses scrollbars in IE 11 and FirefoxWe have to get a legacy web application to run in Internet Explorer 11 and Firefox. The application does not set any doctype and therefore sends both browsers into quirks mode.
We have a table that needs to be scrollable, which is embedded in a div with overflow: auto. This works on its own, but our web application embeds this div again in a table and wraps the table with another two divs. See the fiddle here:
https://jsfiddle.net/Tim_van_Beek/y7hsp1zp/3/
(Please use IE 11 or Firefox, the page does not work in Chrome at all.)
The wrapping table (the first -node in the HTML tree) seems to suppress the scrollbars. They reappear when one removes it. So while this structure does not have scrollbars (see fiddle above):
<div style="overflow: hidden;..."> <div ...> <table width="auto" height="auto" cellspacing="0" cellpadding="0"> <tbody> <tr> <td width="100%" height="100%" align="left" valign="top"> <div style="overflow: auto;"> ...table data to be scrolled
...this one does (remove the table, tbody, tr and td tags):
<div style="overflow: hidden;..."> <div ...> <div style="overflow: auto;"> ...table data to be scrolled
It would seem that one needs to format the table in a certain way to get it to display scrollbars again (or rather: not suppress the scrollbars of its child node), any suggestions?
We cannot simply remove the table from our application without compromising the rest of the layout, but we can add/modify css at will.
-1906578 0 switch mod rewritten URLWe are using a mod rewritten URL within our PHP site, this is the rewrite rule we are using:
RewriteRule ^category/([^.]+)/([0-9]+)/([^.]+)/([0-9]+) categories.php?c_id=$2&filters=$3&_p=$4&area=category&areaname=$1
However, a user of a different system is switching to our setup and wants to 301 all their old pages to their new equivalents. So, for example, this URL:
http://domain.com/categories/clothing/5/1
becomes:
http://domain.com/category/clothing/5/0-0-0-0/1
Is it possible to do this in a single rewrite rule or rewrite match (or similar), my intial thought was something like this would work:
RewriteRule /categories/(.*)/(.*)/1 /category/$1/$2/0-0-0-0-0-0-0-0/1 [R=301,L]
it doesn't, any ideas?
Also tried this with RedirectMatch which also doesnt work:
RedirectMatch /categories/(.*)/(.*)/1 http://domain.com/category/$1/$2/0-0-0-0-0-0-0-0/1
-23033073 0 Queue
is an interface not a class. LinkedList
is an implementation of Queue
interface.
You can think it like this.
Animal a = new Cat() Animal b = new Dog() Animal c = new Cow()
a,b and c are all animals. But they are all different kind of animals.
There are other implementation of Queue interface like ArrayBlockingQueue and PriorityQueue. They all implement Queue interface but do things diffferently inside. http://docs.oracle.com/javase/7/docs/api/java/util/Queue.html http://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html
You can think it like this. Animal a = new Cat() Animal b = new Dog() Animal c = new Cow()
-38081485 0Easiest way I could see to do this was absolutely positioned 'before' pseudo-element with the gradient applied to it, and the opacity set to 0 when active. I've also added a toggle on the ul itself for the sake of ease.
Easiest to give you the jsfiddle:
https://jsfiddle.net/efreeman79/8oemm50L/1/
I've added this to the styles:
li:before { content: ''; display: block; position: absolute; left: 0; bottom: 0; height: 100%; width: 100%; opacity: 1; transition: all 0.35s ease; /* GRADIENT CSS CODE HERE */ } .active li:before { opacity: 0; } li.even:before { transform: rotate(180deg); }
and this for the sake of ease:
$('ul').toggleClass('active');
It needs some polish but it does the job. Basically when the ul is active, opacity on the gradient is set to 0, when the active class is removed, the gradient layer's opacity is animated back to 1.
-25712561 0Add button to list_item then set onclick listener to the button inside the adapter
<Button android:id="@+id/button1"/>
inside adapter:
holder.go= (Button) convertView.findViewById(R.id.button1); holder.go.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //start next activity here } });
-36504754 0 Everything inside that if (isset($_FILES['picName'])and isset($_POST['submit']))
doesn't work because the superglobal $_FILES
is probably not having a key named picName
. To check this out, try var_dump
-ing the $_FILES
, like var_dump($_FILES);
By the output of the var_dump
you'd get to know if there is any content inside $_FILES
. And if it is populated, just see what the key name is and, access the file by using that key.
But if the array is empty, there may be some mis-configurations in PHP, or APACHE.
One possible fix would be setting file_uploads = On
in the ini file for php.
Hope it helps!
-17482411 0One thing to consider is how many date calculations you are performing and where in the query your conversion is taking place. If you are searching a DB of 10 million records and you are converting a DateTime field into a Unix Timestamp inside of a WHERE clause for every single record and only ending up with 100 records in the query result it would be less efficient to use SQL to perform that conversion on 10 million records than it would be to use PHP to convert the DateTime object into a Timestamp on only the resulting 100 records.
Granted, only the result of 100 records would be converted anyway if you put the conversion in the select statement so it would be pretty much the same.
-30564650 0Catch-all email trappers aren't implemented in DNS to the best of my knowledge, they're configured at the email server level. So there's no shortcut for testing this other than checking for the validity of an email address.
Note that you don't have to actually send an email to test. Within, say, an SMTP session the RCPT TO command returns: 200 or 250 on success, 251 or 551 on forward, 252 cannot verify but will accept, 450 or 550 mailbox unavailable, 552 exceeded storage, 553 mailbox name not allowed. Upon determining whether/not the wildcard exists you'd send a QUIT.
-8167645 0You should try to use JSON
var jsArray = <?php echo json_encode($phpArray); ?>;
accessible then via
jsArray.someKey
-3867462 0 I'm not familiar with Arel, but won't it handle:
l.includes(:card)
-9063466 0 Luca Bolognese has written a great series of Write Yourself a Scheme in 48 Hours in F# where he used FParsec for parsing. The full source code with detailed test cases are online here.
The most relevant post is 6th one where he talked about parsing a simple Lisp-like language. This language is closer to JavaScript than to C just so you know.
Current series on his blog is parsing lambda expressions in F# (using FParsec) which could be helpful for you too.
-1396771 0The SDF classes aren't designed to be "better" than the CF classes - they are largely an extension of the CF-supplied classes. In many cases they provides methods, properties, etc. that the full framework may have but that the CF omitted.
Obviously that's an over-simplification - for example the entire OpenNETCF.WindowsCE namespace is purely features that don't exist in the FFx or the CF, but as a general answer, that's how it works.
The SDF is not a replacement for the CF, it's an extension of it.
-34052994 0Is it possible to simply do:
git add .
That way you don't need to specifically reference the filenames that may have spaces (but will stage everything)
-1375474 0 Variable Arity in C?Does anyone knows how I might be able to implement variable arity for functions in C?
For example, a summing function:
Sum(1,2,3,4...); (Takes in a variable number of args)
Thanks!
-34948166 0I'd propose to write a function and use pd.apply
like that:
import pandas as pd df = pd.DataFrame({'a': [0, 1]}) def add500ifnot0(c): if c == 0: return c else: return c + 500 df['e'] = df['a'].apply(add500ifnot0) df
-18013893 0 Why? You only care if something is listening if you want to connect to it. So, connect to it, and handle the error. "Don't test, use." This applies to any resource. The best way to test whether it is available is to try to use it.
-6115324 0 Evasive cause inside InvocationTargetExceptionExecuting a Java code I capture an InvocationTargetException. Using the printStackTrace method I get the following:
java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at Tester.main(Tester.java:180) Caused by: java.lang.NullPointerException at [...] (it doesn't really matters)
My code checks several programs written by other persons, so the cause shown by printStackTrace is varied. However, if I try to get just the internal cause using method getCause, the result is always a disgusting null!
Java 6 API says that, from release 1.4 in advance, getCause returns the cause exception provided during construction... should I assume that Method.invoke does not construct the exception properly, or am I losing something?
Thanks in advance
-32301521 0You're trying to access parts of a variable which don't exist. You may want to check before using them, if they exist.
-10283674 0That will work if Environment.NewLine
is CR+LF, which it's likely to be on Windows. Of course it won't catch the situation where the string actually only contains line feeds, or only contains carriage returns. Perhaps you want:
StringBuilder sb = new StringBuilder(s).Replace("\r\n", "<br/>") .Replace("\n", "<br/>") .Replace("\r", "<br/>");
(Note that there's no point in using a verbatim string literal for "<br/>"
as there's no backslash in the string, and it's a single line.)
You could instead output the images as a list of divs, or just divs, and then use CSS to show the images in two columns. Your layout should not be that hardwired.
<style> div.gallery { width: 650px; } div.gallery ul li { list-style: none; float: left; } div.image { height: 500px; width: 300px; } </style> <div class="gallery"> <ul> <li> <div class="image"> <span class="image_title">Some title</span><br/> <img src="foo.png"/> </div> </li> <li> <div class="image"> <span class="image_title">Another title</span><br/> <img src="bar.png"/> </div> </li> <li> <div class="image"> <span class="image_title">Another title</span><br/> <img src="foo.png"/> </div> </li> <li> <div class="image"> <span class="image_title">Another title</span><br/> <img src="bar.png"/> </div> </li> <li> <div class="image"> <span class="image_title">Another title</span><br/> <img src="foo.png"/> </div> </li> </ul> </div>
Result:
Your code should look something like:
<div class="gallery"> <ul> <?php include_once("config.php"); $result = mysql_query("SELECT * FROM images"); while($res = mysql_fetch_array($result)) { ?> <li> <div class="image"> <a class="image_title" href="indimage.php?imageid=<?php echo $res['imageid']?>"><?php echo $res['imagename']?></a><br/> <a href="indimage.php?imageid=<?php echo $res['imageid']?>"><img src="<?php echo $res['image']?>" /></a> </div> </li> <?php } ?> </ul> </div>
-70758 0 Does anyone know of a way of hiding a column in an asp.net listview? I know you can put <% if %> statements in the ItemTemplate to hide controls but the column is still there. You cannot put <% %> statements into the LayoutTemplate which is where the column headings are declared, hence the problem. Does anyone know of a better way?
-39828675 0You could bind to an object wrapper on an elements properties, or bind the elements en masse to your own do-something
object. I found it easiest to have a pair of maps, registrants as keys object or user etc, and property name, then the maps keep the current values and (when i get to it) a generator or iterator will update the properties on the appropriate registrants. Below is an example without extending the nodeList prototype with array functions, I did the extension because looping can be well, you will see the code.
Here is some code I have in a codepen, on a project I started September 15. I am trying to get an interface for building and recording reading test passages and questions to maintain state, be able to recreate state, and offer some helpful clues about learning....
Code is redundant throughout, as I had never done the work before without the Observers Addi mentions above. In Polymer components you dont have to do your own binding. You could try that new spec v1 polymer two approach too. It has essentially a clean Object observe, and a lot of other cool features I just had a spec issue with some changes for contractual requirements.
`
var archive=[]; this.archive=[];//TODO ME: NOTE worked, recorded reported, returned re-impl state, but needs some 'slick' to stay updatable and fast... so double check then do again at least a hand full of times with generator/proxy/map... .Try on and off thread
var inputNodes=document.querySelectorAll("input");//NOTE TODO ME: replace with symbol iterator of symbols for dom nodes HTML REPLACED IN DEMO 6; var counterOne=inputNodes.length; this.inputArray=[];//check this.propertyArray=[];//check add? for(var i=0; i<counterOne;i++) { var newProp=inputNodes[i].attributes.id.value; var elem=document.getElementById(newProp); this.propertyArray.push(newProp); this.inputArray.push(elem); } var selectNodes=document.querySelectorAll("select"); var counterT=selectNodes.length; for(var zz=0; zz<counterT;zz++){ var newProp3=selectNodes[zz].attributes.id.value; var za=document.getElementById(newProp3); this.propertyArray.push(newProp3); this.inputArray.push(za); } var taNodes=document.querySelectorAll("textarea"); var counterTwo=taNodes.length; for(var i=0; i<counterTwo;i++){ var newProp2=taNodes[i].attributes.id.value; var ta=document.getElementById(newProp2); this.propertyArray.push(newProp2); this.inputArray.push(ta); } NOTE: TODO-AGAIN: ME--reinstitute the extensions to nodeListProto or at least make a helper func, this looks gross this.propertyArray.forEach((prop, index)=>{ var elem=this.inputArray[index]; if(elem.nodeName==="TEXTAREA"){ elem.value=elem.innerHTML; } if(elem.nodeName==="SELECT"){ console.log(elem.selectedIndex, "LOOK HERE DUMMY"); elem.value=elem.children[elem.selectedIndex].value; } var val=elem.value; Object.defineProperty(this, prop,{ enumerable: true, configurable: true, get: function() { if(elem.type=="checkbox" || elem.type=="radio"){ this.archive.push({name:prop, value: elem.checked}); return elem.checked; } else if(elem.nodeName==="SELECT"){ var retVal=(elem.selectedIndex==undefined)?elem.children[1].value:elem.children[elem.selectedIndex].value; return retVal; } else{ if(elem.nodeName==="TEXTAREA"){ var val=elem.value; } this.archive.push({name:prop, value: val}); return val; } }, set: function() { if(elem.type=="checkbox" || elem.type=="radio"){prop=elem.checked; } else{ prop = val; } } }); if(elem.nodeName=="SELECT"){ var nom=elem.attributes.id.value; elem.addEventListener("blur",()=>{ this[`${nom}Func`]; alert("the thing changed");},false);} if(elem.type!="button"){ elem.addEventListener("change", ()=>{ var keys=Object.keys(this); console.log(keys); keys.forEach((key)=>{ console.log(key, this[key]); }); console.log(this[prop], elem.value,elem.checked, prop, "newprop values here", this.archive) }, false); } }, this); this.codeMirror={};//check `
-18622073 0 Why jsf:binding attribute creates jsessionid cookie when used on input field? Why jsessionid cookie is created when I visit page that has jsf:binding
attribute? If I remove jsf:binding
no cookie is created. I'd like to have my page cookieless. The backing bean is annotated with these two Spring annotations: @Controller
and @Scope("request")
.
<div class="form-group #{!username.valid ? 'has-error' : ''}"> <label for="username" class="col-md-2 control-label"> #{i18n['signup.username.text']} </label> <div class="col-md-4"> <input type="text" class="form-control" jsf:id="username" jsf:binding="#{username}" jsf:value="#{signUpBean.username}" jsf:maxlength="#{signUpBean.USERNAME_MAXLENGTH}" placeholder="#{i18n['signup.username.placeholder.text']}"> <f:ajax event="change" render="username-message" /> </input> </div> <h:message for="username" id="username-message" styleClass="col-md-6 help-block" /> </div>
-8065171 0 rendering UIImage with size > 1024 with OpenGL ES 2.0 on the iPhone I'm capturing a full resolution UIImage on the iPhone 4 (1936X2592)
then i'm scaling it to a square of size 1936x1936.
now i need to load this image into a texture and let OpenGL render it with some GLSL.
problem is OpenGL only supports power of 2 texture sizes and only up to 1024.
so how do i solve this?
Thank You.
EDIT: my question is irrelevant, i target 3GS and up and it supports 2048x2048 image size. my problem is another question: Camera frame to UIImage to OpenGL rendering gives an odd image (attached)
-16686055 0This is something that's usually done through the web server, so the answer depends on whether you're using Apache, Nginx, or something else. Here's how I do it with Nginx.
I typically have a directory in my site root called controllers
. All of the files in controllers
correspond to URL paths. For example:
/controllers/home.php ---> http://example.com/home /controllers/about.php ---> http://example.com/about /controllers/contact.php ---> http://example.com/contact
Then I use the web server (Nginx) to direct the traffic (which is what it's built to do). So if Nginx gets a request for http://example.com/home
, then it looks in the controllers
directory for a file called home.php
. If the file exists, then Nginx serves it up. If the file doesn't exist, then Nginx serves up some fallback page. Here's what the Nginx configuration looks like:
server { listen 80; server_name example.com; root /srv/example; index index.php; rewrite ^/(.*)/$ /$1 permanent; location / { try_files $uri $uri/ /controllers$uri.php?$args; location ~ \.php$ { try_files $uri /index.php; fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; include fastcgi_params; } } }
-4836365 0 I think you may combine following examples:
Load on demand: https://demos.telerik.com/aspnet-ajax/combobox/examples/loadondemand/wcf/defaultcs.aspx
Related combo boxes: https://demos.telerik.com/aspnet-ajax/combobox/examples/functionality/multiplecomboboxes/defaultcs.aspx
Overview: http://www.telerik.com/help/aspnet-ajax/combo_loadondemandoverview.html
I am developing a weather app like S4 weather app. This app also has a digital clock with it. I want to make other widget for digital clock in the same project and then add that widget to main widget. Hope you get the point. Here'the image link of what i am doing
Since this is my first project i am getting confused on how to add the clock widget in the main widget.
My activity_main.xml <LinearLayout> //some stuff <com.itcse.weather.DigitalClock xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/digitalClock" /> // some stuff </LinearLayout>
The GraphicalLayout
of the activity_main.xml
is showing
The following classes could not be instantiated: - com.itcse.weather.DigitalClock
which i know it should show since i haven't initialized the class anywhere. But i am getting confused in how to do it.
At present i have not done any coding in DigitalClock.java
, simply set default layout in AppwidgetProvider
. When i run the project on emulator i am getting a new widget of digital clock as option thus that means it is working.
I know i have to initialize DigitalClock
Class in my AppWidgetProvider Configure
but I am getting confused in how to do so.
I am using a DigitalClock
separately since that is my custon digital clock and would need to set update period as 0. It would be unnecessary to set the update time of main widget as 0 so i am using this widget. Is this way right?
Also i want to ask something that when i finish this project can i upload it here and ask for some suggestions on what should i have actually done. Since this is my first project so i have done a lot of hit and trial and i don't know if i can do this, so i am asking you. Is this allowed??
UPDATE:- I think i am not making myself clear. Consider that i am making two seperate widgets in my same project. One is DigitalClock
which has time and date. Another is main widget
which has weather plus time and date. Now i want that to use DigitalClock
in place of time and date in main widget
. I have declared both widgets seperatly in manifest and they both are working correctly seperatly. Is this possible?
i have a problem when i upload a video with a form in my server. In the moment of upload, the aplication, must to convert the format of the video to mp4. In my notebook, this convertion work fine but when i try to convert a video in the server, i receive this error:
ExecutableNotFoundException in FFProbeDriver.php line 50: Unable to load FFProbe
This is my form:
{!! Form::open(['route' =>'upload.store', 'method'=>'POST', 'files'=> true ]) !!} <div class = "form-group" style ="display: none;"> {!! Form::label('usuario_id', 'usuario_id:') !!} {!! Form::text('usuario_id', Auth::user()->id) !!} </div> <div class = "form-group" style ="display: none;"> {!! Form::label('state', 'State:') !!} {!! Form::text('state', 0) !!} </div> <div class = "form-group"> {!! Form::label('asignatura_id', 'Asignatura:') !!} {!! Form::select('asignatura_id', $subject) !!} </div> <div class = "form-group"> {!! Form::label('name', 'Nombre:') !!} {!! Form::text('name', null, ['class'=> 'form-control', 'placeholder' => 'Ingresa el nombre de la pelicula']) !!} </div> <div class = "form-group"> {!! Form::label('language', 'Idioma:') !!} {!! Form::text('language', null, ['class'=> 'form-control', 'placeholder' => 'Ingresa la descripcion']) !!} </div><div class = "form-group"> {!! Form::label('creation_date', 'Fecha Creación:') !!} {!! Form::text('creation_date', null, ['class'=> 'form-control', 'placeholder' => 'Ingresa el nombre de la pelicula']) !!} </div> <div class = "form-group"> {!! Form::label('description', 'Descripcion:') !!} {!! Form::text('description', null, ['class'=> 'form-control', 'placeholder' => 'Ingresa la descripcion']) !!} </div> <div class = "form-group"> {!! Form::label('imageRef', 'Imagen:') !!} {!! Form::file('imageRef') !!} </div> <div class = "form-group"> {!! Form::label('url', 'Video:') !!} {!! Form::file('url') !!} </div> {!! Form::submit('Registrar',['class' =>'btn btn-primary']) !!} {!! Form::close() !!}
The function in the model:
public function setUrlAttribute($url){ $this->attributes['url'] = 'old/'.Carbon::now()->second.$url->getClientOriginalName(); $name = Carbon::now()->second.$url->getClientOriginalName(); \Storage::disk('local')->put($name, \File::get($url)); $file = pathinfo($name,PATHINFO_FILENAME); $extension = pathinfo($name,PATHINFO_EXTENSION); $ffmpeg = \FFMpeg\FFMpeg::create([ 'ffmpeg.binaries' => '/usr/bin/ffmpeg.exe', 'ffprobe.binaries' => '/usr/bin/ffprobe.exe', 'timeout' => 0, // The timeout for the underlying process 'ffmpeg.threads' => 12, // The number of threads that FFMpeg should use ]); $video = $ffmpeg->open($url); $format = new FFMpeg\Format\Video\X264('libmp3lame', 'libx264'); $format->on('progress', function ($video, $format, $percentage) { echo "$percentage % transcoded"; }); $format -> setKiloBitrate(1000) -> setAudioChannels(2) -> setAudioKiloBitrate(256); $video ->save($format, 'files/convert/'.$file.'.mp4'); $this->attributes['url'] = $file.'.mp4'; }
if i convert the video in the console i receive this:
# ffmpeg -i 67portrait.MOV -vcodec libx264 new.mp4 FFmpeg version 0.6.5, Copyright (c) 2000-2010 the FFmpeg developers built on Jan 29 2012 17:52:15 with gcc 4.4.5 20110214 (Red Hat 4.4.5-6) configuration: --prefix=/usr --libdir=/usr/lib64 --shlibdir=/usr/lib64 --mandir=/usr/share/man --incdir=/usr/include --disable-avisynth --extra-cflags='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -fPIC' --enable-avfilter --enable-avfilter-lavf --enable-libdc1394 --enable-libdirac --enable-libfaac --enable-libfaad --enable-libfaadbin --enable-libgsm --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-librtmp --enable-libschroedinger --enable-libspeex --enable-libtheora --enable-libx264 --enable-gpl --enable-nonfree --enable-postproc --enable-pthreads --enable-shared --enable-swscale --enable-vdpau --enable-version3 --enable-x11grab libavutil 50.15. 1 / 50.15. 1 libavcodec 52.72. 2 / 52.72. 2 libavformat 52.64. 2 / 52.64. 2 libavdevice 52. 2. 0 / 52. 2. 0 libavfilter 1.19. 0 / 1.19. 0 libswscale 0.11. 0 / 0.11. 0 libpostproc 51. 2. 0 / 51. 2. 0 Seems stream 1 codec frame rate differs from container frame rate: 1200.00 (1200/1) -> 29.97 (30000/1001) Input #0, mov,mp4,m4a,3gp,3g2,mj2, from '67portrait.MOV': Metadata: major_brand : qt minor_version : 0 compatible_brands: qt date : 2013-11-29T13:19:09+0100 date-fra : 2013-11-29T13:19:09+0100 Duration: 00:00:02.08, start: 0.000000, bitrate: 926 kb/s Stream #0.0(und): Audio: aac, 44100 Hz, mono, s16, 60 kb/s Stream #0.1(und): Video: h264, yuv420p, 568x320, 863 kb/s, 29.98 fps, 29.97 tbr, 600 tbn, 1200 tbc [libx264 @ 0x24bab70]broken ffmpeg default settings detected [libx264 @ 0x24bab70]use an encoding preset (e.g. -vpre medium) [libx264 @ 0x24bab70]preset usage: -vpre <speed> -vpre <profile> [libx264 @ 0x24bab70]speed presets are listed in x264 --help [libx264 @ 0x24bab70]profile is optional; x264 defaults to high Output #0, mp4, to 'new.mp4': Stream #0.0(und): Video: libx264, yuv420p, 568x320, q=2-31, 200 kb/s, 90k tbn, 29.97 tbc Stream #0.1(und): Audio: libfaac, 44100 Hz, mono, s16, 64 kb/s Stream mapping: Stream #0.1 -> #0.0 Stream #0.0 -> #0.1 Error while opening encoder for output stream #0.0 - maybe incorrect parameters such as bit_rate, rate, width or height
i have tried a lot of thinks to resolve this problem but steel happend.
-8635880 0No, your code is not threadsafe assuming that the window handle (FWnd
) is created in main (GUI) thread. A standard VCL approach is to call all GDI functions in GUI thread, via Synchronize
or Queue
methods of TThread
class.
Check this blog:
Understanding "login failed" (Error 18456) error messages in SQL Server 2005
From the blog:
If the server encounters an error that prevents a login from succeeding, the client will display the following error mesage.
Msg 18456, Level 14, State 1, Server , Line 1 Login failed for user ''
Note that the message is kept fairly nondescript to prevent information disclosure to unauthenticated clients. In particular, the 'State' will always be shown to be '1' regardless of the nature of the problem. To determine the true reason for the failure, the administrator can look in the server's error log where a corresponding entry will be written. An example of an entry is:
2006-02-27 00:02:00.34 Logon Error: 18456, Severity: 14, State: 8. 2006-02-27 00:02:00.34 Logon Login failed for user ''. [CLIENT: ] n
The key to the message is the 'State' which the server will accurately set to reflect the source of the problem. In the example above, State 8 indicates that the authentication failed because the user provided an incorrect password.
The common error states and their descriptions are provided in the following table:
2 and 5 = Invalid userid 6 = Attempt to use a Windows login name with SQL Authentication 7 = Login disabled and password mismatch 8 = Password mismatch 9 = Invalid password 11 and 12 = Valid login but server access failure 13 = SQL Server service paused 18 = Change password required
Hope this helps
-23232832 0One way to do it can be saving largest index, not value. You also need to return some value in case of empty array:
public static int largest(int[] nums3) { if (nums3.length == 0) { return -1; } int largestIndex = 0; for(int i=0; i < nums3.length; i++) { if(nums3[i] > nums3[largestIndex]) { largestIndex = i; } } return largestIndex; }
-6783474 0 try saving those fetched images to the cache, then for each image check if the image already exists in the cache so that it doesn't have to be downloaded again.
-4794870 0 Can I send more than one 'stream' of jpeg ByteArray data in a single URLRequest and output 2 images? Flash AS3 -> PHPI have an AS3 swf which users can upload jpg images to my EC2 instances which sit behind and Elastic Load Balancer. The jpg images are converted into bytearray data and sent using URLLoader.load(URLRequest)
I make 2 calls when uploading, one to upload a large version, then another to upload a thumbnail version. A PHP script to which the bytearray data is uploaded converts this to a file using file_put_contents($destination, $GLOBALS["HTTP_RAW_POST_DATA"])
Is it possible to combine these two requests into a single request which contains both the bytearray data for the large and thumbnail images and 'split' the HTTP_RAW_POST_DATA to create 2 files at the server. This would be better than uploading the bytearray for the large version then using something like ImageMagick to resize the resulting image into a thumbnail which I realise is another option.
any suggestions? cheers
-36929247 0I had this problem also but it is on win10.. After I have tried a lots of different solution from web .. Finally.. it worked to change connection string to fix this problem.. But I changed "Provider=MSDAORA.1"
to "Provider=OraOLEDB.Oracle"
Update
This works but @rdelmar's answer is much more compact.
/////////////////////////////////////////////////////////////////////////////////////////////////
I discovered an answer elsewhere on SO. Basically I had to use NSRange and check via the following method:
[string rangeOfString:@"hello" options:NSCaseInsensitiveSearch].location != NSNotFound
I also had to split my string before doing the check. So in the example words are separated by a period. I called:
NSArray *myArray = [string componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"."]];
and the looped through that array of strings doing the rangeOfString
search. I set a BOOL so that once my string 'hello' was found it stopped searching.
You could use $index to show the number like so:
<div ng-repeat='item in names'> {{item.name}} <br> {{numbers[$index].number}} </div>
However, I would recommend putting the names and numbers in one object as that would be better practice.
-3736215 0There aren't any guaranteed reliable ways to do this. There are a number of methods that work some of the time, but there's no way to be certain. Most of the methods that could have been reliable are routinely blocked by end users due to spam.
The most common way is to send an HTML email with graphics that are loaded from your site (or quite frequently from a third-party tracking agency's site). The graphic would be loaded and the URL would be spiked with a unique ID so you know which recipient has loaded it.
However this only works if the user (a) reads their email in HTML mode, (b) allows it to load graphics, and (c) reads it while they're online.
Some techniques use Javascript to perform a similar task. But that has all the same issues, and can also be stopped by users blocking Javascript in their email.
The best method (ie the most socially acceptable one, and least likely to be blocked) is to provide a link for the user to click on to get more info, which has a unique ID. This of course doesn't tell you what's been read, but it does tell you who's interested in what they've read, which is probably more valuable to know anyway.
The down side of all these methods is the need to give each user a unique ID. This means that each email you send has to be unique, which means quite a big processing overhead for your mail system as it has to re-generate the text for every single user. This is the reason that most people who do this sort of thing delegate the task to a third party tracking agency.
-22552956 0Is it right?.Let's say when user click "Home", the bottom border will appear (under "Home" link).If so, just adds the css (your css) as shown in attached image. (.current_page_item) is the class added for CURRENT (selected) li. If home selected, then border-bottom will appear.
header#top nav .sf-menu li.current_page_item > a, header#top nav .sf-menu li.current-menu-item > a, header#top nav .sf-menu li.current_page_item > a { border-style: solid; border-bottom: thick solid #27CCC0; }
If you want to see the live demo whether it works just like what you want, you can go to "inspect element" and click on 1(in my attached image).Then, add the css to 2(in my attached image).
And, Good Luck..Sorry if this is not the answer.
-21711903 0 Protractor tests fails because model value is emptyI have a sample fiddle that I am trying to test using protractor.
Below are my tests
describe("Fiddle homepage", function() { beforeEach(function() { browser.get('http://fiddle.jshell.net/yfUQ8/9/show'); browser.rootEl = 'div'; }); describe("binding", function() { var inputByModel; beforeEach(function() { inputByModel = element(by.model('model.yourName')); }) // Fail it("should have value Julie1", function() { inputByModel.sendKeys('Julie1'); // browser.waitForAngular(); expect(inputByModel.getText()).to.eventually.equal('Julie1'); }); // Fail it("should have value Julie2", function() { inputByModel.sendKeys('Julie2'); var greeting = element(by.model('model.yourName')); expect(greeting.getText()).to.eventually.equal('Julie2'); }); // Pass it("should have value Julie3", function() { inputByModel.sendKeys('Julie3'); var byBinding = element(by.binding('model.yourName')); expect(byBinding.getText()).to.eventually.equal('Julie'); }); // Fail it("should get value by id and should pass the test", function() { inputByModel.sendKeys('Julie4'); var byID = element(by.id('myinput')); expect(byID.getText()).to.eventually.equal('Julie4'); }) }); });
I am using mocha, chaiAsPromised to run my tests. Can anyone explain why my first two tests are failing?
-23507481 1 python ez_setup on windows XPTrying to install ez_setup.py on windows xp. Python2.7 is installed, and proper path variables are established.
I tried following this, but get the following error below:
copying build\lib\setuptools\command\bdist_rpm.py -> build\bdist.win32\egg\setup tools\command copying build\lib\setuptools\command\bdist_wininst.py -> build\bdist.win32\egg\s etuptools\command copying build\lib\setuptools\command\build_ext.py -> build\bdist.win32\egg\setup tools\command copying build\lib\setuptools\command\build_py.py -> build\bdist.win32\egg\setupt ools\command copying build\lib\setuptools\command\develop.py -> build\bdist.win32\egg\setupto ols\command copying build\lib\setuptools\command\easy_install.py -> build\bdist.win32\egg\se tuptools\command copying build\lib\setuptools\command\egg_info.py -> build\bdist.win32\egg\setupt ools\command copying build\lib\setuptools\command\install.py -> build\bdist.win32\egg\setupto ols\command copying build\lib\setuptools\command\install_egg_info.py -> build\bdist.win32\eg g\setuptools\command copying build\lib\setuptools\command\install_lib.py -> build\bdist.win32\egg\set uptools\command copying build\lib\setuptools\command\install_scripts.py -> build\bdist.win32\egg \setuptools\command copying build\lib\setuptools\command\launcher manifest.xml -> build\bdist.win32\ egg\setuptools\command copying build\lib\setuptools\command\register.py -> build\bdist.win32\egg\setupt ools\command copying build\lib\setuptools\command\rotate.py -> build\bdist.win32\egg\setuptoo ls\command copying build\lib\setuptools\command\saveopts.py -> build\bdist.win32\egg\setupt ools\command copying build\lib\setuptools\command\sdist.py -> build\bdist.win32\egg\setuptool s\command copying build\lib\setuptools\command\setopt.py -> build\bdist.win32\egg\setuptoo ls\command copying build\lib\setuptools\command\test.py -> build\bdist.win32\egg\setuptools \command copying build\lib\setuptools\command\upload_docs.py -> build\bdist.win32\egg\set uptools\command copying build\lib\setuptools\command\__init__.py -> build\bdist.win32\egg\setupt ools\command copying build\lib\setuptools\compat.py -> build\bdist.win32\egg\setuptools copying build\lib\setuptools\depends.py -> build\bdist.win32\egg\setuptools copying build\lib\setuptools\dist.py -> build\bdist.win32\egg\setuptools copying build\lib\setuptools\extension.py -> build\bdist.win32\egg\setuptools copying build\lib\setuptools\gui-32.exe -> build\bdist.win32\egg\setuptools copying build\lib\setuptools\gui-64.exe -> build\bdist.win32\egg\setuptools copying build\lib\setuptools\gui-arm-32.exe -> build\bdist.win32\egg\setuptools copying build\lib\setuptools\gui.exe -> build\bdist.win32\egg\setuptools copying build\lib\setuptools\lib2to3_ex.py -> build\bdist.win32\egg\setuptools copying build\lib\setuptools\package_index.py -> build\bdist.win32\egg\setuptool s copying build\lib\setuptools\py26compat.py -> build\bdist.win32\egg\setuptools copying build\lib\setuptools\py27compat.py -> build\bdist.win32\egg\setuptools copying build\lib\setuptools\py31compat.py -> build\bdist.win32\egg\setuptools copying build\lib\setuptools\sandbox.py -> build\bdist.win32\egg\setuptools copying build\lib\setuptools\script template (dev).py -> build\bdist.win32\egg\s etuptools copying build\lib\setuptools\script template.py -> build\bdist.win32\egg\setupto ols copying build\lib\setuptools\site-patch.py -> build\bdist.win32\egg\setuptools copying build\lib\setuptools\ssl_support.py -> build\bdist.win32\egg\setuptools copying build\lib\setuptools\svn_utils.py -> build\bdist.win32\egg\setuptools creating build\bdist.win32\egg\setuptools\tests copying build\lib\setuptools\tests\doctest.py -> build\bdist.win32\egg\setuptool s\tests copying build\lib\setuptools\tests\environment.py -> build\bdist.win32\egg\setup tools\tests copying build\lib\setuptools\tests\py26compat.py -> build\bdist.win32\egg\setupt ools\tests copying build\lib\setuptools\tests\script-with-bom.py -> build\bdist.win32\egg\s etuptools\tests copying build\lib\setuptools\tests\server.py -> build\bdist.win32\egg\setuptools \tests copying build\lib\setuptools\tests\test_bdist_egg.py -> build\bdist.win32\egg\se tuptools\tests copying build\lib\setuptools\tests\test_build_ext.py -> build\bdist.win32\egg\se tuptools\tests copying build\lib\setuptools\tests\test_develop.py -> build\bdist.win32\egg\setu ptools\tests copying build\lib\setuptools\tests\test_dist_info.py -> build\bdist.win32\egg\se tuptools\tests copying build\lib\setuptools\tests\test_easy_install.py -> build\bdist.win32\egg \setuptools\tests copying build\lib\setuptools\tests\test_egg_info.py -> build\bdist.win32\egg\set uptools\tests copying build\lib\setuptools\tests\test_find_packages.py -> build\bdist.win32\eg g\setuptools\tests copying build\lib\setuptools\tests\test_markerlib.py -> build\bdist.win32\egg\se tuptools\tests copying build\lib\setuptools\tests\test_packageindex.py -> build\bdist.win32\egg \setuptools\tests copying build\lib\setuptools\tests\test_resources.py -> build\bdist.win32\egg\se tuptools\tests copying build\lib\setuptools\tests\test_sandbox.py -> build\bdist.win32\egg\setu ptools\tests copying build\lib\setuptools\tests\test_sdist.py -> build\bdist.win32\egg\setupt ools\tests copying build\lib\setuptools\tests\test_svn.py -> build\bdist.win32\egg\setuptoo ls\tests copying build\lib\setuptools\tests\test_test.py -> build\bdist.win32\egg\setupto ols\tests copying build\lib\setuptools\tests\test_upload_docs.py -> build\bdist.win32\egg\ setuptools\tests copying build\lib\setuptools\tests\__init__.py -> build\bdist.win32\egg\setuptoo ls\tests copying build\lib\setuptools\version.py -> build\bdist.win32\egg\setuptools copying build\lib\setuptools\__init__.py -> build\bdist.win32\egg\setuptools creating build\bdist.win32\egg\_markerlib copying build\lib\_markerlib\markers.py -> build\bdist.win32\egg\_markerlib copying build\lib\_markerlib\__init__.py -> build\bdist.win32\egg\_markerlib byte-compiling build\bdist.win32\egg\easy_install.py to easy_install.pyc byte-compiling build\bdist.win32\egg\pkg_resources.py to pkg_resources.pyc byte-compiling build\bdist.win32\egg\setuptools\archive_util.py to archive_util. pyc byte-compiling build\bdist.win32\egg\setuptools\command\alias.py to alias.pyc byte-compiling build\bdist.win32\egg\setuptools\command\bdist_egg.py to bdist_eg g.pyc byte-compiling build\bdist.win32\egg\setuptools\command\bdist_rpm.py to bdist_rp m.pyc byte-compiling build\bdist.win32\egg\setuptools\command\bdist_wininst.py to bdis t_wininst.pyc byte-compiling build\bdist.win32\egg\setuptools\command\build_ext.py to build_ex t.pyc byte-compiling build\bdist.win32\egg\setuptools\command\build_py.py to build_py. pyc byte-compiling build\bdist.win32\egg\setuptools\command\develop.py to develop.py c byte-compiling build\bdist.win32\egg\setuptools\command\easy_install.py to easy_ install.pyc byte-compiling build\bdist.win32\egg\setuptools\command\egg_info.py to egg_info. pyc byte-compiling build\bdist.win32\egg\setuptools\command\install.py to install.py c byte-compiling build\bdist.win32\egg\setuptools\command\install_egg_info.py to i nstall_egg_info.pyc byte-compiling build\bdist.win32\egg\setuptools\command\install_lib.py to instal l_lib.pyc byte-compiling build\bdist.win32\egg\setuptools\command\install_scripts.py to in stall_scripts.pyc byte-compiling build\bdist.win32\egg\setuptools\command\register.py to register. pyc byte-compiling build\bdist.win32\egg\setuptools\command\rotate.py to rotate.pyc byte-compiling build\bdist.win32\egg\setuptools\command\saveopts.py to saveopts. pyc byte-compiling build\bdist.win32\egg\setuptools\command\sdist.py to sdist.pyc byte-compiling build\bdist.win32\egg\setuptools\command\setopt.py to setopt.pyc byte-compiling build\bdist.win32\egg\setuptools\command\test.py to test.pyc byte-compiling build\bdist.win32\egg\setuptools\command\upload_docs.py to upload _docs.pyc byte-compiling build\bdist.win32\egg\setuptools\command\__init__.py to __init__. pyc byte-compiling build\bdist.win32\egg\setuptools\compat.py to compat.pyc byte-compiling build\bdist.win32\egg\setuptools\depends.py to depends.pyc byte-compiling build\bdist.win32\egg\setuptools\dist.py to dist.pyc byte-compiling build\bdist.win32\egg\setuptools\extension.py to extension.pyc byte-compiling build\bdist.win32\egg\setuptools\lib2to3_ex.py to lib2to3_ex.pyc byte-compiling build\bdist.win32\egg\setuptools\package_index.py to package_inde x.pyc byte-compiling build\bdist.win32\egg\setuptools\py26compat.py to py26compat.pyc byte-compiling build\bdist.win32\egg\setuptools\py27compat.py to py27compat.pyc byte-compiling build\bdist.win32\egg\setuptools\py31compat.py to py31compat.pyc byte-compiling build\bdist.win32\egg\setuptools\sandbox.py to sandbox.pyc byte-compiling build\bdist.win32\egg\setuptools\script template (dev).py to scri pt template (dev).pyc byte-compiling build\bdist.win32\egg\setuptools\script template.py to script tem plate.pyc byte-compiling build\bdist.win32\egg\setuptools\site-patch.py to site-patch.pyc byte-compiling build\bdist.win32\egg\setuptools\ssl_support.py to ssl_support.py c byte-compiling build\bdist.win32\egg\setuptools\svn_utils.py to svn_utils.pyc byte-compiling build\bdist.win32\egg\setuptools\tests\doctest.py to doctest.pyc byte-compiling build\bdist.win32\egg\setuptools\tests\environment.py to environm ent.pyc byte-compiling build\bdist.win32\egg\setuptools\tests\py26compat.py to py26compa t.pyc byte-compiling build\bdist.win32\egg\setuptools\tests\script-with-bom.py to scri pt-with-bom.pyc byte-compiling build\bdist.win32\egg\setuptools\tests\server.py to server.pyc byte-compiling build\bdist.win32\egg\setuptools\tests\test_bdist_egg.py to test_ bdist_egg.pyc byte-compiling build\bdist.win32\egg\setuptools\tests\test_build_ext.py to test_ build_ext.pyc byte-compiling build\bdist.win32\egg\setuptools\tests\test_develop.py to test_de velop.pyc byte-compiling build\bdist.win32\egg\setuptools\tests\test_dist_info.py to test_ dist_info.pyc byte-compiling build\bdist.win32\egg\setuptools\tests\test_easy_install.py to te st_easy_install.pyc byte-compiling build\bdist.win32\egg\setuptools\tests\test_egg_info.py to test_e gg_info.pyc byte-compiling build\bdist.win32\egg\setuptools\tests\test_find_packages.py to t est_find_packages.pyc byte-compiling build\bdist.win32\egg\setuptools\tests\test_markerlib.py to test_ markerlib.pyc byte-compiling build\bdist.win32\egg\setuptools\tests\test_packageindex.py to te st_packageindex.pyc byte-compiling build\bdist.win32\egg\setuptools\tests\test_resources.py to test_ resources.pyc byte-compiling build\bdist.win32\egg\setuptools\tests\test_sandbox.py to test_sa ndbox.pyc byte-compiling build\bdist.win32\egg\setuptools\tests\test_sdist.py to test_sdis t.pyc byte-compiling build\bdist.win32\egg\setuptools\tests\test_svn.py to test_svn.py c byte-compiling build\bdist.win32\egg\setuptools\tests\test_test.py to test_test. pyc byte-compiling build\bdist.win32\egg\setuptools\tests\test_upload_docs.py to tes t_upload_docs.pyc byte-compiling build\bdist.win32\egg\setuptools\tests\__init__.py to __init__.py c byte-compiling build\bdist.win32\egg\setuptools\version.py to version.pyc byte-compiling build\bdist.win32\egg\setuptools\__init__.py to __init__.pyc byte-compiling build\bdist.win32\egg\_markerlib\markers.py to markers.pyc byte-compiling build\bdist.win32\egg\_markerlib\__init__.py to __init__.pyc creating build\bdist.win32\egg\EGG-INFO copying setuptools.egg-info\PKG-INFO -> build\bdist.win32\egg\EGG-INFO copying setuptools.egg-info\SOURCES.txt -> build\bdist.win32\egg\EGG-INFO copying setuptools.egg-info\dependency_links.txt -> build\bdist.win32\egg\EGG-IN FO copying setuptools.egg-info\entry_points.txt -> build\bdist.win32\egg\EGG-INFO copying setuptools.egg-info\requires.txt -> build\bdist.win32\egg\EGG-INFO copying setuptools.egg-info\top_level.txt -> build\bdist.win32\egg\EGG-INFO copying setuptools.egg-info\zip-safe -> build\bdist.win32\egg\EGG-INFO creating dist creating 'dist\setuptools-3.5.1-py2.7.egg' and adding 'build\bdist.win32\egg' to it removing 'build\bdist.win32\egg' (and everything under it) Processing setuptools-3.5.1-py2.7.egg Removing c:\python27\lib\site-packages\setuptools-3.5.1-py2.7.egg Copying setuptools-3.5.1-py2.7.egg to c:\python27\lib\site-packages setuptools 3.5.1 is already the active version in easy-install.pth Installing easy_install-script.py script to C:\Python27\Scripts Installing easy_install.exe script to C:\Python27\Scripts Installing easy_install.exe.manifest script to C:\Python27\Scripts Installing easy_install-2.7-script.py script to C:\Python27\Scripts Installing easy_install-2.7.exe script to C:\Python27\Scripts Installing easy_install-2.7.exe.manifest script to C:\Python27\Scripts Installed c:\python27\lib\site-packages\setuptools-3.5.1-py2.7.egg Processing dependencies for setuptools==3.5.1 Traceback (most recent call last): File "setup.py", line 217, in <module> dist = setuptools.setup(**setup_params) File "C:\Python27\lib\distutils\core.py", line 152, in setup dist.run_commands() File "C:\Python27\lib\distutils\dist.py", line 953, in run_commands self.run_command(cmd) File "C:\Python27\lib\distutils\dist.py", line 972, in run_command cmd_obj.run() File "c:\docume~1\jason\locals~1\temp\tmpqpn4qe\setuptools-3.5.1\setuptools\co mmand\install.py", line 65, in run self.do_egg_install() File "c:\docume~1\jason\locals~1\temp\tmpqpn4qe\setuptools-3.5.1\setuptools\co mmand\install.py", line 115, in do_egg_install cmd.run() File "c:\docume~1\jason\locals~1\temp\tmpqpn4qe\setuptools-3.5.1\setuptools\co mmand\easy_install.py", line 360, in run self.easy_install(spec, not self.no_deps) File "c:\docume~1\jason\locals~1\temp\tmpqpn4qe\setuptools-3.5.1\setuptools\co mmand\easy_install.py", line 576, in easy_install return self.install_item(None, spec, tmpdir, deps, True) File "c:\docume~1\jason\locals~1\temp\tmpqpn4qe\setuptools-3.5.1\setuptools\co mmand\easy_install.py", line 627, in install_item self.process_distribution(spec, dist, deps) File "c:\docume~1\jason\locals~1\temp\tmpqpn4qe\setuptools-3.5.1\setuptools\co mmand\easy_install.py", line 673, in process_distribution [requirement], self.local_index, self.easy_install File "c:\docume~1\jason\locals~1\temp\tmpqpn4qe\setuptools-3.5.1\pkg_resources .py", line 633, in resolve requirements.extend(dist.requires(req.extras)[::-1]) File "c:\docume~1\jason\locals~1\temp\tmpqpn4qe\setuptools-3.5.1\pkg_resources .py", line 2291, in requires dm = self._dep_map File "c:\docume~1\jason\locals~1\temp\tmpqpn4qe\setuptools-3.5.1\pkg_resources .py", line 2277, in _dep_map for extra, reqs in split_sections(self._get_metadata(name)): File "c:\docume~1\jason\locals~1\temp\tmpqpn4qe\setuptools-3.5.1\pkg_resources .py", line 2715, in split_sections for line in yield_lines(s): File "c:\docume~1\jason\locals~1\temp\tmpqpn4qe\setuptools-3.5.1\pkg_resources .py", line 1989, in yield_lines for ss in strs: File "c:\docume~1\jason\locals~1\temp\tmpqpn4qe\setuptools-3.5.1\pkg_resources .py", line 2305, in _get_metadata for line in self.get_metadata_lines(name): File "c:\docume~1\jason\locals~1\temp\tmpqpn4qe\setuptools-3.5.1\pkg_resources .py", line 1369, in get_metadata_lines return yield_lines(self.get_metadata(name)) File "c:\docume~1\jason\locals~1\temp\tmpqpn4qe\setuptools-3.5.1\pkg_resources .py", line 1361, in get_metadata return self._get(self._fn(self.egg_info, name)) File "c:\docume~1\jason\locals~1\temp\tmpqpn4qe\setuptools-3.5.1\pkg_resources .py", line 1425, in _get return self.loader.get_data(path) zipimport.ZipImportError: bad local file header in c:\python27\lib\site-packages \setuptools-3.5.1-py2.7.egg Something went wrong during the installation. See the error message above. C:\Python27>python ez_setup.py install
-2416675 0 EDIT: added some details about explain().
Some general introduction: The Lucene Highlighter is meant to find text snippets from a hit document, and to highlight tokens matching the query.
Explanation expl = searcher.explain(query, docId);
String asText = expl.toString();
String asHtml = expl.toHtml();
docId is the raw document id from the search results.
Only if you do need the snippets and/or highlights, you should use the Highlighter. If you still want to use the highlighter, follow Nicholas Hrychan's advice. Beware, though, as he describes the Lucene 2.4.1 API - If you use a more advanced version, you should use "QueryScorer" where he says "SpanScorer" .
-11894358 0 Implementing iAd BannerI just published an application on the App Store with an iAd banner. When I downloaded it to check for the advertisement, I just saw a plain white horizontal rectangle even though it says "Live: This app is receiving live ads." in development.
adView = [[ADBannerView alloc] initWithFrame:CGRectZero]; [adView setCurrentContentSizeIdentifier:ADBannerContentSizeIdentifierLandscape]; [adView setDelegate:self]; [self.view addSubview:adView]; [self.view bringSubviewToFront:adView]; - (BOOL)bannerViewActionShouldBegin:(ADBannerView *)banner willLeaveApplication:(BOOL)willLeave { return YES; }
Everything in my performance chart is zero, except for the 715 requests. What does this mean?
Also, is it possible for iAd to determine the user's location so that apple can put ads from local companies? For example, the user is in Japan, will iAd only show ads from Japan?
-2996065 0JavaScript does garbage collection automatically for you.
It might free it right away or it might wait when the moment is best. This is up to the JavaScript implementation.
So no, it won't cause a memory leak.
-32926966 0 PHP rename() not workingI am trying to rename a duplicate file name upon upload of a new file with the same name. Everything is working great except for that I am getting an error:
<b>Warning</b>: rename(./uploads/484360_438365932885330_1444746206_n.jpeg,): No such file or directory in <b>/home/unisharesadmin/public_html/wp-content/themes/blankslate/check_duplicate_img.php</b> on line <b>36</b><br />
Despite confirming that the directory exists and that the file and directory are both writeable, PHP is still throwing this error. I have consulted countless threads on here already and none of them seem to help, as I cannot find any path or string error with my file path.
Thank you for any help you can provide!
Cheers Colin
Code:
<? require_once('../../../wp-config.php'); function RandomString($length = 10) { $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $charactersLength = strlen($characters); $randomString = ''; for ($i = 0; $i < $length; $i++) { $randomString .= $characters[rand(0, $charactersLength - 1)]; } return $randomString; } $this_img = $_REQUEST['filename']; $path = './uploads/' . $this_img; $img_array = explode(".", $this_img); $new_img = RandomString() . '.' . $img_array[sizeof($img_array)-1]; $new_path = './uploads/' . $new_img; if (file_exists($path)) { query_posts('posts_per_page=-1'); while(have_posts()) { the_post(); if( strpos(get_post_meta(get_the_id(), 'imgurl1')[0], $this_img) !== false ) { //echo "this posts url1 matches, so update the existing files name and the posts refrence to it"; echo is_writeable("./uploads"); rename($path, $newpath); //echo update_post_meta(get_the_id(), 'imgurl1', get_template_directory_uri() . '/uploads/' . $new_img); } else if( strpos(get_post_meta(get_the_id(), 'imgurl2')[0], $this_img) !== false ) //this posts url2 matches { echo "this posts url2 matches, so update the existing files name and the posts refrence to it"; //rename($path, $newpath); //echo update_post_meta(get_the_id(), 'imgurl2', get_template_directory_uri() . '/uploads/' . $new_img); } } } else { echo 0; } ?>
-32861574 0 How to use file_get_contents on loop? I'm trying to use file_get_contents on loop, in order to fetch JSON string from an URL continuously (every second). And i need to store the result into a javascript variable. Here was my approach, but i didn't get any result from this. My page showed me nothing but endless loading.
<?php set_time_limit(0); while(true) { $jsonContent=file_get_contents('http://megarkarsa.com/gpsjson.php'); echo $jsonContent; sleep(10); } ?>
And here my javascript code.
setInterval(function(){ var jsonUpdPostData = <?php echo $jsonContent; ?>; }, 100);
What should i do to make it work? Any suggestion will be appreciated.
-847428 0You should use the following syntax:
<ul> $orders: {order| <li>Order $order.OrderId$</li> }$ </ul>
The documentation about this feature is really hard to find, I found some info here (search for the pipe symbol |).
-8183890 0No, only tokenizer=porter
When I specify tokenizer=icu, I get "android.database.sqlite.SQLiteException: unknown tokenizer: icu"
Also, this link hints that if Android didn't compile it in by default, it will not be available http://sqlite.phxsoftware.com/forums/t/2349.aspx
-20607942 0Some of my apps in that project were missing the "application-descriptor.xml" file for unknown reason... I've deleted the folders for those apps, then the migration succeeded.
-39330493 0Can you try this:
RewriteEngine On RewriteCond %{THE_REQUEST} "^GET\s(.+)\s(.+)\sHTTP/1.1" RewriteRule ^ "%1\%20%2" [PT]
Tested on Apache 2.4.6.
-10765331 0Apparently it is the way it should be done. There's no need to do it any other way if the desired outcome is as described.
-11010890 0Your order appears to be alphabetical, but since you didn't say this, I'm assuming this isn't a reliable expectation.
How's this?
http://www.xmlplayground.com/cMOOBF
If indeed the order IS is reliably alphabetical, it would be better to first sort your nodes rather than use a complex predicate as I have.
-32321352 0 How to set CasperJS page options from within a test in test environment?I run most of my CasperJS tests with the test
command as well as the --ssl-protocol=any
and --ignore-ssl-errors=true
flags.
Is there a way that I can add those 2 flags to the tests themselves if they're in the test environment? I know you can set page options if you use the casper module like var casper = require('casper').create({
, but that's not how my tests are set up.
I also know you can do stuff like
casper.options.verbose = true; casper.options.logLevel = "debug";
...but casper.options.ignoreSslProtocol=true
doesn't seem to work.
here's part of my login test --
var config = require('../../config'), x = require('casper').selectXPath; casper.test.comment('basic login test!'); casper.start(config.base_url); casper.test.begin('test basic login functionality', function (test) { casper.then(function() { this.click('.js-flip_box'); test.info('logging in'); this.fill('#login_form', { 'email': config.email, 'password': config.password }, true); }); casper.then(function () { test.assertVisible ('.home_bar', 'nav bar visible'); }); casper.run(function() { test.done(); }); });
...which I run with casperjs --ssl-protocol=any --ignore-ssl-errors=true test login.js
(a mouthful)
am I doomed?
-21142228 0You could use
socketl = new ServerSocket(port, 0);
or even
socketl = new ServerSocket(port);
-32507256 0 parse.com, where does parseSendRequest() show up on ParseIot dashboard I am writing a small sensor send Request from 'C' on Raspberry Pi to the parseIoT platform from this link
https://www.parse.com/apps/quickstart#embedded/raspberrypi
Where does this show up on the Parse Dashboard ? I was hoping to see it in Data Modified Sample code from main.c is :
strcpy (data , " '{ \'currentTemperature\': 175.0 }'");
parseSendRequest(client, "POST", "/1/classes/TemperatureReading", data, NULL);
-27280127 0File.GetCreationTime(pstFileFolder)
will return you CreationDate
for folder, and you will get the same value back for all files. Instead use:
string fileCreatedDatey = File.GetCreationTime(file).Date.ToString("yyyy-MM-dd");
-5821293 0 Message.Show is not working when webpage is published I created a ASP.NET project in which I am using MessageBox.Show to show the user if there is an error or something else. But when I published it, it is giving me this err:
Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation. Specify the ServiceNotification or DefaultDesktopOnly style to display a notification from a service application.
Dont know what it means? What the turnaround of it? Thanks!
-18648227 0You are dumping list of strings so json.dumps does exactly what you are asking for. Rather ugly solution for your problem could be something like below.
def split_and_convert(s): bits = s[1:-1].split(',') return ( int(bits[0]), bits[1], float(bits[2]), float(bits[3]), float(bits[4]), float(bits[5]) ) data_to_dump = [split_and_convert(s) for s in data] json.dumps(data_to_dump)
-15115472 0 Enable mod_rewrite and .htaccess through httpd.conf
and then put this code in your .htaccess
under DOCUMENT_ROOT
directory:
Options +FollowSymLinks -MultiViews # Turn mod_rewrite on RewriteEngine On RewriteBase / RewriteRule ^(folder)/([^.]+)\.asp$ /$1/$2.php [L,NC]
-12017187 0 *tr
is invalid XPath as you're mixing the wildcard with a literal node name.
You need just *
, i.e. *[starts-with...
I have downloaded "apache-log4j-2.0-beta9-bin" from http://logging.apache.org/log4j/ and extaracted it and added to my project. Then I wrote a configuration properties file in my project as below
# Define the root logger with appender file log = X:\logs log4j.rootLogger = DEBUG, FILE # Define the file appender log4j.appender.FILE=org.apache.log4j.FileAppender log4j.appender.FILE.File=${log}/log.out # Define the layout for file appender log4j.appender.FILE.layout=org.apache.log4j.PatternLayout log4j.appender.FILE.layout.conversionPattern=%m%n
and I wrote sample program to test it, the sample program is shown below.
public class Log4jExample { static Logger log = Logger.getLogger(Log4jExample.class.getName()); public static void main(String[] args)throws IOException{ log.debug("Hello this is an debug message"); log.info("Hello this is an info message"); } }
While executing it am receiving this error, please advice.
java.lang.NoClassDefFoundError: org/apache/flume/Event at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:186) at org.apache.logging.log4j.core.config.plugins.PluginManager.decode(PluginManager.java:241) at org.apache.logging.log4j.core.config.plugins.PluginManager.collectPlugins(PluginManager.java:152) at org.apache.logging.log4j.core.config.plugins.PluginManager.collectPlugins(PluginManager.java:130) at org.apache.logging.log4j.core.pattern.PatternParser.<init>(PatternParser.java:116) at org.apache.logging.log4j.core.pattern.PatternParser.<init>(PatternParser.java:102) at org.apache.logging.log4j.core.layout.PatternLayout.createPatternParser(PatternLayout.java:183) at org.apache.logging.log4j.core.layout.PatternLayout.<init>(PatternLayout.java:115) at org.apache.logging.log4j.core.layout.PatternLayout.createLayout(PatternLayout.java:219) at org.apache.logging.log4j.core.config.DefaultConfiguration.<init>(DefaultConfiguration.java:51) at org.apache.logging.log4j.core.LoggerContext.<init>(LoggerContext.java:63) at org.apache.logging.log4j.core.selector.ClassLoaderContextSelector.locateContext(ClassLoaderContextSelector.java:217) at org.apache.logging.log4j.core.selector.ClassLoaderContextSelector.getContext(ClassLoaderContextSelector.java:114) at org.apache.logging.log4j.core.selector.ClassLoaderContextSelector.getContext(ClassLoaderContextSelector.java:81) at org.apache.logging.log4j.core.impl.Log4jContextFactory.getContext(Log4jContextFactory.java:83) at org.apache.logging.log4j.core.impl.Log4jContextFactory.getContext(Log4jContextFactory.java:34) at org.apache.logging.log4j.LogManager.getContext(LogManager.java:200) at org.apache.log4j.Logger$PrivateManager.getContext(Logger.java:61) at org.apache.log4j.Logger.getLogger(Logger.java:39) at log4j.Log4jExample.<clinit>(Log4jExample.java:16) Caused by: java.lang.ClassNotFoundException: org.apache.flume.Event at java.net.URLClassLoader$1.run(URLClassLoader.java:366) at java.net.URLClassLoader$1.run(URLClassLoader.java:355) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:354) at java.lang.ClassLoader.loadClass(ClassLoader.java:423) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) at java.lang.ClassLoader.loadClass(ClassLoader.java:356) ... 21 more
Exception in thread "main" Java Result: 1
-3404103 0Another version of my solution with ranges:
List<int> getUniqueColors(int amount) { final int lowerLimit = 0x10; final int upperLimit = 0xE0; final int colorStep = (upperLimit-lowerLimit)/Math.pow(amount,1f/3); final List<int> colors = new ArrayList<int>(amount); for (int R = lowerLimit;R < upperLimit; R+=colorStep) for (int G = lowerLimit;G < upperLimit; G+=colorStep) for (int B = lowerLimit;B < upperLimit; B+=colorStep) { if (colors.size() >= amount) { //The calculated step is not very precise, so this safeguard is appropriate return colors; } else { int color = (R<<16)+(G<<8)+(B); colors.add(color); } } return colors; }
This one is more advance as it generates the colors that differ from each other as much as possible (something like @aiiobe did).
Generally we split the range to 3 subranges of red green and blue, calculate how many steps do we need to iterate each of them (by applying a pow(range,1f/3)) and iterate them.
Given the number 3 for example, it will generate 0x0000B1, 0x00B100, 0x00B1B1
. For number 10 it will be: 0x000076, 0x0000EC, 0x007600, 0x007676, 0x0076EC, 0x00EC00, 0x00EC76, 0x00ECEC, 0x760000, 0x760076
This might sound silly but do you have gems.rubyforge.org in your remote sources?
-10845776 0I've never used SWT_AWT
but I use JFreeChart with SWT (using ChartComposite), and I can capture a chart into an image with the code below. It may help you :
ChartComposite chartComposite = ...; Image image = new Image(chartComposite.getDisplay(), chartComposite.getBounds()); GC gc = new GC(image); chartComposite.print(gc); gc.dispose();
-15207852 0 Take a look at these UIView methods. You subclass can override these methods and do what you require.
touchesBegan:withEvent:, touchesMoved:withEvent:, touchesEnded:withEvent:, touchesCancelled:withEvent:
I got stuck with a problem which seems to have been solved here. I want to use order list as it's in an example here. But it doesn't work at all. I have nested <p:ajax>
in order list like in an example.
Namely, I have got an error:
javax.servlet.ServletException: /resources/abc/rankingAnswer.xhtml @21,85
<p:ajax>
Unable to attach behavior to non-ClientBehaviorHolder parent
My Primefaces config in pom.xml is
<!-- prime faces --> <primefaces.version>5.1</primefaces.version> <primefaces.themes.version>1.0.10</primefaces.themes.version>
My view is
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:composite="http://java.sun.com/jsf/composite" xmlns:p="http://primefaces.org/ui" xmlns:f="http://java.sun.com/jsf/core" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html"> <composite:interface> <composite:attribute name="question" /> </composite:interface> <composite:implementation> <ui:decorate template="answerDecorator.xhtml"> <ui:define name="component"> <p:orderList value="#{cc.attrs.question.possibleAnswers}" var="answer" itemLabel="#{answer.text}" itemValue="#{answer}" controlsLocation="left" editable="true" > <f:facet name="caption">#{msg['survey.default.makeOrder']}</f:facet> <p:ajax event="reorder" listener="#{cc.attrs.question.onReorder}" /> <p:column> <h:outputText value="#{answer.text}" /> </p:column> </p:orderList> </ui:define> </ui:decorate> </composite:implementation> </html>
My model is
public class RankingQuestionDTO extends AbstractQuestionDTO implements Serializable { private ArrayList<RankingAnswerDTO> possibleAnswers; private boolean randomizeAnswers; private String text; public RankingQuestionDTO() { super(QuestionType.RANKING); this.text = MessageUtils.getBundle("survey.default.text"); this.possibleAnswers = new ArrayList<>(); this.possibleAnswers.add(new RankingAnswerDTO(MessageUtils.getBundle("survey.default.text"))); this.possibleAnswers.add(new RankingAnswerDTO(MessageUtils.getBundle("survey.default.text"))); this.randomizeAnswers = true; } public void onSelect(SelectEvent event) { System.out.print(event.getObject().toString()); } public void onUnselect(UnselectEvent event) { System.out.print(event.getObject().toString()); } public void onReorder() { } public void addEmptyPossibleAnswer() { this.possibleAnswers.add(new RankingAnswerDTO(MessageUtils.getBundle("survey.default.text"))); } public ArrayList<RankingAnswerDTO> getPossibleAnswers() { return possibleAnswers; } public String getText() { return text; } public void setPossibleAnswers(ArrayList<RankingAnswerDTO> possibleAnswers) { this.possibleAnswers = possibleAnswers; } public void setRandomizeAnswers(boolean randomizeAnswers) { this.randomizeAnswers = randomizeAnswers; } public boolean getRandomizeAnswers() { return randomizeAnswers; } public void setText(String text) { this.text = text; } }
-7089665 0 For the disabled attribute I think it's the presence of the attribute that disables the element regardless of its value.
It guess one of the reasons could be to allow more values than just yes/no in the future. For instance, instead of visible=true/false, you can have visibility=visible/hidden/collapsed
-21205124 0 Log4j not workingI using common logging and jboss eap 6.2 in java application, log file is creating but empty and hibernate log also not working.
This is my jboss-deployment-structure.xml
<jboss-deployment-structure> <deployment> <exclusions> <module name="org.apache.commons.logging"/> <module name="org.apache.log4j"/> </exclusions> </deployment> <sub-deployment name="abc.war"> <exclusions> <module name="org.apache.log4j"/> <module name="org.apache.commons.logging"/> </exclusions> </sub-deployment> </jboss-deployment-structure>
and this is my log4j.properties
log4j.rootLogger=DEBUG, FILE log4j.appender.FILE=org.apache.log4j.RollingFileAppender log4j.appender.FILE.File=c\:\\log\\eSocietySQLLog.log log4j.appender.FILE.ImmediateFlush=true log4j.appender.FILE.Threshold=debug log4j.appender.FILE.Append=true log4j.appender.FILE.MaxFileSize=10MB log4j.appender.FILE.MaxBackupIndex=5 log4j.appender.FILE.layout=org.apache.log4j.PatternLayout log4j.appender.FILE.layout.ConversionPattern=%d{HH:mm:ss,SSS} %-5p %c %n%m%C log4j.appender.FILE.DatePattern='.' yyyy-MM-dd-a
and add JAVA_OPTS="$JAVA_OPTS -Dorg.jboss.as.logging.per-deployment=false" in standalone.conf of jboss eap 6.2.
-19926211 0 math.net DenseVectors vs DenseMatrix 1xn | nx1This is really simple stuff but, as I am a noob with math.net, I may need to be pointed in the right direction:
let a = new DenseVector([| 5.0; 2.0; 3.0; |]) let m = new DenseMatrix(3, 3, 1.0) let r = a * m let r2 = m * a
results in:
> r;; val it : DenseVector = seq [10.0; 10.0; 10.0] > r2;; val it : DenseVector = seq [10.0; 10.0; 10.0]
Matrix-Vector multiplication takes too much liberty here. I need to enforce proper dimensionality checks. Should I just work with DenseMatrix
, creating 1xn, nx1 matrices? This basically makes Vectors
and DenseVectors
redundant in my case.
Okay, I solved my problem and would like to answer my own question. I figured it would be better for the other users here.
First, get the file here: http://www.JSON.org/json_parse.js
var geodata = json_parse("{{geodata|escapejs}}");
I just used escapejs: http://docs.djangoproject.com/en/dev/ref/templates/builtins/#escapejs
EDIT: Thanks to Ignacio Vazquez-Abrams. It was him that helped me in #python Freenode. Should have credited him when I made this post. I didn't know he was in Stackoverflow.
-15338118 0As KD suggested, I would add name attributes to all the form elements.
<input type="text" name="length" value="8" id="length_field"> <input type="checkbox" id="includeLetters" checked>
etc...
but I would let the model binder give us strongly typed values by specifying the argument type.
[HttpPost] public ActionResult PasswordGenerator(int length, bool includeLetters, etc...) { }
If the number of arguments exceeds what you feel comfortable with, simply create an object with [properties that match your form field. IE:
public class PasswordGeneratorArguments { public int Length {get;set} public bool IncludeLetters {get;set} etc... }
and use that as the argument
[HttpPost] public ActionResult PasswordGenerator(PasswordGeneratorArguments model) { }
-26523337 0 In arch/arm/config.mk there is:
CONFIG_STANDALONE_LOAD_ADDR = 0xc100000
In file examples/standalone/.hello_world.cmd
cmd_examples/standalone/hello_world := arm-linux-gnueabi-ld.bfd -g -Ttext 0xc100000 -o examples/standalone/hello_world -e hello_world examples/standalone/hello_world.o examples/standalone/libstubs.o -L /usr/lib/gcc-cross/arm-linux-gnueabi/4.7 -lgcc
Here the -Ttext is 0xc100000. That means hello_world entry address is 0xc100000. So the hello.bin must be loaded to memory address 0xc100000.
-27588019 0Manually adding all repositories will help:
{ "repositories": [ { "type": "package", "package": { "name": "fuel/auth", "type": "fuel-package", "version": "1.7.2", "dist": { "url": "https://github.com/fuel/auth/archive/1.7/master.zip", "type": "zip" }, "source": { "url": "https://github.com/fuel/auth.git", "type": "git", "reference": "1.8/develop" } } }, { "type": "package", "package": { "name": "fuel/email", "type": "fuel-package", "version": "1.7.2", "dist": { "url": "https://github.com/fuel/email/archive/1.7/master.zip", "type": "zip" }, "source": { "url": "https://github.com/fuel/email.git", "type": "git", "reference": "1.8/develop" } } }, { "type": "package", "package": { "name": "fuel/oil", "type": "fuel-package", "version": "1.7.2", "dist": { "url": "https://github.com/fuel/oil/archive/1.7/master.zip", "type": "zip" }, "source": { "url": "https://github.com/fuel/oil.git", "type": "git", "reference": "1.8/develop" } } }, { "type": "package", "package": { "name": "fuel/orm", "type": "fuel-package", "version": "1.7.2", "dist": { "url": "https://github.com/fuel/orm/archive/1.7/master.zip", "type": "zip" }, "source": { "url": "https://github.com/fuel/orm.git", "type": "git", "reference": "1.8/develop" } } }, { "type": "package", "package": { "name": "fuel/parser", "type": "fuel-package", "version": "1.7.2", "dist": { "url": "https://github.com/fuel/parser/archive/1.7/master.zip", "type": "zip" }, "source": { "url": "https://github.com/fuel/parser.git", "type": "git", "reference": "1.8/develop" } } }, { "type": "package", "package": { "name": "fuel/core", "type": "fuel-package", "version": "1.7.2", "dist": { "url": "https://github.com/fuel/core/archive/1.7/master.zip", "type": "zip" }, "source": { "url": "https://github.com/fuel/core.git", "type": "git", "reference": "1.8/develop" } } }, { "type": "package", "package": { "name": "fuel/docs", "type": "fuel-package", "version": "1.7.2", "dist": { "url": "https://github.com/fuel/docs/archive/1.7/master.zip", "type": "zip" }, "source": { "url": "https://github.com/fuel/docs.git", "type": "git", "reference": "1.8/develop" } } } ], "require": { "fuel/fuel": "dev-1.7/master" }
}
-651046 0It's probably not the case - but by any chance are you using different compiler versions (even minor version differences) while compiling the two source bases?
-34952970 0 "Another object on this page already uses ID 'XXXXXXX'Not related to: Another object on this page already uses ID 'XXXXXXX'
I've got a jQuery Multiselect Listbox
control on my page:
jQuery(document).ready(function () { jQuery(function () { jQuery("#UCStyle1 select").multiselect({ header: true, height: 175, minWidth: 240, size: 3, classes: '', checkAllText: 'Check all', uncheckAllText: 'Uncheck all', noneSelectedText: '0 Selected', selectedText: '# selected', selectedList: 0, show: null, hide: null, autoOpen: false, multiple: true, position: {}, appendTo: "body" }); });
It's referenced a bunch of times in div tags like this:
<tr> <td> Looking for: </td> <td colspan="3"> <div id="UCStyle1"> <asp:ListBox ID="MatchGender" SelectionMode="Multiple" runat="server"> </asp:ListBox> </div> </td> </tr> <tr> <td> State: </td> <td colspan="3"> <div id="UCStyle1"> <asp:ListBox ID="sState" SelectionMode="Multiple" runat="server"> </asp:ListBox> </div> </td> </tr>
So, they need to reference that jQuery, but they're different controls.
I'm getting the warning:
Another object on this page already uses ID 'ucstyle1'
Multiple times.
Any idea how I can clean this up so that I don't get that warning? I think it's causing the page to look completely wonky on IE, but Firefox doesn't seem to care about it.
-38855056 0Just to elaborate on Injecteers answer actually the data:{} is what is posting information to it so may clash with params:[..]} :
<g:javascript> function go(){ var javaScriptVariable='123' $.ajax({ url:'${g.createLink( controller:'my', action:'go')}', data:{ param1: "${params.params1}", param2: javascriptVariable } }); } </g:javascript>
data:{}
can also be data: $('form').serialize();
where serialize function grabs all the form elements and serializes it for you as params to be passed back.
I think you can use very fast solution with numpy.where
:
homework2['ADJ_HDI'] = np.where(homework2['HDI'] > .5, homework2['HDI'], 0)
Timings:
import pandas as pd import numpy as np homework2 = pd.DataFrame({"A": [10, 8, 1, 1, 2, 2, 2], "HDI": [25, np.nan, 2.3, 2.4, 1.2, 0.3, 5.7]}) #for test 7k uncomment row bellow #homework2 = pd.concat([homework2]*1000).reset_index(drop=True) print homework2 h = homework2.copy() h1 = homework2.copy()
def a(mydataframe): def adj_hdi(row): hdi = row['HDI'] if hdi>.5: return hdi else: return 0 mydataframe['ADJ_HDI'] = mydataframe.apply(lambda row: adj_hdi(row), axis = 1) return mydataframe def b(homework2): homework2['ADJ_HDI'] = 0 homework2.loc[(homework2['HDI'] > 0.5), ['ADJ_HDI']] = homework2['HDI'] return homework2 def c(homework2): homework2['ADJ_HDI'] = np.where(homework2['HDI'] > .5, homework2['HDI'], 0) return homework2 print a(homework2) print b(h) print c(h1)
len(homework2) = 7
:
In [2]: %timeit a(homework2) 1000 loops, best of 3: 376 µs per loop In [3]: %timeit b(h) The slowest run took 4.62 times longer than the fastest. This could mean that an intermediate result is being cached 1000 loops, best of 3: 1.49 ms per loop In [4]: %timeit c(h1) The slowest run took 5.52 times longer than the fastest. This could mean that an intermediate result is being cached 1000 loops, best of 3: 283 µs per loop
len(homework2) = 7k
:
In [7]: %timeit a(homework2) 10 loops, best of 3: 106 ms per loop In [8]: %timeit b(h) 100 loops, best of 3: 2.63 ms per loop In [9]: %timeit c(h1) The slowest run took 5.30 times longer than the fastest. This could mean that an intermediate result is being cached 1000 loops, best of 3: 324 µs per loop
-20427266 0 The usual approach to this is to treat either the first or the last printf
as a special case (outside of the loop):
for(ii=0; ii<2; ii++) { jj = 0; printf("%d", jj); // first number printed without space. for(jj=1; jj<4; jj++) { printf(" %d", jj); // include the space before the number printed } if(ii<2-1) printf("\n"); }
Obviously I simplified how the loops are constructed and what is printed - for simplicity. You could make the first printf
statement
printf("\n%d", jj);
then you have a newline at the start of your output (often a good thing) and then you don't need the if
statement later - you just don't have a newline printed at the end of the line (because it will be printed at the start...)
There are marginally more efficient ways of doing this that would involve no if
statements at all - but these all come at the expense of less readable code. For example, here is a "no loop unrolling and no additional if statements" version of the code:
#include <stdio.h> int main(void) { int ii, jj; ii = 0; while(1) { jj = 0; while(1) { printf("%d", jj); // include the space before the number printed jj++; if(jj<4) printf("."); else break; } ii++; if(ii<2) printf("*\n"); else break; } return 0; }
Output:
0.1.2.3* 0.1.2.3
Basically I have taken the functionality of the for
loop and made it explicit; I also use a .
rather than a and
"*\n"
rather than "\n"
to show in the printout that things behave as expected.
It does what you asked without extra evaluation of the condition. Is it more readable? Not really...
-13975752 0Here's how I pass multi-touch to C++ code for an OpenGL program (with 1 or 2 fingers):
// Set this in your ViewController's init code [self setMultipleTouchEnabled:YES]; // Implement these in ViewController int touchCount = 0; UITouch* touch[2]; - (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event{ NSArray* array = [touches allObjects]; UITouch* touchTemp; int t; int touchedPixel[2]; for(int i = 0; i < [array count]; ++i){ touchTemp = [array objectAtIndex:i]; if(touchCount >= 2) return; if(touch[0] == NULL) t = 0; else t = 1; touch[t] = touchTemp; CGPoint touchLoc = [touch[t] locationInView:(EAGLView *)self.view]; ++touchCount; touchedPixel[X] = touchLoc.x; touchedPixel[Y] = touchLoc.y; mainScreen->push(t, touchedPixel); // mainScreen is a C++ object for GL drawing. } } - (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event{ NSArray* array = [touches allObjects]; UITouch* touchTemp; int t; int touchedPixel[2]; for(int i = 0; i < [array count]; ++i){ touchTemp = [array objectAtIndex:i]; for(t = 0; t < 2; ++t){ // Find the matching touch in the array if(touchTemp == touch[t]) break; } if(t == 2) // Return if touch was not found continue; CGPoint touchLoc = [touch[t] locationInView:(EAGLView *)self.view]; touchedPixel[X] = touchLoc.x; touchedPixel[Y] = touchLoc.y; mainScreen->move(t, touchedPixel); } } - (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event{ NSArray* array = [touches allObjects]; UITouch* touchTemp; int t; int touchedPixel[2]; for(int i = 0; i < [array count]; ++i){ touchTemp = [array objectAtIndex:i]; for(t = 0; t < 2; ++t){ // Find the matching touch in the array if(touchTemp == touch[t]) break; } if(t == 2) // Return if touch was not found continue; CGPoint touchLoc = [touch[t] locationInView:(EAGLView *)self.view]; touch[t] = NULL; --touchCount; touchedPixel[X] = touchLoc.x; touchedPixel[Y] = touchLoc.y; mainScreen->release(t, touchedPixel); } } - (void)touchesCancelled:(NSSet*)touches withEvent:(UIEvent*)event{ printf("Touch cancelled\n"); [self touchesEnded:touches withEvent: event]; }
-12889413 0 id:
It will identify the unique element of your entire page. No other element should be declared with the same id. The id selector is used to specify a style for a single, unique element. The id selector uses the id attribute of the HTML element, and is defined with a "#".
class:
The class selector is used to specify a style for a group of elements. Unlike the id selector, the class selector is most often used on several elements.
This allows you to set a particular style for many HTML elements with the same class.
The class selector uses the HTML class attribute, and is defined with a "."
-36099219 0The reason .NET could not "just" sort your Customer
objects is because it has no way of guessing in what way you want to sort them: by salary, by first name, by last name, by the time they placed their first order, etc.
However, you can make it work without implementing IComparable
in three different ways:
IComparer<Customer>
implementation - this lets you move comparison logic to a separate class, and apply different comparison logics based on a situation.Comparison<Customer>
delegate - same as above, but now you don't need a separate class; this lets you provide comparison logic in a lambda.OrderBy
instead - Similar to above, but gives you additional capabilities (filtering, projecting, grouping, etc.)In scala.collection
, there are two very similar objects JavaConversions
and JavaConverters
.
Just found the answer: adding .url fixes this issue fixes it such as {{fl.uploadedfile.url}}
For(int i=0; JsonArray.length(); i++) { JSONObject jsonObj = JsonArray.getJSONObject(i); CourseDetail[i].setCourseName(jsonObj.getString("Name")); ... ... }
Hope this help!
-8695891 0 Is there any way to work with a Node stream as an iterable?I’m writing a tool which processes a bunch of text passed in to stdin
, each line is an “entry”. I’d like to make my code more functional, so I’d like to treat the set of lines as a “sequence” or “iterable” and iterate over it using reduce
.
I’m currently using the Node module LineStream to process stdin
as a set of lines, but it works by dispatching a data
event for each line — which is fine, it’s implementing the Readable Stream interface.
So I’m currently doing kind of a very “manual” reduce by passing the interim value in to my function every time the data
event fires:
var windows = []; linestream.on('data', function(line) { return windows = rollup(windows, extractDate(line), argv.w); }); linestream.on('end', function() { return process.stdout.write(toCsv(windows)); }); process.stdin.resume();
But it’d be more functional to do something like:
linestream.lines.reduce(rollup, []); function rollup(windows, line) { // would return a new interim or final value }
Of course, I could “collect” all the lines into a regular array and then reduce it, but I tried that and it uses way too much memory when I’m running my tool on a large dataset — so something like iteration over the stream is really what’s necessary.
I guess what I’m asking is whether it’s possible to write a Node function/module which would do this, or whether one exists already.
Thanks!
-27195992 0 Why iOS App name is capitalised even dow I set uncapitalized project name?I created a "Trade Movie Records" project in Xcode, and when I run app, it uses under icon the "Trade movie records" label, why? How can I force use small capital?
I change Bundle name to "Trade movie records", that was the trick, thanks.
Untested, but I think this does what you want.
jQuery(function () { var menus = jQuery('#menu li'); var open_menu = function open_menu() { var menu_to_open = jQuery(this); if (menu_to_open.hasClass('open')) { menu_to_open.removeClass('open'); } else { menus.removeClass('open'); menu_to_open.addClass('open'); } }; menus.click(open_menu); });
-15947572 0 The interface has to be Visitor<T>
Edit: The interface has to look like this
interface Visitor<T> { void visit(T Value); }
-4155844 0 How do I safely read from a stream in asp.net? byte[] bytes = new byte[uploader.UploadedFiles[0].InputStream.Length]; uploader.UploadedFiles[0].InputStream.Read(bytes, 0, bytes.Length); var storedFile = new document(); string strFullPath = uploader.UploadedFiles[0].FileName; string strFileName = Path.GetFileName(strFullPath); storedFile.document_id = Guid.NewGuid(); storedFile.content_type = uploader.UploadedFiles[0].ContentType; storedFile.original_name = strFileName; storedFile.file_data = bytes; storedFile.date_created = DateTime.Now; db.documents.InsertOnSubmit(storedFile); db.SubmitChanges();
If:
Reading from a stream in a single call to Read is very dangerous. You're assuming all the data will be made available immediately, which isn't always the case. You should always loop round, reading until there's no more data.
How should I change the above code to make it 'less dangerous'?
-3839645 0 Transparent background for the Group Table CellFor group table cell, I fall into this problem.
cell.backgroundColor=[UIColor clearColor]
make the cell bg black. It works for normal cell, not for group table cell. I want to add some button, e.g. like the detail view of iPhone contact with transparent background.
-13887634 0 Open multiple song files from appI am writing a simple media server application. I'd like the user to be able to build a playlist of songs within my application and then be able to hit "open", which would then open the default media player (the Windows 8 Music App in my case). Currently, I am using Process.Start() to open the app, but that will only open a single song. Does anyone know how to pass a list of songs to the media player (as arguments?) that will act as a play queue? Thanks for the help.
-15991331 0You might be reffering to: example
If so, set the template property as needed.
You need to delete the summary
text.
pages
stands for the pagination
items
stands for ... the list of items
<?php $this->widget('zii.widgets.CListView', array( 'dataProvider' => $dataProvider, 'template' => "{summary}\n{pager}\n{items}\n{summary}\n{pager}", 'itemView' => '_index', 'pager' => array( 'maxButtonCount' => 10, ), ) ); ?>
-24100314 0 Based on the two examples you provided, this works for me:
str.match(/p\d{4}abc\d{4}-?/i)
Updated, based on comment below.
-21299448 0v &= -signed(v)
will clear all but the lowest set bit (1
-bit) of v, i.e. extracts the least significant 1 bit from v (v will become a number with power of 2 afterwards). For example, for v=14 (1110)
, after this, we have v=2 (0010)
.
Here, using signed()
is because v is unsigned
and you're trying to negate an unsigned
value (gives compilation error with VS2012) (comment from JoelRondeau). Or you will get a warning like this: warning C4146: unary minus operator applied to unsigned type, result still unsigned
(my test).
I'm working on a python script that processes PDF files, though some of them contain encryption that restricts usage to only printing, which I have to manually remove before I can process them.
For that I have been manually using QPDF to remove these restrictions on individual PDF files before running the script (the commands for qpdf are pretty simple...inside the command prompt -> qpdf --decrypt input.pdf output.pdf)
My question is - rather than doing this bit manually, is it possible to execute the QPDF executable file within my Python script and run the command? I haven't been able to find any python modules specifically to control QPDF so I am not holding much hope.
-2357608 0A properly normalized database will look nothing like a proper object-oriented design. The needs of a database are very different from the needs of a software application.
You should design your application according to the requirements for how it is to be used. What sorts of things is the application supposed to do? What objects will be required to support those needs? And what are the natural relationships between them?
A single business object may be stored across a dozen database tables, or a single table may store data for a dozen objects. It really depends on the specifics of the system you are working with.
-31024784 0 Comparing Datagrid cell original value with edited value in CellEditEnding eventI have a totals variable that is updated based on the numbers entered by the user in my Datagrid rows. I would like to update that value on changing each row cell. This is what I've done so far:
private void QuotationDG_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e) { int ColumnIndex = e.Column.DisplayIndex; Double amount= Double.Parse(((TextBox)e.EditingElement).Text); Cat1SubTotal += amount; GrandTotal += amount; }
This code adds up the amount each time the user enters a new value. However, if the user edited the existing value then this would add up the new value without removing the old value thus will show incorrect totals.
I need to do something like this:
Cat1SubTotal += (NewValue-OriginalValue)
-9861916 0 It is ultimately up to the vendor to define the filesystem / filesystem layout. So it might be in a different place. If there is no customized definition then the libraries will be in /data/data/your.package.name/lib
.
In case it is in a different directory then System.loadLibrary
will know that and load the library from that place.
ORDER BY total_clicks, link_time DESC;
-3667710 0 You want to check out Integrated Windows Authentication. This will allow the Active Directory username and password (hashed) to be sent across the network to the server. If they pass you can redirect them to the site, and if not, push them to the login page.
-16689138 0Have you already tried to set the TextBox focus explicitly?
-41045631 0I ended up pulling directly from the database and using a where statement.
return _db.Items .Where(a => a.ItemPayments.Any(b => b.ItemPaymentSplits.Any(c => c.YearSetupId == yearSetupId))) .GroupBy(a => yearSetupId)
-15478116 0 PayPal sanbox API credentials missing? I am using PayPal classic API. When I try to reach out for the sandbox test account API credentials, I got the empty screen below. Can anyone tell me what is going on?
I have a table of class players
with 5 columns and 40 rows. I want to make the second column have width: 200px
.
I can not figure out how to select the specific column in the table. So far I have narrowed it down to this, but this does it to all of the rows in the table. Can someone help me set the column width for a specific column?
table.players td { }
-14756318 0 How to disable a User Control to draw it's background (or Region) My question : How to disable a User Control to draw it's background (or Region)
Note : I already tried to override and empty OnPaintBackground or set background color to transparent.
I'm trying to bypass winform paint for my custom user controls in a custom container. For that I thought to give a try to this : Beginners-Starting-a-2D-Game-with-GDIplus
My setup is :
My render loop is inside the DrawingBoard with all elements specified in the previous link.
public DrawingBoard() { InitializeComponent(); //Resize event are ignored SetStyle(ControlStyles.FixedHeight, true); SetStyle(ControlStyles.FixedWidth, true); SetStyle(System.Windows.Forms.ControlStyles.AllPaintingInWmPaint, true);// True is better SetStyle(System.Windows.Forms.ControlStyles.OptimizedDoubleBuffer, true); // True is better // Disable the on built PAINT event. We dont need it with a renderloop. // The form will no longer refresh itself // we will raise the paint event ourselves from our renderloop. SetStyle(System.Windows.Forms.ControlStyles.UserPaint, false); // False is better } #region GDI+ RENDERING public Timer t = new Timer(); //This is your BackBuffer, a Bitmap: Bitmap B_BUFFER = null; //This is the surface that allows you to draw on your backbuffer bitmap. Graphics G_BUFFER = null; //This is the surface you will use to draw your backbuffer to your display. Graphics G_TARGET = null; Size DisplaySize = new Size(1120, 630); bool Antialiasing = false; const int MS_REDRAW = 32; public void GDIInit() { B_BUFFER = new Bitmap(DisplaySize.Width, DisplaySize.Height); G_BUFFER = Graphics.FromImage(B_BUFFER); //drawing surface G_TARGET = CreateGraphics(); // Configure the display (target) graphics for the fastest rendering. G_TARGET.CompositingMode = CompositingMode.SourceCopy; G_TARGET.CompositingQuality = CompositingQuality.AssumeLinear; G_TARGET.SmoothingMode = SmoothingMode.None; G_TARGET.InterpolationMode = InterpolationMode.NearestNeighbor; G_TARGET.TextRenderingHint = TextRenderingHint.SystemDefault; G_TARGET.PixelOffsetMode = PixelOffsetMode.HighSpeed; // Configure the backbuffer's drawing surface for optimal rendering with optional // antialiasing for Text and Polygon Shapes //Antialiasing is a boolean that tells us weather to enable antialiasing. //It is declared somewhere else if (Antialiasing) { G_BUFFER.SmoothingMode = SmoothingMode.AntiAlias; G_BUFFER.TextRenderingHint = TextRenderingHint.AntiAlias; } else { // No Text or Polygon smoothing is applied by default G_BUFFER.CompositingMode = CompositingMode.SourceOver; G_BUFFER.CompositingQuality = CompositingQuality.HighSpeed; G_BUFFER.InterpolationMode = InterpolationMode.Low; G_BUFFER.PixelOffsetMode = PixelOffsetMode.Half; } t.Tick += RenderingLoop; t.Interval = MS_REDRAW; t.Start(); } void RenderingLoop(object sender, EventArgs e) { try { G_BUFFER.Clear(Color.DarkSlateGray); UIPaint(G_BUFFER); G_TARGET.DrawImageUnscaled(B_BUFFER, 0, 0); } catch (Exception ex) { Console.WriteLine(ex); } } #endregion
Then my elements get the event fired and try to draw what I would like:
public override void UIPaint(Graphics g) { Pen p = new Pen(Color.Blue,4); p.Alignment = System.Drawing.Drawing2D.PenAlignment.Inset; g.DrawLines(p, new Point[] { new Point(Location.X, Location.Y), new Point(Location.X + Width, Location.Y), new Point(Location.X + Width, Location.Y + Height), new Point(Location.X, Location.Y + Height), new Point(Location.X, Location.Y - 2) }); g.DrawImageUnscaled(GDATA.GetWindowImage(), Location); }
here is what happening on my DrawingBoard :
As I can't post image ... here is the link : http://s8.postimage.org/iqpxtaoht/Winform.jpg
So from there I've tried everything I could to disable WinForm to make some magic drawing in background. Tried to override and empty everything that got paint/update/refresh/invalidate/validate on Form/DrawingBoard/Elements but nothing allowed me to get my texture or drawing to not get cropped by the control background : (
I also tried to set the background of the Element as transparent and also to set Form.TransparencyKey = blabla with each element BackColor = blabla. But failed each time.
I'm certainly missing something : / But I don't know what.
-646910 0 A site where users could make suggestion for my code?Hi do you guys know a site where other programmers could make suggestions about the code that I make? I always think that the code I make could be better and I also wish someone could like mentor me or point out some bad habits that I make. I code in Java.
-3298712 0 jQuery UI Sortable - Determine which element is beneath the element being draggedI've implemented jQuery UI's Sortable plug-in on a simple unordered list. Is there any way to determine which element is beneath the element being dragged?
In this screenshot Row 3, column 1
is hovering over Row 2-3, column 1
. In this case; I would need to get hold of Row 2-3, column 1
.
My question has to do with the output that is generated when I run a BIRT report.
Normally, a BIRT report would not show the duplicate portion of each row of data that is written to a report. For instance, if I were generating a report that were to contain multiple lines (rows) of data and the data was organized by a 'Group ID'. The data, for each specific Group ID would be shown indented and organized by each Group ID. The Group ID would be shown in the first row of output, but for subsequent rows of data (for that same Group ID), the Group ID would not be shown. In otherwords, no need to display the same Group ID over and over in the report. This method helps to keep the clutter down and makes the report easier to read.
I have a customer who doesn't want the report generated this way. The specifications are to show each row of report data as if it were directly from a SQL query.
Is there a way to have the BIRT report show all data during the report generation? I've looked all over and still haven't come up with any ideas.
Thanks!
-39907905 0Assuming my understanding is correct you just need to:
numpy.logical_and.reduce(features[index] == features)
Here we first produce the matches between all rows and feature[index]
with:
features[index] == features
Then, we reduce the matrix, which effectively tests, for a column j
, if features[index][j] == features[j]
for all i
As an example:
>>> features = numpy.asarray(numpy.random.randint(2, size=(5, 10)), dtype=bool) >>> features array([[False, True, True, True, False, False, True, False, False, False], [ True, False, True, True, True, True, True, True, False, True], [ True, False, True, False, False, True, True, True, True, True], [False, False, True, False, True, False, False, True, False, True], [False, True, True, True, False, True, False, True, True, True]], dtype=bool) >>> numpy.logical_and.reduce(features[3] == features) array([False, False, True, False, False, False, False, False, False, False])
-7090882 0 If "C:\test.txt" exists and is hidden, then following code fails (h = INVALID_HANDLE_VALUE) :
h = CreateFile("C:\\test.txt", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, 0);
this fails too (argument 6 == FILE_ATTRIBUTES_NORMAL or argument6 == 0 seems so be the same) :
h = CreateFile("C:\\test.txt", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
but this works :
h = CreateFile("C:\\test.txt", GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_HIDDEN, 0);
So roughly in other words : if the file already exists and is hidden then CreateFile with "CREATE_ALWAYS" fails if argument 6 != FILE_ATTRIBUTE_HIDDEN.
-6899365 0There's a pretty nice tool called UML Pad.
http://web.tiscalinet.it/ggbhome/umlpad/umlpad.htm
-12112099 0Without the Location property, in addition to the server side caching, the output cache provider also tells the client (browser) to cache the response for the duration given on the attribute properties. To prevent this you need to use the Location property of the OutputCacheAttribute
Changing your attribute to this will solve your problem:
[OutputCache(Duration = 120, Location=OutputCacheLocation.Server)]
-4136368 0 This is probably a stupid solution because I'm terrible and lazy, but here is my crazy work-around:
In the head:
<script type="text/javascript"> function fixmyheight(h) { document.getElementById('fixme').style.height = h + "px"; } </script>
And then in the body:
<ul id="fixme"> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> <li>Item 4</li> <li>Item 5</li> <li>Item 6</li> </ul>
Sorry, I screwed that up at first. Fixed now.
-7184813 0A few quick notes:
Please don’t use eval()
. There are very, very few cases where it’s needed, and it has performance and security implications.
You’ve discovered that JavaScript doesn’t have “variable variables” (the ability to get or set a variable by name), which is why you had to resort to eval()
. When you need to look something up out of a set, don’t use a bunch of numbered variables. Try an array or an object instead.
Objects in JavaScript don’t get copied when you assign them to variables. The line
var arrayExtended = arrayGiven;
doesn't make a copy of arrayGiven
— arrayExtended
ends up being a variable which points at the same array. So, when you change something in arrayExtended
, it also changes it in arrayGiven
. If you need to copy an array in JavaScript, use .slice()
with no arguments:
var arrayExtended = arrayGiven.slice();
Some other things in JavaScript, like objects, are trickier to copy.
What are you trying to do here? (mainArray
is already an array) This is going to create a string which is a “[”, followed by the string representation of mainArray
(each item in the array separated by commas), followed by “]”. Slimbox won’t know what to do with it.
jQuery.slimbox("[" + mainArray + "]",startAtImage);
If you do want to wrap something in an array, just put brackets around it like you did up above:
[mainArray];
I think your main problem is "[" + mainArray + "]"
. With those tips, you should be able to make your code work (and, without eval()
). But, I want to show you my approach to this problem too. It’s below.
I’m storing the names and descriptions of all the images in an array. Because arrays in JavaScript (and a lot of other programming languages) start at 0 instead of one, I subtracted one from all the image numbers in the arrays that specify the order.
var album = "summer", images = [ [ { name: "1", description: "Description #1" }, { name: "4", description: "Description #4" }, { name: "5", description: "Description #5" } ], [ { name: "2", description: "Description #2" }, { name: "6", description: "Description #6" } ], [ { name: "3", description: "Description #3" } ] ], order = [0, 2, 1], startAtImage = 0, slimboxImages = Array.prototype.concat.apply([], order.map(function(id){ return images[id]; })) .map(function(image){ return [ 'img/' + album + '/' + image.name + '.jpg', image.description]; }); jQuery.slimbox(slimboxImages, startAtImage);
-29697477 0 Sorry, that page does not exist [code] => 34 POST /statuses/retweet
is giving me this error while POST statuses/tweet
and GET search/tweets
are working fine.
public $host = "https://api.twitter.com/1.1/"; $con = $this->oauth(); $retweets = $con->post('statuses/retweet/', array('id' => $searchid));
The query will get the Status id_str
of the object. It is in string format.
/** * POST wrapper for oAuthRequest. */ function post($url, $parameters = array()) { $response = $this->oAuthRequest($url, 'POST', $parameters); if ($this->format === 'json' && $this->decode_json) { return json_decode($response); } return $response; }
API console gives me no error:
https://api.twitter.com/1.1/statuses/retweet/{id}.json
-36233348 0 How to find the oauth_verifier in Magento I've to use Magento Web API's using OAuth . I have created a Consumer with web panel and i've consumer key and consumer secret key. now i have to find the Access token . so i refered some material and came to run the following command
oauth \ --verbose \ --query-string \ --consumer-key c9c60d4aaf670c86acee7e93bb776e45 \ --consumer-secret 0a0b845eb7507de84c63740b15561568 \ --access-token-url http://localhost/magento/oauth/token \ --authorize-url http://localhost/magento/oauth/authorize \ --request-token-url http://localhost/magento/oauth/initiate \ authorize
The response came like
Server appears to support OAuth 1.0a; enabling support. Please visit this url to authorize: http://localhost/magento/oauth/authorize?oauth_token=6a57c2e2d3f9883a94bfd2087dd95a89 Please enter the verification code provided by the SP (oauth_verifier):
Now i dont know where to find the verification code and how to use this.
Help me through this,. Thanks in advance:)
-40581017 0 Retrofit calls to jersey Rest API issuei am banging my head over this issue but i can not tell what it is exactly.. Anyway i have a mobile application that uses Retrofit 2 to make calls to my jersey Rest server, i will post the code below and try to explain what happens.
Server side Database connector
public class Connector { private Context initCtx = null; private Context envCtx; private DataSource ds; public Connection con; public Connection getDbConnection () throws SQLException{ try { Class.forName("org.mariadb.jdbc.Driver").newInstance(); initCtx = new InitialContext(); envCtx = (Context) initCtx.lookup("java:comp/env"); ds = (DataSource) envCtx.lookup("jdbc/kokosinjac"); con = ds.getConnection(); System.out.print("Got Connection"); }catch (Exception ex){ // con.close(); System.out.print("Could not establish connection to the Database"); ex.printStackTrace(); } return con;} }
Comment service
@Path ("/commentService") public class CommentService { CommentDAO cmDao = new CommentDAO(); @POST @Path ("/insertRecords") @Consumes (MediaType.APPLICATION_JSON) public void insertData (Comment comment) throws SQLException{ System.out.println("Do we have something here? : "+ comment.getUploader()); cmDao.insertTextData(comment); } @GET @Path ("/listComments") @Produces (MediaType.APPLICATION_JSON) public List getComments (@QueryParam ("catId")int catId,@QueryParam ("itemId")int itemId) throws SQLException { return cmDao.getComments(catId,itemId);} }
Comment DAO
public class CommentDAO { public void insertTextData (Comment comment) throws SQLException{ Connector dbConnector = new Connector(); Connection con = null; PreparedStatement preparedStmt; String query = "INSERT into comments (catId,itemId,comment,uploader,date)" + "VALUES (?,?,?,?,?)"; Date todaysDate = new Date(); DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { con = dbConnector.getDbConnection(); preparedStmt = con.prepareStatement(query); preparedStmt.setInt(1,comment.getCatId() ); preparedStmt.setInt(2,comment.getItemId()); preparedStmt.setString(3, comment.getComment()); preparedStmt.setString(4, comment.getUploader()); preparedStmt.setString(5, df.format(todaysDate)); preparedStmt.execute(); con.close(); dbConnector.con.close(); preparedStmt.close(); con = null; dbConnector = null; preparedStmt = null; }catch (Exception ex){ System.out.println("Insert comment exception"); ex.printStackTrace(); }finally{ if (con != null){ try { con.close(); }catch (Exception ex){ ex.printStackTrace(); } con = null; } if (dbConnector != null){ try { dbConnector.con.close(); }catch(Exception ex){ex.printStackTrace();} dbConnector = null; } } } public List<Comment> getComments (int catId,int itemId) throws SQLException { List<Comment> commentData = new ArrayList<>(); Comment comment = null; Connector dbConnector = new Connector(); ResultSet rs = null; Statement stmt = null; Context initCtx= null; Context envCtx = null; DataSource ds =null; Connection con = null; try { con = dbConnector.getDbConnection(); stmt = con.createStatement(); rs = stmt.executeQuery("SELECT * FROM comments WHERE catId = "+catId+" AND itemId ="+itemId+" ORDER BY date DESC"); while (rs.next()){ comment = new Comment(); comment.setComment(rs.getString("comment")); comment.setUploader(rs.getString("uploader")); comment.setDate(rs.getString("date")); commentData.add(comment); } con.close(); dbConnector.con.close(); rs.close(); stmt.close(); con = null; dbConnector = null; rs = null; stmt = null; }catch (Exception ex){ System.out.println("Get comment list exception"); ex.printStackTrace(); }finally { if (con != null){ try { con.close(); }catch (Exception ex){ ex.printStackTrace(); } con = null; } if (dbConnector != null){ try { dbConnector.con.close(); }catch(Exception ex){ex.printStackTrace();} dbConnector = null; } if (rs != null){ try { rs.close(); }catch (Exception ex){ ex.printStackTrace(); } rs = null; } if (stmt !=null){ try { stmt.close();}catch (Exception ex){ ex.printStackTrace(); } stmt = null; } } return commentData; } }
Android app Activity
........ void commentClick (View v){ ..... listComments(categoryId,item,context); ...... } public void listComments (int catId,int itemId, final Context cont){ RetrofitAPInterface apiService = ApiClient.getClient().create(RetrofitAPInterface.class); Call<ArrayList<Comment>> call = apiService.getComments(catId, itemId); call.enqueue(new Callback<ArrayList<Comment>>() { @Override public void onResponse(Call<ArrayList<Comment>> call, Response<ArrayList<Comment>> response) { ArrayList<Comment> commArr = response.body(); Log.i(TAG, "onResponse: ARRAY"+commArr); combinedArr = new ArrayList<Comment>(); updateCommentArray(commArr); populateListView(cont); } @Override public void onFailure(Call<ArrayList<Comment>> call, Throwable t) { } }); } private ArrayList<Comment> updateCommentArray (ArrayList<Comment> commArray){ for (Comment o : commArray) { combinedArr.add(o); } return combinedArr;} private void populateListView ( final Context cont){ ListView lView = (ListView) findViewById(R.id.commentsListView); if (!uploadClicked){ listAdapter = new AdapterComment(cont, R.layout.custom_row_comment,combinedArr ); lView.setAdapter(listAdapter); } else{ uploadClicked = false; //lView.setAdapter(listAdapter); listAdapter.notifyDataSetChanged(); } } void uploadComment (View v){ ..... final Comment com = new Comment(catId, itemIdint, comment, uploader, date); RetrofitAPInterface apiService = ApiClient.getClient().create(RetrofitAPInterface.class); Call<Comment> call = apiService.insertComment(com); Log.i(TAG, "uploadComment: pre enqueue"); call.enqueue(new Callback<Comment>() { @Override public void onResponse(Call<Comment> call, Response<Comment> response) { Comment check = response.body(); Context context = getApplicationContext(); int duration = Toast.LENGTH_SHORT; //IF COMMENT PASSED if (response.code() == 204) { InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); uploadPb.setVisibility(View.GONE); CharSequence text = "Komentar poslat"; Toast toast = Toast.makeText(context, text, duration); toast.show(); commentText.setText(""); uploaderText.setText(""); combinedArr.add(0,com); populateListView(context); //IF IT DID NOT PASS } else { uploadPb.setVisibility(View.GONE); CharSequence text = "Komentar nije poslat"; Toast toast = Toast.makeText(context, text, duration); toast.show(); } call.cancel(); Log.i(TAG, "onResponse: Response" + response.code()); } @Override public void onFailure(Call<Comment> call, Throwable t) { Context context = getApplicationContext(); uploadPb.setVisibility(View.GONE); AlertDialog.Builder alert = new AlertDialog.Builder(context); alert.setTitle("Server"); alert.setMessage("Ups, nesto nije uredu sa serverom, komentar nije poslat"); alert.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { finish(); } }); alert.show(); } }); ..... }
Ok, so in that activity i have a FAB button that switches between views, when it switches to comment view it requests all comments for that picture, and in comment view i can upload a new comment. Everything works fine except this: for example if i spam the FAB button lets say 6 times and i end up on comment view and upload a new comment, on my tomcat server log i will get
EG. Got Connection Got Connection Got Connection Got Connection Got Connection Got Connection Do we have something here? uploadedComment
The dilemma here is : Is it a memory leak, and if it is how do i make a brand new call every time. Or does the System.out.print write everything in the end, and if it is why doesn't it write Got connection everytime i swipe the screen and it downloads the new comments. If someone could clarify this i would be really really greatfull! Thanks :D
-9967997 0Intel has been doing some open-source research on multithreading in Javascript, it was showcased recently on GDC 2012. Here is the link for the video. The research group used OpenCL which primarily focuses on Intel Chip sets and Windows OS. The project is code-named RiverTrail and the code is available on GitHub
Some more useful links:
Building a Computing Highway for Web Applications
-39545763 0 React-bootstrap-table: Warning: Component's children should not be mutatedI use this short example snippet in my code
<BootstrapTable data={products}> <TableHeaderColumn dataField="id" isKey={true}>Product ID</TableHeaderColumn> <TableHeaderColumn dataField="name">Product Name</TableHeaderColumn> <TableHeaderColumn dataField="price">Product Price</TableHeaderColumn> </BootstrapTable>
And everything's work perfect. There's table, there's data. But (!) I see next warning message in my Chrome console:
whereas if I use my own elements, there's no warnings..
What's wrong? How to fix it?
i run shell in command line in 1 hours. I want use PHP script to stop it . I known its $pid is 2000 by use getmypid();
I used PHP script as: exec("kill 2000");exec("kill -KILL 2000"); exec("kill -9 2000"); posix_kill(2000,9);
but can't kill it.
If in terminal, i simple use ~$ kill 2000
.But can't with php script .
No matter what I do I cannot seem to cache my aspx pages locally on the browser. The first request for a page after login goes to the server and retrieves it from there. The 2nd request onwards, the pages are fetched form local cache. However as soon as I signout and sign back in, the same page is yet again fetched from the server and not taken from the cache locally.
URL of my page is as follows:
http://mywebsite.net/page1.aspx?v=2015_3.0&ln=en-EN&sid=612e0d3f-f29d-4b98-b4f7-6788e5a35a03
Response Header of the Page looks like this:
Cache-Control:private, max-age=31536000 Content-Encoding:gzip Content-Length:18355 Content-Type:text/html; charset=utf-8 Date:Thu, 03 Sep 2015 15:34:59 GMT Expires:Fri, 02 Sep 2016 15:34:56 GMT Last-Modified:Thu, 03 Sep 2015 15:34:56 GMT Server:Microsoft-IIS/8.5 Vary:Accept-Encoding X-AspNet-Version:4.0.30319 X-Powered-By:ASP.NET
In my aspx code behind this is what I had set
resp.Cache.SetCacheability(HttpCacheability.ServerAndPrivate) resp.Cache.SetOmitVaryStar(True) resp.Cache.SetExpires(DateTime.UtcNow.AddYears(1)) resp.Cache.SetMaxAge(New TimeSpan(365, 0, 0, 0)) resp.Cache.SetLastModified(DateTime.UtcNow) resp.Cache.SetValidUntilExpires(True) resp.Cache.VaryByParams.Item("v") = True resp.Cache.VaryByParams.Item("ln") = True resp.Cache.VaryByParams.Item("sid") = False
Can anyone please suggest why would the browser not take the page from local cache?
-34673640 0There is no point in representing it as a mathematical function because it won't save you any computations.
Indeed all you need is the weights, biases, activation and your architecture. I'm assuming it is a simple feedforward network as you said, you need to implement some kind of matrix multiplication and addition in C. Also, you'll need to implement the activation function. After that, you're ready to go. Your feed forward NN is ready to be implemented. If the C code will not be used for training, it won't be necessary to implement the backpropagation algorithm in C.
A feedforward layer would be implemented as follows:
Output = Activation_function(Input * weights + bias)
Where,
Input: (1 x number_of_input_parameters_for_this_layer)
Weights: (number_of_input_parameters_for_this_layer x number_of_neurons_for_this_layer)
Bias: (1 x number_of_neurons_for_this_layer)
Output: (1 x number_of_neurons_for_this_layer)
The output of a layer is the input to the next layer.
-27253198 0You don't have just one line-break but more. .
is just recognizing symbols, but no white-spaces, line-breaks or things like those. Additional to that, when you use the *
then you don't need a ?
anymore.
So a valid rule for your example would be: <w:p (.|\s)*<w:t>(.|\s)*</w:p>
No. Long answer: There are at least two completely different branches of the .NET Framework. The desktop/server ones which are the ones you want access to and the Silverlight ones which include the Windows Phone and XNA branches.
It is possible to write libraries that work with both branches of frameworks in binary form, but they cannot use any API save very fundamental stuff. Especially UI and IO is off limits. So in practice, you have two worlds that are incompatible on a binary level. This is very sad, but that's how it is and it can't changed without breaking backward compatibility.
So as others said, even with elevated privileges, you need to write a separate software in the main .NET framework and communicate with it over COM or Silverlight's host environment.
-33089211 0 Catch-all Exception Handler for non-UI Threads in WPFSpecifically, I'm using WPF with MVVM. I have a MainWindow, which is a WPF Window where all of the action happens. It uses a corresponding View Model class for its properties, commands, etc.
I have set up main UI thread and non-UI thread exception handlers in Application.xaml.vb StartUp like this:
Private Sub Application_DispatcherUnhandledException(sender As Object, e As Windows.Threading.DispatcherUnhandledExceptionEventArgs) Handles Me.DispatcherUnhandledException ' catches main UI thread exceptions only ShowDebugOutput(e.Exception) e.Handled = True End Sub Private Sub Application_Startup(sender As Object, e As StartupEventArgs) Handles Me.Startup ' catches background exceptions Dim currentDomain As AppDomain = AppDomain.CurrentDomain AddHandler currentDomain.UnhandledException, AddressOf UnhandledExceptionHandler AddHandler System.Threading.Tasks.TaskScheduler.UnobservedTaskException, AddressOf BackgroundTaskExceptionHandler End Sub Sub UnhandledExceptionHandler(sender As Object, args As UnhandledExceptionEventArgs) Dim ex As Exception = DirectCast(args.ExceptionObject, Exception) ShowDebugOutput(ex) End Sub Sub BackgroundTaskExceptionHandler(sender As Object, args As System.Threading.Tasks.UnobservedTaskExceptionEventArgs) Dim ex As Exception = DirectCast(args.Exception, Exception) ShowDebugOutput(ex) End Sub
When I try to test this out, by deliberately throwing an exception, it works. It is actually in the View Model in the Sub that handles the Select All button click.
The button:
<Button Content="Select All" Height="23" Width="110" Command="{Binding SelectAllCommand}" />
The Command where I'm throwing the exception that is successfully caught:
Private Sub SelectAll() Throw (New Exception("UI Thread exception")) SetAllApplyFlags(True) End Sub
There's another button in the same MainWindow similarly bound to a command. However, it uses a Task to perform its work in the background, and an exception thrown in there does NOT get caught by my catch-all handlers.
Private Sub GeneratePreview() ' run in background System.Threading.Tasks.Task.Factory.StartNew( Sub() ' ... stuff snipped out, issue is the same with or without the rest of the code here ... Throw (New Exception("Throwing a background thread exception")) End Sub) End Sub
There are several similar questions, but I haven't been able to actually figure out my answer from them. The AppDomain UnhandledException seems to be the answer in most cases, but it isn't for mine. What exactly do I have to add to be able to catch an exception that might be thrown in a non-UI thread this way?
I could not get the TaskScheduler.UnobservedTaskException event to call my event handler when I was handling it in Application.xaml.vb. But I took hints from the other answer, and I'll mark it as the answer because it ultimately helped.
However, it is not at the application level, so if this was a larger application, I'd have to duplicate this in every instance where I used a Task. This wasn't really what I was looking for, but not willing to spend more time on it now.
I ended up putting a try-catch inside the Task. In the catch, I was able to use Dispatcher.Invoke to still display a user-friendly dialog with the exception info.
Private Sub GeneratePreview() ' run in background System.Threading.Tasks.Task.Factory.StartNew( Sub() Try ' ... stuff snipped out, issue is the same with or without the rest of the code here ... Throw (New Exception("Throwing a background thread exception")) Catch ex As Exception Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, DirectCast( Sub() HRNetToADImport.Application.ShowDebugOutput(ex) End Sub, Action)) End Try End Sub) End Sub
-4619085 0 You can only use one character per range in a regex and most regex parsers don't understand multiple bytes using the \x
notation. Use the \u
notation instead.
(:|[A-Z]|_|[a-z]|[\xC0-\xD6]|[\xD8-\xF6]|[\xF8-\u02FF]|[\u0370-\u037D]|[\u037F-\u1FFF]|[\u200C-\u200D]|[\u2070-\u218F]|[\u2C00-\u2FEF]|[\u3001-\uD7FF]|[\uF900-\uFDCF]|[\uFDF0-\uFFFD]|[\u10000-\uEFFFF])
The .NET regex documentation states
\x20
Matches an ASCII character using 2-digit hexadecimal. In this case,\x2-
represents a space.
And for unicode:
\u0020
Matches a Unicode character using exactly four hexadecimal digits. In this case\u0020
is a space.
So I've used both above, \x
for the 2-char hex values and \u
for the larger ones.
You can most certainly do anything with K2 from MVC. They have a full range of APIs (web services, dlls, etc.). You can view the developers reference here.
Your K2 installation contains all the *.dll's you need. The default location is C:\Program Files (x86)\K2 blackpearl\Bin.
Here is a simple example of starting a workflow using the SourceCode.Workflow.Client.dll: (NOTE: I write my own class libraries to handle all of my K2 interactions, to separate the work OUT of my controllers, but you could simply place the method below in your controller if you wanted).
using SourceCode.Workflow.Client; public class MySampleK2Service: IMySampleK2Service { private readonly string serverHost; private readonly string impersonatedUser; public MySampleK2Service(string serverHost, string impersonatedUser) { this.serverHost = serverHost; this.impersonatedUser = impersonatedUser; } public int StartNewWorkflow(string processName, string folio) { using (var connection = new Connection()) { connection.Open(this.serverHost); if (this.impersonatedUser != null) { connection.ImpersonateUser(this.impersonatedUser); } var processInstance = connection.CreateProcessInstance(processName); processInstance.Folio = folio; connection.StartProcessInstance(processInstance, true); return processInstance.ID; } } }
-31437272 0 In XAML there are four possible Stretch
options:
None
The image is shown in it's original size. If its larger than the parent element, it'll only show the top left portion of the image that fits inside. If the image is smaller than the parent element, then it's shown in it's entirety.
Fill
The image is resized to fill the parent element. If the aspect ratios are different, then the image will be stretched to fit the parent. This will distort the image.
Uniform
The image will be scaled up as large as it can be, while still being completely inside of the parent. Unlike Fill which will stretch the image to make it fit perfectly, Uniform will keep the aspect ratio of the image and stop scaling when it reaches the bounds of the parent.
UniformToFill This is the bastard child of the previous two. It will scale the image, while keeping the aspect ratio, until it fills the parent element. This means that some parts of the image will be clipped if the aspect ratios are different.
For more information on the Stretch
enumeration, hit it up on MSDN
UPDATE
If you want to show the image outside of the bounds of the parent you could do something like this:
<Grid Width="100" Height="50"> <Grid.Clip> <RectangleGeometry Rect="0 0 100 50"/> </Grid.Clip> </Grid>
This was suggested here on SO
-33760231 0You need a loop on letterB, also maybe change the timer from 0.5 to 1.0
-1264847 0 Which word stemmer should I use in nltk?My goal is to analyze some corpus (twitter for the now) for emotional content. Just today I realized it would make a bit of sense to search for word stems as opposed to having an exhaustive list of emotional word stems. And so I've been exploring nltk.stem only to realize that there are 4 different stemmers. I'd like to ask the stackoverflow linguists whether LancasterStemmer, PorterStemmer, RegexpStemmer, RSLPStemmer, or WordNetStemmer is best preferably with some justification.
-35849515 0To broad to answer but still one suggestion is that you should save comments or answers into remote server because saving in SQlite to users phone will eat too much memory of device.
-18521768 0 Proguard parseException with -dontoptimize commandI use proguard with optimization enabled, but I need to exclude a class MyCarGrid
from the proguard optimization process
so I have write in my proguard config file
-dontoptimize MyCarGrid{*;}
Unfortunately proguard doesn't accept this syntax and return the following error
Proguard returned with error code 1. See console [2013-08-30 00:03:37 - MyApp] proguard.ParseException: Unknown option 'MyCarGrid' in line 76 of file 'D:\Eclipse\MyApp\proguard-project.txt', [2013-08-30 00:03:37 - MyApp] included from argument number 2 [2013-08-30 00:03:37 - MyApp] at proguard.ConfigurationParser.parse(ConfigurationParser.java:217) [2013-08-30 00:03:37 - MyApp] at proguard.ProGuard.main(ProGuard.java:476)
How could I fix this?
-27474172 0 Using Socket.io, AngularJS and Express, client listening on different port than which the server is running atI was trying to implement a chat application with authentication. I followed this tutorial to make the chat application which uses Socket.io.
When I used this tutorial the server is listening at port 8000 whereas the client is running at port 8100. The Socket URL is at 8000 and the chat application is working perfectly. However when I try to use methods of Express such as app.get()
, I cant seem to make it work. I think the cause is that the port of the local host is 8100 and I am listening on 8000. I am using app.get()
and AngualrJS to authenticate using PassportJS. Please can someone help me out as I have been stuck on this for a while. Thanks and I would really appreciate any help. Maybe I am thinking about this the wrong way.
$(document).ready(function() { var $submit = $("#submit_prog").hide(), $cbs = $('input[name="prog"]').click(function() { $submit.toggle( $cbs.is(":checked") ); }); });
Demo: http://jsfiddle.net/QMtey/1/
The .toggle()
method accepts a boolean for whether to show or hide.
You can put the key between brackets ([]
) to form it from a string:
cookieJSON.Cases['mdata' + i]
This is using the Service-Locator anti-pattern. It will work, but you lose the flexibility of IoC and add a dependency everywhere that is difficult to test.
This simple answer is that you can add "KernelContainer.Inject(this)" to your HttpHandler. Or you can create a custom module (or modify the existing Ninject.Web one) to do injection before handler execution.
-34000747 0There is a String
constructor for this problem:
var s = String(count: 10, repeatedValue: Character(" "))
-25075295 0 You need to keep the selected item index inside pager adapter instead. And on click of any item inside a fragment change that value.
interface ItemSelectionInterface{ void onItemSelectionChanged(int fragmentPosition,int itemIndex); int getSelectedItemOnFragment(int fragmentPosition); }
implement above interface in PagerAdapter:
class YourPagerAdapter....... implements ItemSelectionInterface{ int selectedFragment,selectedItem; @Override public Fragment getItem(int position) { return GridFragment.getInstance(position-(Integer.MAX_VALUE / 2),this); } @Override public int getCount() { return Integer.MAX_VALUE; } void onItemSelectionChanged(int fragmentPosition,int itemIndex){ selectedFragment=fragmentPosition;selectedItem=itemIndex; } int getSelectedItemOnFragment(int fragmentPosition){ if(fragmentPosition!=selectedFragment) return -1; return selectedItem; } }
Change your GridFragment to:
class GridFragment ....{ ItemSelectionInterface selectionInterface; @Override public void setMenuVisibility(final boolean visible) { super.setMenuVisibility(visible); if (visible) { mAdapter.notifyDataSetChanged(); } } public static GridFragment getInstance(int position, ItemSelectionInterface selectionInterface){ ........... ........... this.selectionInterface=selectionInterface; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_calednar, container, false); mAdapter = new CalendarGridViewAdapter(getActivity(), getDateTime(position), MONDAY); mAdapter.setSelectionInterface(selectionInterface); mGridView = (GridView) rootView.findViewById(R.id.gridView); mGridView.setAdapter(mAdapter); // TODO handle on item click listener mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { selectionInterface.onItemSelectionChanged(position,i); mAdapter.notifyDataSetChanged(); } }); } return rootView; }
And finally in adapter:
ItemSelectionInterface selectionInterface; //Create a setter for int position;//create a setter @Override public View getView(int i, View convertView, ViewGroup viewGroup) { // if (convertView == null) { LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.grid_item_day, null); //} TextView txt = (TextView) convertView.findViewById(R.id.dayText); txt.setText(""+datetimeList.get(i).getDay()); View actSelection = convertView.findViewById(R.id.actSelection); actSelection.setVisibility(View.INVISIBLE); if(selectionInterface.getSelectedItemOnFragment(position)== i){ actSelection.setVisibility(View.VISIBLE); } .... return convertView; }
-40213624 0 You have syntax error. First set the class into a variable, and then concat it to your string:
$class = 'label label-sm label-info'; //sets the default value $status = 'Processing'; if ($row->status == 2) { $class = 'label label-sm label-success'; $status = 'Approved'; } else if ($row->status == 1) { $class = 'label label-sm label-warning'; $status = 'Waiting'; } $row->status = '<span class="' . $class . '">' . $status . '</span>';
I suggest you to use an IDE like Netbeans, PHPStorm, etc... Those tools are shows you your syntax errors when you are coding.
-12360960 0 how to get each element in one record from mysql databaseI am trying to get each element in one record 'Pests' in database 'crop'.Actually my purpose is to get all the distinct pests in 'Pests' field.
BUT There are not only one element in 'Pests' in database. For example:
Name Pests
Name1 Grasshopper Thrips Potato Leafhoppe Stink Bugs ... ... Name2 Green Cloverworm Mexican Bean Bettle ... ...
My code is like the following. But the result is not what I want. This will display all the pest in each column. But I want all the distinct pests in all column and display each pest in a table, like
Pest | Grasshopper|Thrips|Potato Leafhoppe|Stink Bugs|Green Cloverworm|Mexican Bean Bettle|... ...
Im so appreciate if anyone could give me some hint for how to achieve this. Thanks so much!
$search = "SELECT distinct Pests from crop ORDER BY Pests ASC"; $result = mysql_query($search); echo '<table>'; echo '<tr>'; while ($rs = mysql_fetch_row($result)){ echo '<td>'.$rs[0].'</td>'; } echo '</tr>'; echo '</table>';
-37338717 0 Easy way to try Html 5...without JS
use REQUIRED in input field
<input type="text" name="username" id="username" required>
-26553 0 You can use BindingUtils
to get notified when the dataProvider
property of the combo box changes:
BindingUtils.bindSetter(comboBoxDataProviderChanged, comboBox, "dataProvider");
BindingUtils
lives in the mx.binding.utils
package.
I have a longer description of how to work with BindingUtils
here: Does painless programmatic data binding exist?
You don't need to create a new thread to deal with the EndRequest or EndResponse callback - these will be called for you on a background thread from the ThreadPool. So something like your first code example should work.
If you don't like the nested lambdas just declare named methods :). You can pass state information in the Begin... methods which you can retrieve in the result object.
What you're asking is kind of weird - you're wrapping an async framework with sync version, and rewrapping that with an async version. It sounds like you're creating extra work for yourself in order to stay faithful to your port. You will also use some extra memory to keep an extra thread alive doing nothing (1MB for the stack at least).
If you still want to do it check out this link though.
-5504478 0For low volumes only, yes
You're better to try to INSERT and UPDATE on error. You can assign values with the OUTPUT clause
DECLARE @stuff TBLE (...) BEGIN TRY ... BEGIN TRY INSERT table1 OUTPUT ... VALUES ...() END TRY BEGIN CATCH IF ERROR_NUMBER = 2627 UPDATE table1 SET ... OUTPUT ... ELSE RAISERROR ... END CATCH ... END TRY BEGIN CATCH ... END CATCH
Edit:
Several other answers from me:. Hopefully you get the idea.
You can do the following:
Right click on the file and choose "View History"
On the history tab choose the two revisions you'd like to compare
Finally click on one of the selected revisions and choose "Compare..."
Here's a version of the code that runs on seperate threads. The code you provided above wasn't running a message loop on the second thread. Also setting CheckForIllegalCrossThreadCalls = false is a really bad idea for what you're trying to achieve.
Usage:
ProgressForm.Initialise() ProgressForm.ShowProgressForm("hello", "hello") Dim modalForm As New Form With {.Text = "MyModalForm"} modalForm.ShowDialog() ProgressForm.HideProgressForm() ProgressForm.TearDown()
And here's the ProgressForm definition.
Public Class ProgressForm Inherits Form Private Shared sForm As ProgressForm Private Shared sThread As Thread Public Sub New() Me.TopMost = True Me.BackColor = Color.Green Me.Text = "Progress" End Sub Public Shared Sub Initialise() 'Create the form sThread = New Thread(AddressOf ThreadFunc) sThread.Start() While sForm Is Nothing OrElse sForm.InvokeRequired = False Thread.Sleep(0) End While End Sub Public Shared Sub TearDown() sForm.BeginInvoke(Sub() Application.ExitThread()) End Sub Private Shared Sub ThreadFunc() sForm = New ProgressForm 'Dim handle = sForm.Handle Application.Run(sForm) End Sub Public Shared Sub ShowProgressForm(caption As String, title As String) If sForm.InvokeRequired Then sForm.BeginInvoke(Sub() ShowProgressForm(caption, title)) Else sForm.Text = title 'TODO: Caption sForm.Visible = True sForm.TopMost = True End If End Sub Public Shared Sub HideProgressForm() If sForm.InvokeRequired Then sForm.BeginInvoke(Sub() HideProgressForm()) Else sForm.Visible = False End If End Sub Private Sub ProgressForm_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing If e.CloseReason = CloseReason.UserClosing Then Me.Visible = False e.Cancel = True End If End Sub End Class
-38266581 0 Jasper studio multi column page I have mad a report in jaspersoft studio and I sat the Page Format to 2 columns, Portrait. It shows me what I need to see but starts from the second column at the first page. The first column remains empty! I could not find any configuration regarding this issue. How can I fix this problem. The output looks like this picture:
The source code is:
<?xml version="1.0" encoding="UTF-8"?> <!-- Created with Jaspersoft Studio version 6.3.0.final using JasperReports Library version 6.3.0 --> <!-- 2016-07-08T15:55:48 --> <jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="ergebnisse" columnCount="2" pageWidth="595" pageHeight="842" columnWidth="272" columnSpacing="10" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" isSummaryNewPage="true" uuid="cc068ab5-928c-4253-8ba7-acdd311310fc"> <property name="com.jaspersoft.studio.data.sql.tables" value=""/> <property name="com.jaspersoft.studio.unit." value="pixel"/> <property name="net.sf.jasperreports.print.create.bookmarks" value="true"/> <property name="com.jaspersoft.studio.unit.pageHeight" value="pixel"/> <property name="com.jaspersoft.studio.unit.pageWidth" value="pixel"/> <property name="com.jaspersoft.studio.unit.topMargin" value="pixel"/> <property name="com.jaspersoft.studio.unit.bottomMargin" value="pixel"/> <property name="com.jaspersoft.studio.unit.leftMargin" value="pixel"/> <property name="com.jaspersoft.studio.unit.rightMargin" value="pixel"/> <property name="com.jaspersoft.studio.unit.columnWidth" value="pixel"/> <property name="com.jaspersoft.studio.unit.columnSpacing" value="pixel"/> <property name="com.jaspersoft.studio.data.defaultdataadapter" value="QIDBReport"/> <template><![CDATA["qiDB.jrtx"]]></template> <style name="Table_CH" mode="Opaque" backcolor="#BFE1FF"> <box> <pen lineWidth="0.5" lineColor="#000000"/> <topPen lineWidth="0.5" lineColor="#000000"/> <leftPen lineWidth="0.5" lineColor="#000000"/> <bottomPen lineWidth="0.5" lineColor="#000000"/> <rightPen lineWidth="0.5" lineColor="#000000"/> </box> </style> <style name="Table 1_TH" mode="Opaque" backcolor="#F0F8FF"> <box> <pen lineWidth="0.5" lineColor="#000000"/> <topPen lineWidth="0.5" lineColor="#000000"/> <leftPen lineWidth="0.5" lineColor="#000000"/> <bottomPen lineWidth="0.5" lineColor="#000000"/> <rightPen lineWidth="0.5" lineColor="#000000"/> </box> </style> <style name="condition"> <conditionalStyle> <conditionExpression><![CDATA[$F{KN_Id}.intValue() ==811809 ]]></conditionExpression> <style forecolor="#F0120E"/> </conditionalStyle> </style> <subDataset name="Dataset1" uuid="a8e62151-8fe6-42ec-b6ca-7f971a479ee6"> <property name="com.jaspersoft.studio.data.sql.tables" value=""/> <property name="com.jaspersoft.studio.data.defaultdataadapter" value="QIDBReport"/> <queryString> <![CDATA[select ZI_Infotext, Image, IMG_ID from"ZusatzInfo", Images where ZI_ID = 1269 and IMG_Id = 1]]> </queryString> <field name="ZI_Infotext" class="java.lang.String"/> <field name="Image" class="java.awt.Image"/> <field name="IMG_ID" class="java.lang.Integer"/> </subDataset> <scriptlet name="WrapImage" class="testProjektIman.toc.WrapImage"> <scriptletDescription><![CDATA[Fließtext ums Bild]]></scriptletDescription> </scriptlet> <parameter name="KN_OffeziellGruppe" class="java.lang.Integer"> <defaultValueExpression><![CDATA[3]]></defaultValueExpression> </parameter> <parameter name="LB_ID" class="java.lang.Integer"> <defaultValueExpression><![CDATA[62]]></defaultValueExpression> </parameter> <queryString> <![CDATA[select * from "KennzahlReferenz2015_QIBericht", "Images" where LB_ID = $P{LB_ID} and KN_OffiziellGruppe = $P{KN_OffeziellGruppe} and KN_OffiziellGruppe =$P{KN_OffeziellGruppe} and IMG_ID = 1]]> </queryString> <field name="QI_Praefix" class="java.lang.String"/> <field name="KN_Id" class="java.lang.Integer"/> <field name="bewertungsArtTypNameKurz" class="java.lang.String"/> <field name="refbereich" class="java.lang.String"/> <field name="refbereichVorjahres" class="java.lang.String"/> <field name="KN_ZAlleinstehend" class="java.lang.String"/> <field name="KN_GGAlleinstehend" class="java.lang.String"/> <field name="erlaueterungDerRechregeln" class="java.lang.String"/> <field name="teildatensatzbezug" class="java.lang.String"/> <field name="mindesanzahlZaeler" class="java.lang.Integer"/> <field name="mindesanzahlNenner" class="java.lang.Integer"/> <field name="KN_FormelZ" class="java.lang.String"/> <field name="KN_FormelGG" class="java.lang.String"/> <field name="verwendeteFunktionen" class="java.lang.String"/> <field name="KN_Vergleichbarkeit_Vorjahr" class="java.lang.String"/> <field name="bewertungsArtTypNameLang" class="java.lang.String"/> <field name="bewertungsArtVorjahrTypNameLang" class="java.lang.String"/> <field name="KN_OffiziellGruppeBezeichnung" class="java.lang.String"/> <field name="idLb" class="java.lang.String"/> <field name="LB_LangBezeichnung" class="java.lang.String"/> <field name="LB_ID" class="java.lang.Integer"/> <field name="nameAlleinstehend" class="java.lang.String"/> <field name="KN_BezeichnungAlleinstehendKurz" class="java.lang.String"/> <field name="refBereichArt" class="java.lang.Integer"/> <field name="refBereichEinheitErgebnis" class="java.lang.String"/> <field name="refBereichInfo" class="java.lang.String"/> <field name="KN_OffiziellGruppe" class="java.lang.Integer"/> <field name="KN_Zusatzinfo_Erlaeuterung_Rechenregel" class="java.lang.String"/> <field name="KN_Zusatzinfo_Erlaeuterung_Refbereich" class="java.lang.String"/> <field name="KN_Zusatzinfo_Methode_Risikoadjustierung" class="java.lang.String"/> <field name="KN_Zusatzinfo_Erlaeuterung_Risikoadjustierung" class="java.lang.String"/> <field name="KN_Zusatzinfo_Erlaeuterung_zum_SD" class="java.lang.String"/> <field name="KN_Zusatzinfo_DV_Indikatorbezug" class="java.lang.String"/> <field name="KN_Zusatzinfo_DV_Mindestanzahl_Z" class="java.lang.String"/> <field name="KN_Zusatzinfo_DV_Mindestanzahl_N" class="java.lang.String"/> <field name="KN_Zusatzinfo_DV_Relevanz" class="java.lang.String"/> <field name="KN_Zusatzinfo_DV_Hypothese" class="java.lang.String"/> <field name="KN_Zusatzinfo_DV_Jahr_der_Erstanwendung" class="java.lang.String"/> <field name="KN_Zusatzinfo_DV_Kommentar" class="java.lang.String"/> <field name="KN_Zusatzinfo_DV_Einleitungstext" class="java.lang.String"/> <field name="refBereichInfoArt" class="java.lang.String"/> <field name="refBereichOperator1" class="java.lang.String"/> <field name="refBereichStringAusgabe" class="java.lang.String"/> <field name="refBereichVorjahrInfoArt" class="java.lang.String"/> <field name="refBereichVorjahrOperator1" class="java.lang.String"/> <field name="refBereichVorjahrStringAusgabe" class="java.lang.String"/> <field name="refBereichWert1" class="java.math.BigDecimal"/> <field name="sortierung" class="java.lang.Integer"/> <field name="veroeffentlichungsPflicht" class="java.lang.Integer"/> <field name="QI_ID" class="java.lang.Integer"/> <field name="IMG_ID" class="java.lang.Integer"/> <field name="Name" class="java.lang.String"/> <field name="Image" class="java.awt.Image"/> <variable name="breakPos" class="java.lang.Integer" calculation="System"> <initialValueExpression><![CDATA[$P{WrapImage_SCRIPTLET}.getBreakPosition($F{KN_Zusatzinfo_DV_Einleitungstext},250,60)]]></initialValueExpression> </variable> <group name="LB" isReprintHeaderOnEachPage="true" keepTogether="true"> <groupExpression><![CDATA[$F{LB_ID}]]></groupExpression> <groupHeader> <band height="34"/> </groupHeader> <groupFooter> <band height="50"/> </groupFooter> </group> <group name="KN_ID" isReprintHeaderOnEachPage="true" keepTogether="true"> <groupExpression><![CDATA[$F{KN_Id}]]></groupExpression> <groupHeader> <band height="40"/> </groupHeader> <groupFooter> <band height="50"/> </groupFooter> </group> <background> <band splitType="Stretch"/> </background> <title> <band height="53" splitType="Stretch"> <staticText> <reportElement x="-10" y="10" width="60" height="20" forecolor="#BABABA" uuid="293b49d1-7b6f-46b8-bf8d-eecf08e4d76c"/> <textElement> <font fontName="SansSerif"/> </textElement> <text><![CDATA[Ergebnisse]]></text> </staticText> <textField isStretchWithOverflow="true"> <reportElement x="350" y="5" width="201" height="21" forecolor="#6B66FA" uuid="920ddc7a-36c4-4064-bacb-0d06eee25674"/> <textElement textAlignment="Right"/> <textFieldExpression><![CDATA[$F{idLb} +" - "+ $F{LB_LangBezeichnung}]]></textFieldExpression> </textField> <staticText> <reportElement x="360" y="30" width="191" height="20" uuid="bc3f12b2-89f2-4da8-af9f-97f4f7e6f6ef"/> <textElement textAlignment="Right"/> <text><![CDATA[Dr XYZ]]></text> </staticText> </band> </title> <pageHeader> <band height="59" splitType="Stretch"> <property name="com.jaspersoft.studio.layout" value="com.jaspersoft.studio.editor.layout.FreeLayout"/> <printWhenExpression><![CDATA[new Boolean($V{PAGE_NUMBER} != 1)]]></printWhenExpression> <textField> <reportElement x="350" y="34" width="201" height="21" forecolor="#6B66FA" uuid="e6b696bf-6a6f-4c47-b92f-b4c4df3f56d6"/> <textElement textAlignment="Right"/> <textFieldExpression><![CDATA[$F{idLb} +" - "+ $F{LB_LangBezeichnung}]]></textFieldExpression> </textField> <staticText> <reportElement x="-10" y="7" width="60" height="20" forecolor="#BABABA" uuid="4d7cc8c1-51e1-475c-94b9-9cdb4b912a6d"/> <textElement> <font fontName="SansSerif"/> </textElement> <text><![CDATA[Ergebnisse]]></text> </staticText> </band> </pageHeader> <columnHeader> <band height="61" splitType="Stretch"/> </columnHeader> <detail> <band height="401" splitType="Stretch"> <image scaleImage="RetainShape"> <reportElement x="0" y="10" width="80" height="80" uuid="f9fa3516-451b-46e0-8e60-380798ae46e2"> <property name="com.jaspersoft.studio.unit.width" value="pixel"/> <property name="com.jaspersoft.studio.unit.height" value="pixel"/> </reportElement> <imageExpression><![CDATA[$F{Image}]]></imageExpression> </image> <textField isStretchWithOverflow="true"> <reportElement x="85" y="10" width="185" height="30" uuid="cf3b40af-aaa2-48a9-9742-b6a1de5224fd"> <property name="com.jaspersoft.studio.unit.y" value="pixel"/> </reportElement> <textElement textAlignment="Justified"/> <textFieldExpression><![CDATA[$F{KN_Zusatzinfo_DV_Einleitungstext}.substring(0,$V{breakPos}.intValue() )]]></textFieldExpression> </textField> <textField isStretchWithOverflow="true"> <reportElement x="4" y="101" width="260" height="30" uuid="35f16f07-67b7-4f1d-99e3-0c37f37764dd"/> <textElement textAlignment="Justified"/> <textFieldExpression><![CDATA[$F{KN_Zusatzinfo_DV_Einleitungstext}.substring($V{breakPos}.intValue())]]></textFieldExpression> </textField> <staticText> <reportElement style="StyleHeader" positionType="Float" x="10" y="140" width="170" height="30" forecolor="#000000" uuid="c9456766-8f28-4b5b-813c-00a1e1eac882"/> <textElement markup="styled"/> <text><![CDATA[Documentationspflichtige Leistung]]></text> </staticText> <textField isStretchWithOverflow="true"> <reportElement style="condition" positionType="Float" x="10" y="180" width="100" height="30" uuid="e1ae18a6-1d88-4d4b-b4aa-ecc86ea9f990"/> <textElement markup="styled"/> <textFieldExpression><![CDATA[0]]></textFieldExpression> </textField> </band> </detail> <columnFooter> <band height="45" splitType="Stretch"/> </columnFooter> <pageFooter> <band height="54" splitType="Stretch"/> </pageFooter> <summary> <band height="42" splitType="Stretch"/> </summary> </jasperReport>
I'm creating a Rails 3.0.3 gem and can't get it to work:
# attached.rb module Attached require 'attached/railtie' if defined?(Rails) def self.include(base) base.send :extend, ClassMethods end module ClassMethods def acts_as_fail end end end # attached/railtie.rb require 'attached' require 'rails' module Attached class Railtie < Rails::Railtie initializer 'attached.initialize' do ActiveSupport.on_load(:active_record) do ActiveRecord::Base.send :include, Attached end end end end
I get undefined local variable or method 'acts_as_fail'
when I add acts_as_fail
to any of my ActiveRecord
models. Please help! I'm extremely frustrated with this seemingly trivial code! Thanks!
cant get ionic to setup and run because of the xmlbuilder error and have tried every possibilty of trying it but no luck:
C:\Program Files (x86)\nodejs\node_modules>ionic start todo blank
Error: Cannot find module 'xmlbuilder' at Function.Module._resolveFilename (module.js:338:15) at Function.Module._load (module.js:280:25) at Module.require (module.js:364:17) at require (module.js:380:17) at Object. (C:\Users\armaan\AppData\Roaming\npm\node_modules\ionic\node_modules\xml2js\lib\xml2js.js:12:13) at Object. (C:\Users\armaan\AppData\Roaming\npm\node_modules\ionic\node_modules\xml2js\lib\xml2js.js:436:4) at Module._compile (module.js:456:26) at Object.Module._extensions..js (module.js:474:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:312:12)
-40526461 0 Type error on using Apache Kakfa's KafkaConsumer apiIm writing a simple Kafka Consumer class as follows
public class MySimpleKafkaConsumer { public static void main(String[] args) { Properties props = new Properties(); props.put("bootstrap.servers", "localhost:9092"); props.put("group.id", "mygroup"); props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(props); consumer.subscribe(Arrays.asList("storm-test-topic"));
. .
Although I get an error at the below line stating
The method subscribe(String...) in the type KafkaConsumer is not applicable for the arguments (List)
consumer.subscribe(Arrays.asList("storm-test-topic"));
This seems correct as per the api docs. Here is the dependency version
<groupId>org.apache.kafka</groupId> <artifactId>kafka-clients</artifactId> <version>0.9.0.1</version>
Am I missing something? Thanks
-5431059 0You must know the source encoding.
string someText = "The quick brown fox jumps over the lazy dog."; byte[] bytes = Encoding.Unicode.GetBytes(someText); char[] chars = Encoding.Unicode.GetChars(bytes);
-38371341 0 As far as I can tell from my experiments each top-level test, ie each test named in the load test, gets its own copy of the data sources of called tests. Hence even though the data source is attached to the called (ie login) test each calling test will use all of its values.
My experiment: A very simple web test named Called
has a CSV data source having 100 rows and a column containing the row number. This web test just visits http://localhost/
and expects a 404 response. A WebTestPlugin
has a PostWebTest
method that writes the data source's row number field plus the context parameters $WebTestIteration
and WebTestUserId
to a log file. A second test has as its only actions (1) a call of Called
and (2) a call of the plugin. Made copies of this second test and gave them the names Caller1
, Caller2
and Caller3
. These three tests are used in a load test for 6 virtual users for 2 minutes duration. The log file clearly shows that each CSV row is used by each of the three top-level tests.
It seems that ie and table widths don't play nicely together.
What you can do to enforce a minimum width for your table is to add an extra row to your table which spans all columns which has a width of the minimum size that you desire. This will then enforce your td percentages when the broswer is resized or your iframe is small.
Like so:
<html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title></title> <style> .min500 { width: 500px; height: 1px; } </style> </head> <body> <form id="form1" runat="server"> <table align="center" border="1" cellpadding="0" cellspacing="0" class="loginBg"> <asp:Panel runat="server" ID="pnlLoginIn" style="width:100%;"> <tr> <td colspan="2"> <div class="min500"></div> </td> </tr> <tr> <td style="padding-left:0px;font-family:Verdana;font-size:70%;width:30%;"> Username </td> <td style="padding-right:0px;width:70%;" align="left"> <asp:TextBox id="txtUsername" runat="server" Width="90px" /></td> <asp:RequiredFieldValidator ID="rfvUserName" runat="server" ErrorMessage="*" ControlToValidate="txtUsername" ValidationGroup="credentials" Display="Dynamic" /> </tr> </asp:Panel> </table> </form>
-12991175 0 OSMDroid: onTap example
I've started to study Android few weeks ago and now I need your help. My task is create off-line map (using OSMDroid and Mobile Atlas Creator), with two markers on it, path between them and some activity after clicking on this markers. I've done map, markers and path. Here is the code (Android 2.3.3):
public class MainActivity extends Activity {
private MapView mapView; LocationManager locationManager; ArrayList<OverlayItem> overlayItemArray; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mapView = new MapView(this, 256); mapView.setClickable(true); mapView.setBuiltInZoomControls(true); mapView.getController().setZoom(15); mapView.getController().setCenter(new GeoPoint(54.332, 48.389)); mapView.setUseDataConnection(false); overlayItemArray = new ArrayList<OverlayItem>(); OverlayItem olItem = new OverlayItem("Here", "SampleDescription", new GeoPoint(54.332, 48.389)); overlayItemArray.add(olItem); overlayItemArray.add(new OverlayItem("Hi", "You're here", new GeoPoint(54.327, 48.389))); PathOverlay myPath = new PathOverlay(Color.RED, this); myPath.addPoint(new GeoPoint(54.327, 48.389)); myPath.addPoint(new GeoPoint(54.332, 48.389)); mapView.getOverlays().add(myPath); DefaultResourceProxyImpl defaultResourceProxyImpl = new DefaultResourceProxyImpl(this); ItemizedIconOverlay<OverlayItem> myItemizedIconOverlay = new ItemizedIconOverlay<OverlayItem>(overlayItemArray, null, defaultResourceProxyImpl); mapView.getOverlays().add(myItemizedIconOverlay); setContentView(mapView); //displaying the MapView } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; }
} Question: how to realize onClick-method for this markers? And additional question for profy: how to do it right (I mean how to divide this program by classes)? Thanks a lot! =)
-23557151 0 NullPointerException in AsyncTask where value is checkedI am developing app in Google play. My app have "Google Analytics" and I see in Exceptions:
NullPointerException (@AsyncDownload:onPostExecute:70)
Where is the problem ?
public class AsyncDownload extends AsyncTask<String, Void, Feed > { private FragmentCallback mFragmentCallback; public AsyncDownload(FragmentCallback fragmentCallback) { mFragmentCallback = fragmentCallback; } @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected Void doInBackground(String... arg0) { Feed feed = ArticlesManager.getInstance().getFeed(arg0[0]); if(feed==null){ try { HttpGet get = new HttpGet(Ipsum.Headlines[Integer.valueOf(arg0[0])][2]); HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, 3000); HttpConnectionParams.setSoTimeout(httpParameters, 5000); HttpClient hc = new DefaultHttpClient(); HttpResponse rp = hc.execute(get); if (rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { String res = EntityUtils.toString(rp.getEntity(),HTTP.UTF_8); Feed feed = RssReader.read(res,Integer.valueOf(arg0[0]) == 7); ArticlesManager.getInstance().addFeed(arg0[0], feed); } } catch (Exception e) { e.printStackTrace(); } } return null; } protected void onPostExecute(final Feed feed){ if(mFragmentCallback != null) { mFragmentCallback.onTaskDone(feed); } }
}
-12430065 0 Fancybox 2 afterClose focusI've just tried Fancybox 2 and have a problem! In Fancybox 1.3.4 I could trigger a function when fancybox closed, namely to add the focus to the current thumb element (e.g. in a gallery).
It looked this way:
onClosed : function(){ currentArray[currentIndex].focus(); }
However, in Fancybox 2 they deprecated onClosed
and there is an other parameter, afterClose
, but I couldn't find the variables that store the current thumb element.
Please, help!
-37856330 0 How to redirect bindings to "outside" of a XAML controlLet's say I have a ListView with a ContextMenu. I'd like to use it as a separate control called ListViewWithContextMenu. How can I redirect the command bindings from ContextMenu so they're visible in ListViewWithContextMenu?
Example code:
ListViewWithContextMenu.xaml
<ListView x:Class="WpfApplication4.ListViewWithContextMenu" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:WpfApplication4" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300"> <ListView.ContextMenu> <ContextMenu> <MenuItem Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:ListViewWithContextMenu}}, Path= PreviewCommand}" /> </ContextMenu> </ListView.ContextMenu>
ListViewWithContextMenu.xaml.cs
using System.Windows; using System.Windows.Input; namespace WpfApplication4 { public partial class ListViewWithContextMenu { public ICommand PreviewCommand { get { return (ICommand)GetValue(PreviewCommandProperty); } set { SetValue(PreviewCommandProperty, value); } } public static readonly DependencyProperty PreviewCommandProperty = DependencyProperty.Register("PreviewCommand", typeof(ICommand), typeof(ListViewWithContextMenu)); public ListViewWithContextMenu() { InitializeComponent(); } } }
MainWindow.xaml
<Window x:Class="WpfApplication4.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WpfApplication4" mc:Ignorable="d" Title="MainWindow" Height="350" Width="525"> <Window.DataContext><local:MainWidnowViewModel></local:MainWidnowViewModel></Window.DataContext> <Grid> <local:ListViewWithContextMenu PreviewCommand="{Binding Preview}"></local:ListViewWithContextMenu> </Grid> </Window>
MainWindowViewModel.cs
using System.Windows; using System.Windows.Input; using Microsoft.Practices.Prism.Commands; namespace WpfApplication4 { public class MainWidnowViewModel { public MainWidnowViewModel() { Preview = new DelegateCommand(PreviewMethod); } private void PreviewMethod() { MessageBox.Show("PREVIEW"); } public ICommand Preview { get; set; } } }
This code does not call the PreviewMethod in ViewModel which I want to achive
-40575329 0What your IDE means is likely:
(p) -> new ReadOnlyStringWrapper(p.getValue());
No return
needed.
I have a form on my website, in which I want to submit some data and search a database. The form has a input field, a drop-down menu and a submit button. I want the input field and drop-down to flag/ not submit if the submit button is pressed and nothing is entered. I have looked here: Bootstrap Validator
but it has not worked for me. When i click submit, it just submits the data eg. nothing, to the next page.
Here is my form:
<header> <div class="container"> <div class="row"> <h2>Enter a username and choose a category to search in</h2> <form action="search.php" method="get" novalidate="novalidate" data-toggle="validator" role="form "> <div class="col-lg-12"> <div class="intro-text"> <div class="row"> <div class="input-group"> <div class="form-group"> <input name="search" type="text" class="form-control" aria-label="..." placeholder="Search a username here" required></input> </div> <div class="input-group-btn"> <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Cataegory <span class="caret"></span></button> <ul class="dropdown-menu choice"> <li value="one"><a href="#">Minecraft username</a></li> <li role="separator" class="divider"></li> <li value="two"><a href="#">Minecraft UUID</a></li> <li role="separator" class="divider"></li> <li value="three"><a href="#">McMarket Username</a></li> <li role="separator" class="divider"></li> <li value="four"><a href="#">Skype Username</a></li> </ul> <input type='hidden' name='choice'> <button type="submit" class="btn btn-default">Search</button> </div><!-- /btn-group --> </div><!-- /input-group --> </div><!-- /.row --> </div> </div> </form> </div> </div> </div> </header>
I have tried many of the solutions posed by members on other threads on this forum, and they haven't worked, so I believe the problem is probably a syntax error. Any help would be great. Thank you!
-34810312 0I would recommend you look at Jade. It is a template engine for node js which can be used to create html pages. It is easy to use and very flexible.
A good tutorial is found here. It shows you how to create a simple Website with Node, Express and Jade and is a good starting Point in my opinion.
To solve your problem with Jade there are several answers in stackoverflow like here.
-6223697 0This basically means that in JS "Aardvark" is considered lesser than "Zoroaster" because JS uses something called Lexicographical Ordering, also known as Dictionary Order because dictionaries also use the same order when listing words.
-2497127 0 Validating Application Settings Key Values in Isolated Storage for Windows Phone ApplicationsI am very new at all this c# Windows Phone programming, so this is most probably a dumb question, but I need to know anywho...
IsolatedStorageSettings appSettings = IsolatedStorageSettings.ApplicationSettings; if (!appSettings.Contains("isFirstRun")) { firstrunCheckBox.Opacity = 0.5; MessageBox.Show("isFirstRun not found - creating as true"); appSettings.Add("isFirstRun", "true"); appSettings.Save(); firstrunCheckBox.Opacity = 1; firstrunCheckBox.IsChecked = true; } else { if (appSettings["isFirstRun"] == "true") { firstrunCheckBox.Opacity = 1; firstrunCheckBox.IsChecked = true; } else if (appSettings["isFirstRun"] == "false") { firstrunCheckBox.Opacity = 1; firstrunCheckBox.IsChecked = false; } else { firstrunCheckBox.Opacity = 0.5; } }
I am trying to firstly check if there is a specific key in my Application Settings Isolated Storage, and then wish to make a CheckBox appear checked or unchecked depending on if the value for that key is "true" or "false". Also I am defaulting the opacity of the checkbox to 0.5 opacity when no action is taken upon it.
With the code I have, I get the warnings
Possible unintended reference comparison; to get a value comparison, cast the left hand side to type 'string'
Can someone tell me what I am doing wrong. I have explored storing data in an Isolated Storage txt file, and that worked, I am now trying Application Settings, and will finally try to download and store an xml file, as well as create and store user settings into an xml file. I want to try understand all the options open to me, and use which ever runs better and quicker
-13892778 0I would assume you're trying to create member object properties
''represents a class instance of a blog entry''' title = models.CharField(max_length=100) created = models.DateTimeField() body = models.TextField()
which should ideally go into the constructor method under
def __init__(self): ''represents a class instance of a blog entry''' title = models.CharField(max_length=100) created = models.DateTimeField() body = models.TextField()
-19329366 0 How does git checkout know whether to remove a file or leave it alone? I have some files with "settings" (say, Eclipse *.prefs files) that I don't want to track. They were already being tracked (because I didn't set something up right), but it looked like git rm --cached
was how to stop the files from being tracked. I tried this, and now git status
lists the files as deleted:
, but they're still there in my directory. So far, so good.
Suppose that I use git commit
in the current state; it will create a new commit C1 but won't track those files. Suppose that some time later, and after several more commits, and assuming I've made some changes to my settings files, I use git checkout
to revert to the commit C1. Will this remove the no-longer-tracked settings files, or just leave them alone? I'm concerned about how Git knows the difference, when checking out an earlier commit, between "this file isn't in the commit so I'm going to remove it", and "this file should be left alone". The fact that Git is reporting the files as deleted:
makes me a bit more concerned, I guess, although perhaps that's just inaccurate output.
The 'at' command.
-18359122 0 postgres, contains-operator for multidimensional arrays performs flatten before comparing?"The AT command schedules commands and programs to run on a computer at a specified time and date. The Schedule service must be running to use the AT command."
The following query:
SELECT ARRAY[[1,2,3], [4,5,6], [7,8,9]] @> ARRAY[2, 3, 5];
gets responded with true and not false as expected, since the array[2, 3, 5]
doesn't exist in the source array. Any ideas how can it happen? Maybe flatten is applied to multidimensional arrays?
Problem
My RecyclerView displays elements with photos. Every photo is being downloaded from the Internet which may take up to few seconds. Hence, I try to avoid blocking the UI thread and I pass the work to a Handler, however, due to RecyclerView's recycling behavior, it shows the images improperly.
This is how it looks like:
Loads image 1 to list item 1.
Loads image 2 to list item 2.
I scroll down.
Loads image 3 to list item 20.
Loads image 4 to list item 21.
Loads image 4 to list item 20.
Loads image 5 to list item 21.
At the end everything is ok, but during the loading process, RecyclerView recycles the ViewHolders with the wrong images!
My code
mHandler.post(new Runnable() { @Override public void run() { final Uri image = complexFetchingFunction(); activity.runOnUiThread(new Runnable() { @Override public void run() { try { holder.imageView.setImageURI(image); } catch (Exception e) { e.printStackTrace(); } } }); } });
End
Handler works on a separate thread. That's sure. I know all these things happen, because I load the images asynchronously and RecyclerView doesn't like it, but otherwise it's painfully slow.
Does anyone have a solution?
-6960761 0I suspect that you added the System.Drawing reference to the wrong project. Please verify that the Validator.cs file in the project that has the System.Drawing reference.
-15987713 0<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="ContentPlaceHolder1"> <asp:Panel ScrollBars="Auto" runat="server"> <asp:ValidationSummary ID="ValidationSummary1" runat="server" ValidationGroup="all" /> <table border="0" cellspacing="0" cellpadding="0"> <tr align="left" valign="middle"> <td class="font_01"> From Date: </td> <td> <asp:CustomValidator ID="cvCalFrom" runat="server" ValidationGroup="all" >*</asp:CustomValidator> <uc3:Calendar ID="calFrom" DateString="" runat="server" /> </td> <td> </td> <td class="font_01"> ToDate: </td> <td> <asp:CustomValidator ID="cvCalTo" runat="server" ValidationGroup="all">*</asp:CustomValidator> <uc3:Calendar ID="calTo" DateString="" runat="server" /> </td> <td> </td> <td> </td> </tr> <tr align="left" valign="middle"> <td class="font_01"> Unique Code: </td> <td> <asp:TextBox runat="server" ID="txtCode"/> </td> <td> </td> <td class="font_01"> File Name: </td> <td > <asp:TextBox runat="server" ID="txtFileName"/> </td> <td> <asp:Button ID="Button1" runat="server" CssClass="font_01" Text="Go" Width="50px" Height="20px" onclick="btnSearch_Click" /> </td> <td> <!-- <asp:Button ID="Button2" runat="server" CssClass="font_01" Text="List All" Width="50px" Height="20px" onclick="btnListAll_Click" />--> </td> </tr> <tr valign="middle"> <td></td> <td colspan="5" > </td> <td></td> </tr> </table> </asp:Panel> <asp:UpdatePanel ID="updatePnl" runat="server" > <ContentTemplate> <CR:CrystalReportViewer Width="500px" Height="400px" ID="CrystalReportViewer1" runat="server" AutoDataBind="true" /> </ContentTemplate> </asp:UpdatePanel>
Do the change like this and remove the code for unload........
-14991880 0You could press ctrl-z (at least in Windows this works for me) but you probably don't want to do that. This would mean your program could only ever read once from the console. Better would be that you only read a line at a time rather than try to read "the whole file". Then you can just press enter to finish reading. Somthing like this:
Scanner s = new Scanner(System.in); String t = s.nextLine();
-13084811 0 Char Array contains null characters before the end I've got a class project to make a webserver in c++. Everything's been going OK until I got to the point where I needed to host images or pdfs, at which point the files were corrupted. Doing some more digging, I realized that all the corrupted images had null characters before the end.
That brings me to my question. I have a char* which I've read these files to, and I know the length of the file. I'm pretty positive that the entire file is being read in (code below), but I don't know how to print it out or send it. How can I tell C++ that I want to send the first X characters following the char*? (I'm sure the answer is somewhere here or on the web, I just can't seem to phrase my question in the right way to find the answer)
ifstream myfile (path.c_str() , ios::in|ios::binary|ios::ate); ifstream::pos_type size = myfile.tellg(); cout << size << endl; fileSize = (int) size; fileToReturn = new char [size]; myfile.seekg (0, ios::beg); myfile.read (fileToReturn, size); myfile.close(); cout << "file read\n"<< fileToReturn << endl;
For a plain text file, this would output fine. For the PDF, it only prints the first part of the file (the part before the first null character). How do I get it to print out the whole file?
EDIT: To clarify, my end goal is to send this over the web, not re-save the file.
// reply is string with all my headers and everything set. // fileToReturn is my char*, and fileSize is the int with how long it should be char* totalReply = new char [reply.length() + fileSize+1]; strcpy(totalReply, reply.c_str()); strcat(totalReply, fileToReturn); send(client, totalReply, reply.length() + fileSize, 0);
-31484763 0 For a much more sophisticated discussion of storing JSON in SQL Server as relational data and extracting it back as JSON please see this wonderful article by Phil Factor (thats the name he goes by), Producing JSON Documents from SQL Server queries via TSQL,https://www.simple-talk.com/sql/t-sql-programming/producing-json-documents-from-sql-server-queries-via-tsql/ .
Be careful about storing JSON as varchar with full text indexes or as xml type (which is not the same as JSON) with xml indexes. There can be severe performance issues when doing inserts on even a million row table so test carefully with realistic, for you, numbers of rows to see if an XML or varchar solution works for you.
If all you are going to do is stuff JSON data into varchars and back again then you should have no problems. Until the latest version of Mongo (3.04 or so) Mongo was not transactional based and one client of mine was always losing data and that caused a world of finger pointing. If the version of Mongo that you are using is not ACID compliant be very, very careful.
I am amending this answer because SQL Server 2016 now supports JSON in a big way. According to Microsoft it was one of the most requested features. Please see the following two articles:
https://msdn.microsoft.com/en-us/library/dn921897.aspx https://blogs.msdn.microsoft.com/jocapc/2015/05/16/json-support-in-sql-server-2016/
-16669438 0 Why don't you replace the @PreUpdate/@PrePersist
mechanism with a @Version
on the lastModified field ? This way all updated entity will have the field set (and only updated ones).
It should make the job as you expect if I understood well your case.
-30247683 0I'm a bit late on this but have you tried something like this?
GET /attask/api/project/search?status_mod=notnull&DE:Custom Field=0&DE:Custom Field_mod=notnull?
You usually need to give it a value before you try to modify the value from what i understand.
-40779020 0 Bootstrap hide and show div based on sidebar menu item clickedI'm new to bootstrap and still trying to familiarize myself with the available classes that I can use. So, I tried to build a sidebar but I can't get it to show only the target div
of the menu item clicked on the sidebar.
In other words, one div
at a time and not stack of div
s.
To better illustrate, here's a screenshot.
It doesn't replace the current div
, instead it just simply shows the div
then hides it on button
click. This ends up on displaying or hiding one or both of the div
s everytime I click on a menu item on the sidebar
dashboard.xhtml
<div class="container-fluid"> <div class="row"> <div class="col-sm-3 col-md-2 sidebar"> <ul class="nav nav-sidebar"> <li class="active"><a href="#">Dashboard <span class="sr-only">(current)</span></a></li> <li><a href="#customer-div" class="btn btn-default" data-toggle="collapse">Customers</a></li> <li><a href="#orders-div" class="btn btn-default" data-toggle="collapse">Orders</a></li> </ul> <ul class="nav nav-sidebar"> <li><a href="">Frames</a></li> <li><a href="">Posters</a></li> <li><a href="">About Us</a></li> <li><a href="">Users</a></li> </ul> </div> <!-- CUSTOMER --> <div id="customer-div" class="well col-xs-8 collapse"> <h1>CUSTOMER</h1> </div> <!-- END OF CUSTOMER DIV --> <!-- ORDERS --> <div id="orders-div" class="well col-xs-8 collapse"> <h1>ORDERS</h1> </div> <!-- END OF ORDERS DIV --> </div> </div>
I want one div
to replace the current div
on it's container.
I'd appreciate any help.
Thank you.
-39870154 0 MySQL Log-In with PHP - How often?Okay this might be an obvious question, but as soon as i call MySQL with PHP (whhich means i log in) and then close the PHP tag, (shown below) Do I have to call the database again later?
$mysqli = new mysqli("host", "username", "pw", "dbname"); if ($mysqli->connect_errno) { echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error; } $res = $mysqli->query("SELECT EmbedURL FROM Videos ORDER BY RAND() LIMIT 8");
etc... And then I need to call it again later in the script to fetch something else fromt he database. Do i have to log into the database again?
Thank you!
-25410847 0My mistake was implementing the delegate method:
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
instead of the one I meant to implement:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
Hence only being called on the second cell being tapped, because that was when the first cell would be de selected. Stupid mistake made with the help of autocomplete. Just a thought for those of you who may wander here not realizing you've made the same mistake too.
-5047533 0 PHP equivalent to JavaScript's string split methodI'm working with this on JavaScript:
<script type="text/javascript"> var sURL = "http://itunes.apple.com/us/app/accenture-application-for/id415321306?uo=2&mt=8&uo=2"; splitURL = sURL.split('/'); var appID = splitURL[splitURL.length - 1].match(/[0-9]*[0-9]/)[0]; document.write('<br /><strong>Link Lookup:</strong> <a href="http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/wa/wsLookup?id=' + appID + '&country=es" >Lookup</a><br />'); </script>
This script takes the numeric ID and gives me 415321306.
So my question is how can I do the same thing but using PHP.
Best regards.
-33612022 0Although it requires a 3rd party tool, these days I use curl. The -X option allows me to specify the HTTP verb. Windows has a few bash clients that allow you to run curl including Cygwin.
$ curl -H "Content-Type: application/json" -X POST -d '{value: "600"}' http://localhost:8888/my/endpoint
There's no generic method that can work with primitives, because primitives can't be a generic type. The closest you could come in pure Java is to overload getArrayList
with an int[]
...
public static ArrayList<Integer> getArrayList(int[] a){ ArrayList<Integer> retList = new ArrayList<Integer>(); for (int i : a){ retList.add(i); } return retList; }
which will box your int
for you. It's not generic, and you'd need a new overload for each primitive array type, but that's the closest solution I can think of.
I have two activities; let's say A and B. In activity A
there is a broadcast receiver registered that listens for a particular event which will finish activity A. I am registering the broadcast receiver in onCreate()
, and destroying it in onDestroy()
of activity A
.
For simplicity, there is one button
in activity B
named "Destroy Activity A". When a user clicks on button
, activity A
should be destroyed.
Normally all of this is running smoothly without any issues,but the problem occurs in following scenarios:
1) Suppose I am in activity B
and i press the Home key to move the application to the background then if i use other resource-heavy applications, Android system will kill my application to free memory. Then If I open my application from recent tasks, activity B
will be resumed, and it's onCreate()
, onResume()
etc method will be called. Now I press button
to destroy activity A
, but activity A has already been destroyed, so activity A
's onCreate()
, onResume()
etc methods will not be called until and unless i go to activity A
by pressing the back button
. Thus broadcast receiver
is not registered to listen for the event.
2) The same problem will arise when user has selected "Don't keep activities" from Developer options in the device's settings.
I have been looking to solve this issue for a long time, but i am unable to find a proper answer. What is the best way to handle this scenario? Is this an Android bug? There should be some solution for this issue.
Please help me.
-11697093 0You can avoid it when you check for new record:
unless task.new_record? #other tasks stuff end
-17626330 0 What's the difference between global var post and get_post? I use the_posts filter to add an object to each queried post. When access the added object, I get different result by using $post
or get_post
.
This is the code to attach the object to posts:
add_filter( 'the_posts', 'populate_posts_obj', 10,2 ); function populate_posts_obj( $posts, $query ){ if ( !count( $posts ) || !isset($query->query['post_type']) ) return $posts; if( in_array( $query->query['post_type'], get_valid_grade_types())){ foreach ( $posts as $post ) { if ( $obj = new Gradebook( $post->ID ) ) $post->gradebook = $obj; } } return $posts; }
Then, access the obj via $post
, sometimes get the obj, sometimes not (even when it's the same post):
function get_the_gradebook(){ global $post; return isset($post->gradebook) ? $post->gradebook : null; }
Access the obj via get_post()
, always get the obj:
function get_the_gradebook(){ global $post; $p = get_post($post->ID); return isset($p->gradebook) ? $p->gradebook : null; }
I can just use the get_post()
version, but it would be useful if I know why the difference.
If you ask the reason I attach an obj to each post, I think WordPress may take care of the caching process at the first place. Then, other caching plugins can work on my obj as if working on standard WP posts.
-28286290 0 Linux system call time() is returning ((time_t) -14) on errorThe man page man 2 time
says:
SYNOPSIS #include <time.h> time_t time(time_t *t); RETURN VALUE On success, the value of time in seconds since the Epoch is returned. On error, ((time_t) -1) is returned, and errno is set appropriately. ERRORS EFAULT t points outside your accessible address space.
I've got a simple test set up, trying to coerce an error from that function - should be the most straightforward thing ever:
time_t *ptr = (time_t *) 0xabad1dea; time_t secs = time(ptr); if (secs == ((time_t) -1)) /* Not caught */ exit(EXIT_FAILURE); printf("Number of seconds since the Epoch: %lld\n", secs); printf("It should return ((time_t) -1) on error: %lld\n", (time_t) -1); secs = *ptr; /* This *does* segfault */
For some reason, time() is returning -14 instead of -1 on my system. I'm completely stumped. Baffled, even.
I doubt anyone can reproduce this issue, but does anybody out there know why on earth I might be getting that behaviour? If so, I'm terribly curious!
EDIT: I know time isn't dereferencing the bad pointer I pass it, because that crashes the program. And the man page does say it should return -1 and set errno if the address isn't reachable. EFAULT is 14, but isn't returning -EFAULT not what time() is defined as doing here?
-34808035 0 Starting async method as Thread or as TaskI'm new to C#
s await/async
and currently playing around a bit.
In my scenario I have a simple client-object which has a WebRequest
property. The client should send periodically alive-messages over the WebRequest
s RequestStream
. This is the constructor of the client-object:
public Client() { _webRequest = WebRequest.Create("some url"); _webRequest.Method = "POST"; IsRunning = true; // --> how to start the 'async' method (see below) }
and the async alive-sender method
private async void SendAliveMessageAsync() { const string keepAliveMessage = "{\"message\": {\"type\": \"keepalive\"}}"; var seconds = 0; while (IsRunning) { if (seconds % 10 == 0) { await new StreamWriter(_webRequest.GetRequestStream()).WriteLineAsync(keepAliveMessage); } await Task.Delay(1000); seconds++; } }
How should the method be started?
new Thread(SendAliveMessageAsync).Start();
or
Task.Run(SendAliveMessageAsync); // changing the returning type to Task
or
await SendAliveMessageAsync(); // fails as of the constructor is not async
My question is more about my personal understanding of await/async
which I guess may be wrong in some points.
The third option is throwing
The 'await' operator can only be used in a method or lambda marked with the 'async' modifier
-24816135 0 you can do by adding timespan to datetime like,
TimeSpan timespan = new TimeSpan(03,00,00); DateTime time = DateTime.Today.Add(timespan); string displayTime = time.ToString("hh:mm tt");
instead of 03,00,00 you can directly pass your timespan variable
-33372276 0 Method not found: 'Void Microsoft.AspNet.Razor.CodeGenerators.GeneratedTagHelperContextI upgraded a Project from ASP.NET 5 Beta 7 to Beta 8 and I keep getting the following error which I am not able to solbe:
MissingMethodException: Method not found: 'Void Microsoft.AspNet.Razor.CodeGenerators.GeneratedTagHelperContext.set_HtmlEncoderPropertyName(System.String)'. Microsoft.AspNet.Mvc.Razor.MvcRazorHost..ctor(IChunkTreeCache chunkTreeCache, RazorPathNormalizer pathNormalizer)
I have the following packages on my project:
"Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-beta8", "Microsoft.AspNet.Razor": "4.0.0-beta8-15575", "Microsoft.AspNet.Razor.Runtime": "4.0.0-beta8-15575",
What am I missing?
-14748489 0 How to interlock divs?I would like to interlock an undefined number of divs (as in Pinterest) from this:
++++++++ ******** + + * * + + * * + + ******** + + ++++++++ ~~~~~~~~ -------- ~ ~ - - ~ ~ - - ~~~~~~~~ - - - - - - - - - - --------
to this:
++++++++ ******** + + * * + + * * + + ******** + + -------- ++++++++ - - ~~~~~~~~ - - ~ ~ - - ~ ~ - - ~~~~~~~~ - - - - - - --------
Is it possible with CSS or other stuff?
-8727381 0There is no general and explicit way to constrain vectors. The constraint will have to be enforced as an invariant of your algorithms; whenever you push_back
data to one vector, also push it to the other one. (Be sure to keep the vectors private
.
I have files that are named CULT_2009_BARRIERS_EXP_Linear.dbf
and would like to rename them to CULT_BARRIERS_EXP_Linear.dbf . The files have a date prefixed with them which is always different showing when it was captured. I have tried to replace them with regular expressions. i want to test the string if it contains numbers and then rename. I have used
if [[ $file =~ [0-9] ]]; then rename -v "s/[0-9]//g" * && rename -v s/[_]_/_/ *;
which partially works. But I would ideally like to have one rename command as it is good practice
-2041870 0Probably the easiest is getting a heap dump by VisualVM. JDK also includes related tools, as the jmap tool.
-34928877 0Well just to help other fellows I have retrieve the value of $alias using the following approach:
$alias = \Yii::$app->request->get('alias');
But definitely this is not an accurate answer of the question. I still didn't know what i am doing wrong that i didn't get the value using the approach mentioned in question.
-37210218 0I prefer to have NO extra LIBRARY PATHS in Tools Options, in every Delphi version, and to have each project have its own search path.
I prefer to have my settings exist and be the same for all build configurations. To do this, I make sure that I use the root nodes. This is unfortunately not as straightforward in Delphi 2007 since you have a Build = Debug setting and Build = Release setting, and if I remember correctly, there is no ROOT node in Delphi 2007.
For you, in Delphi 2007, you may have to pay special attention to keeping the values in the debug and the release branch the SAME manually as I believe you can't do this automatically in Delphi 2007.
To answer your question there is no need for a full path and generally no need to use $(PROJECTDIR)
. There is also no need for a full path. You need to use relative paths, like this: ..\Lib\Dir1;..\Lib\Dir2;..\Lib\Dir3
and so on. My goal for using relative paths is to satisfy the desire to check out code and build it anywhere. Code which can only be built when checked out to a certain directory (C:\YOURAPP
) is sloppy, dare I say downright lazy, as well as impractical, and also so sadly common that you might think it was a best practice. Such sloppy no-effort codebases prevent proper continuous integration practices, prevents having multiple working copies that are at different branches or major versions, and so on, and is often worked around by keeping all the code barely building in some kind of virtual machine. Nobody even knows how to set their code up, so they shove it in a VM and let the mess moulder.
When you absolutely CAN NOT use relative paths such as when you don't know where the other stuff is, you should set your OWN in house root folder variable, if your company was called ACME, I would call it ACMEROOT, and I would set it up myself. At my current company we have such a root variable we call it PS because our product's initial capitals are P and S. Then we use $(PS)
similar to the way you see $(BDS)
used in the library path.
Sometimes I find it useful to have an external tool that I have written that will set up the environment variables for me, directly writing to the IDE the environment variables that I want, and I have a practice of checking out code from version control and running this tool to set up my environment. It so happens I can now check the code onto a fresh computer and run it without any manual effort to set up packages, install components, configure library paths, or projects, and everything just builds. Unfortunately the IDE does not provide everything you need for such a practice, but there are a variety of third party tools that can provide you with a portable clean easy to build codebase.
No, you can't change the behavior of IntelliSense that way.
The issue you're facing is actually a code smell regarding your class design.
If you have certain methods that aren't of any use unless a given constructor was used, you should probably split the class so that the different functionality is clearly delineated.
It might make sense to have a base class of the common behavior and subclasses for each of the different types of constructors. This would effectively do what you're asking for, and follow proper object-oriented design.
-4066362 0Enterprise Patterns and MDA: Building Better Software with Archetype Patterns and UML
An excellent read for those looking to leverage ORM and UML
So I found the answer to my own question :
I use this :
data: 'start='+ start+$('#EventAdd').serialize(),
instead of this
data: $('#EventAdd').serialize(),start: start,
-813221 0 my libraries are in SVN, and I usually check them out for (branch them into) a project at ../libraries relative to the project. This keeps the scope of the includes dirs small and to the point.
In the real source (.pas), paths are totally forbidden.
no project related paths in global delphi searchpath (only per project, or they are truly universally shared sources/components)
I hate poluting source with hardcoded paths, so I usually have only a few units in the project, always with relative paths. Not the VSS w:\ drive substitutes hack please! Typically these are the units that pull in framework parts or are needed due to visual inheritance or form initialization.
Unfortunately, relative paths can be dangerous with Delphi, because they are relative to the working directory, which can change according to Delphi dialogs (e.g. Open). The solution is simple, have an include file with an unique name in the main project.
I have a php code running on my server that i call my web service.It processes the data in send integer value.How can i get that?Here is my request url :
NSString *requestURL=[NSString stringWithFormat:@"%@?u=%@& p=%@&platform=ios",url,txtUserName.text,txtPassword.text];
Update Comment : I have a php file on my server.It takes 3 arguments and register my users and returns value like 1(for success,2 for duplicate).I need to send request to my server as :
url="http://smwebtech.com/Pandit/web_service/signup.php?u=Test&p=password&platform=ios"
How can i send this request to server and get the return value from server?
-36710448 0I found the solution:
jasperreports-fonts
extension included in the project.The new font is a tiny bit wider, but that's okay. Other than that it looks very alike.
-5747980 0 Create Single Event ICS file with Expression EngineI'm trying to create an ICAL file based on a single entry inside an Expression Engine channel but my methods of accomplishing this are failing. I've tried the following:
$_GET
function seems to be frowned upon in EECreating a session variable with the entry ID but there seems to be no way of adding this variable to the {exp} query:
{exp:channel:entries channel="gallery" entry_id="MY_PHP_VARIABLE" limit="1" show_future_entries="yes"}
I haven't tried just making a flat file each time the single entry page is accessed with fwrite()
and linking directly to it, but that seems like a costly move.
Is there a way with PHP to make the file when I click a button? Maybe firing off a function written in the page so I don't need to pass or detect the entry_id
?
DefaultTableCellRenderer
inherit from JLabel
(that inherit from JComponent
). So you can change the JLabel properties within getTableCellRendererComponent
.
ImageIcon icon = new ImageIcon(getClass().getResource("images/moon.gif"));// prepared before public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { setText((String)value); setIcon(icon); return this; }
setText
come from the super JLabel class and setIcon
from the super JComponent class.
Almost all DefaultTableCellRenderer
methods override method from these classes.
Why not try something like this:
foreach (var file in System.IO.Directory.GetFiles(k)) { zip.AddFile(file); }
To get the directories and files to an unlimited depth, combine that with a recursion method based on System.IO.Directory.GetDirectories("path")
- should be pretty straightforward methinks.
I see base64_encode
can encode values, but without a key. I need a function that takes a salt and data, encodes it, and can be decoded with the same salt (but if you try to decode it without the salt, it gives you gibberish).
Is there a PHP function for this (can't find it, only modified versions of base64_encode
).
EDIT: Found the answer: use mcrypt ciphers
-9320568 0 ViewState vs cookies vs cashing vs sessionsWhen we are using ViewState or cookies or cashing or sessions where are we storing the information? I know when we use sessions we can store data in sql server or web server. is there any other way we store data when we are using sessions.
One more questions when i get the data from sql server and bind it to the dataset or datatable where that data is going to store(the dataset records)?
-28986042 0 PHP, SOAPClient: Cannot find dispatch methodThis is my WSDL XML: (Generated with SoapUI)
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://soap.test.com/"> <soapenv:Header/> <soapenv:Body> <ser:myMethod> <user> <id>?</id> <name>?</name> </user> <code>?</code> </ser:myMethod> </soapenv:Body> </soapenv:Envelope>
And my PHP code to consume the "myMethod" method:
$opts = array( 'location' => 'http://example.com/myServices?WSDL', 'uri' => 'http://soap.test.com' ); $client = new SOAPClient(null, $opts); $res = $client->__soapCall('myMethod', array( "id" => "123", "name" => "Sam" )); var_dump($res);
And I get the Cannot find dispatch method for {http://soap.test.com} myMethod
error.
I've tested the SOAP with SoupUI and it has responsed correctly.
What is wrong here?
-14038475 0 Is using hard-coded integer values in code a BAD practice from memory considerationsConsider a simple following code in Java:
void func(String test) { if(str.length() > 0) { //do something } }
Does executing str.length() > 0 means that every time this function is called, 4 bytes of memory will be allocated to store 0 integer value ?
-29438912 0 Submit form requires more than one click in IEPlease find below file code where multiple file upload functionality is given. On click of upload link it opens input file browser window where we select file and then click on submit.
In chrome, submit button submits the form on first click but In IE, it does not submit the form on first click.
In IE, If we select one file using upload link then submit button submits the form in second click.
If we select two file then it submits the form in 3rd click and accordingly.
Please let me know how to stop this event chain to submit in one click.
Please find below test.html file as,
https://www.dropbox.com/s/o7dwxhjnegxo0fo/Test.html?dl=0
-11344111 0In a nutshell:
LINQ is a quering technology (Language Integrated Query). LINQ makes extensive use of lambda's as arguments to standard query operator methods such as the Where clause.
A lambda expression is an anonymous function that contain expressions and statements. It is completely separate and distinct from LINQ.
-40066095 0 undefined method `empty?` for nil:NilClassWhen I was trying to run rake db:migrate on this open source project called expertiza (link:https://github.com/expertiza/expertiza), I got this error message. The full message is showing below. I think the problem is probably something wrong with the environment set up. Is there any way to fix this bug without changing the code?
Error message:
rake aborted! StandardError: An error has occurred, all later migrations canceled: undefined method `empty?' for nil:NilClass /home/maxinghua/expertiza/app/models/menu.rb:81:in `initialize' /home/maxinghua/expertiza/app/models/role.rb:87:in `new' /home/maxinghua/expertiza/app/models/role.rb:87:in `rebuild_menu' /home/maxinghua/expertiza/app/models/role.rb:73:in `block in rebuild_cache' /home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/relation/batches.rb:51:in `block (2 levels) in find_each' /home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/relation/batches.rb:51:in `each' /home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/relation/batches.rb:51:in `block in find_each' /home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/relation/batches.rb:124:in `find_in_batches' /home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/relation/batches.rb:50:in `find_each' /home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/querying.rb:9:in `find_each' /home/maxinghua/expertiza/app/models/role.rb:67:in `rebuild_cache' /home/maxinghua/expertiza/db/migrate/002_initialize_custom.rb:184:in `up' /home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:571:in `up' /home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:611:in `exec_migration' /home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:592:in `block (2 levels) in migrate' /home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:591:in `block in migrate' /home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/connection_adapters/abstract/connection_pool.rb:292:in `with_connection' /home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:590:in `migrate' /home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:768:in `migrate' /home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:998:in `block in execute_migration_in_transaction' /home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:1046:in `ddl_transaction' /home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:997:in `execute_migration_in_transaction' /home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:959:in `block in migrate' /home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:955:in `each' /home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:955:in `migrate' /home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:823:in `up' /home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:801:in `migrate' /home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/tasks/database_tasks.rb:137:in `migrate' /home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/railties/databases.rake:44:in `block (2 levels) in <top (required)>' /home/maxinghua/.rvm/gems/ruby-2.2.4/gems/airbrake-5.5.0/lib/airbrake/rake/task_ext.rb:19:in `execute' /home/maxinghua/.rvm/gems/ruby-2.2.4/gems/rake-11.2.2/exe/rake:27:in `<top (required)>' /home/maxinghua/.rvm/gems/ruby-2.2.4/bin/ruby_executable_hooks:15:in `eval' /home/maxinghua/.rvm/gems/ruby-2.2.4/bin/ruby_executable_hooks:15:in `<main>' NoMethodError: undefined method `empty?' for nil:NilClass /home/maxinghua/expertiza/app/models/menu.rb:81:in `initialize' /home/maxinghua/expertiza/app/models/role.rb:87:in `new' /home/maxinghua/expertiza/app/models/role.rb:87:in `rebuild_menu' /home/maxinghua/expertiza/app/models/role.rb:73:in `block in rebuild_cache' /home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/relation/batches.rb:51:in `block (2 levels) in find_each' /home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/relation/batches.rb:51:in `each' /home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/relation/batches.rb:51:in `block in find_each' /home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/relation/batches.rb:124:in `find_in_batches' /home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/relation/batches.rb:50:in `find_each' /home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/querying.rb:9:in `find_each' /home/maxinghua/expertiza/app/models/role.rb:67:in `rebuild_cache' /home/maxinghua/expertiza/db/migrate/002_initialize_custom.rb:184:in `up' /home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:571:in `up' /home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:611:in `exec_migration' /home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:592:in `block (2 levels) in migrate' /home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:591:in `block in migrate' /home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/connection_adapters/abstract/connection_pool.rb:292:in `with_connection' /home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:590:in `migrate' /home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:768:in `migrate' /home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:998:in `block in execute_migration_in_transaction' /home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:1046:in `ddl_transaction' /home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:997:in `execute_migration_in_transaction' /home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:959:in `block in migrate' /home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:955:in `each' /home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:955:in `migrate' /home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:823:in `up' /home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/migration.rb:801:in `migrate' /home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/tasks/database_tasks.rb:137:in `migrate' /home/maxinghua/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active_record/railties/databases.rake:44:in `block (2 levels) in <top (required)>' /home/maxinghua/.rvm/gems/ruby-2.2.4/gems/airbrake-5.5.0/lib/airbrake/rake/task_ext.rb:19:in `execute' /home/maxinghua/.rvm/gems/ruby-2.2.4/gems/rake-11.2.2/exe/rake:27:in `<top (required)>' /home/maxinghua/.rvm/gems/ruby-2.2.4/bin/ruby_executable_hooks:15:in `eval' /home/maxinghua/.rvm/gems/ruby-2.2.4/bin/ruby_executable_hooks:15:in `<main>' Tasks: TOP => db:migrate (See full trace by running task with --trace)
This is the reported empty?
method Code in menu.rb:81:in initialize
:
if role unless role.cache[:credentials].permission_ids.empty? items = MenuItem.items_for_permissions(role.cache[:credentials].permission_ids) end else # No role given: build menu of everything items = MenuItem.items_for_permissions end
-12844095 0 How do I use Bash to create a copy of a file with an extra suffix before the extension? This title is a little confusing, so let me break it down. Basically I have a full directory of files with various names and extensions:
MainDirectory/ image_1.png foobar.jpeg myFile.txt
For an iPad app, I need to create copies of these with the suffix @2X appended to the end of all of these file names, before the extension - so I would end up with this:
MainDirectory/ image_1.png image_1@2X.png foobar.jpeg foobar@2X.jpeg myFile.txt myFile@2X.txt
Instead of changing the file names one at a time by hand, I want to create a script to take care of it for me. I currently have the following, but it does not work as expected:
#!/bin/bash FILE_DIR=. #if there is an argument, use that as the files directory. Otherwise, use . if [ $# -eq 1 ] then $FILE_DIR=$1 fi for f in $FILE_DIR/* do echo "Processing $f" filename=$(basename "$fullfile") extension="${filename##*.}" filename="${filename%.*}" newFileName=$(echo -n $filename; echo -n -@2X; echo -n $extension) echo Creating $newFileName cp $f newFileName done exit 0
I also want to keep this to pure bash, and not rely on os-specific calls. What am I doing wrong? What can I change or what code will work, in order to do what I need?
-9972704 0a few notes / pointers about doing this in python.
v1
is already sorted (e.g. name
and enemy
will collide after disenvoweling).translate(None, "aeiouyAEIOUY")
on the string.["aaa", "aaA", "aAa", "aAA"]
etc. and if this is not enough "incrementing" characters starting from the end, until a non-colliding identifier is found, eg. ["aa"]*7
would become ["aa", "aA", "Aa", "AA", "ab", "aB", "Ab"]
In C# you can do DateTime.MinValue, but is there any method for this in JavaScript or HTML?
I am aware of Date(-number)
in JavaScript, but the constants for number
that I can find are all too big, and there doesn't seem to be a max/min value
I have read nothing but good things about PHP's PDO library. Today in my reading I came across this link that says Oracle discourages the use of PDO when accessing Mysql. The comment stated that PDO doesn't offer access to all the features that Mysql has to offer.
My question is this:
You can import foo.less
as a reference, like so:
@import (reference) "foo.less";
The code will be available for referencing variables, mixins, etc., but will not compile to css output.
-38252099 0The issue here is: You are using your ID for the elements in a while-loop. So you end up having multiple IDs in your document, which is invalid. So jQuery will always get the first one.
I would suggest the following:
onClick
-handler and use a proper event-handlerclass
- selector instead of IDusrid
-value to the element your are clicking onYour code would be as follows:
HTML
<input type='text' class='hidden' name='usridl' id='usrid' value='".$staff_data['id']."' /> <a href='javascript:void(0);' class='delete-row' id='dltbutton' name='btn-dlt' data-usrid='".$staff_data['id']."'><i class='fa fa-trash red'></i></a>
JS
$('.delete-row').on('click', function(){ if(confirm("Do you really want to delete record ?")) { var usrid = $(this).data('usrid'); //all your other stuff } });
for
is indeed mostly just sugar for each
(Try using for
on a non enumerable object - it should complain about it not responding to each). It differs in that it doesn't create block scope.
How each
is implemented depends on the object you are calling it on (each is the method on which all of Enumerable is built). In any case the block will be called with a succession of values. Reassigning the block variable that is yielded does nothing - upon the next iteration i
is set to whatever the next value should be.
You can skip with next
or terminate with break
but that's it as far as controlling the iteration goes - there's no way of saying "jump forwards 3"
I don't like static
data members much, the problem of initialization being foremost.
Whenever I have to do significant processing, I cheat and use a local static
instead:
class MyClass { public: static const SomeOtherClass& myVariable(); }; const SomeOtherClass& MyClass::myVariable() { static const SomeOtherClass MyVariable(someOtherFunction()); return MyVariable; }
This way, the exception will be throw only on first use, and yet the object will be const
.
This is quite a powerful idiom to delay execution. It had a little overhead (basically the compiler checks a flag each time it enters the method), but better worry about correctness first ;)
If this is called from multiple threads:
boost::once
in the Boost.Threads
libraryconst
, you may not care if it's initialized multiple times, unless someOtherFunction
does not support parallel execution (beware of resources)Guideline: only use static
or global
variables instantiation for simple objects (that cannot throw), otherwise use local static
variables to delay execution until you can catch the resulting exceptions.
I have two xmltype tables (object-relation storage) in Oracle 10gR2. My steps:
#1 register schema
begin dbms_xmlschema.registerSchema( 'tab1_schema.xsd', '<?xml version="1.0" encoding="utf-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="man"> <xs:complexType> <xs:sequence> <xs:element name="man_id" type="xs:int" /> <xs:element name="man_name" type="xs:string" /> <xs:element name="man_date" type="xs:date" /> <xs:element name="cars"> <xs:complexType> <xs:sequence> <xs:element maxOccurs="unbounded" name="car"> <xs:complexType> <xs:sequence> <xs:element name="car_id" type="xs:int" /> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>', true, true, false, false); end; / begin dbms_xmlschema.registerSchema( 'tab2_schema.xsd', '<?xml version="1.0" encoding="utf-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="car"> <xs:complexType> <xs:sequence> <xs:element name="car_id" type="xs:int" /> <xs:element name="car_name" type="xs:string" /> <xs:element name="car_date" type="xs:date" /> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>', true, true, false, false); end; /
#2 create xmltype tables
create table tab1 of xmltype xmlschema "tab1_schema.xsd" element "man"; create table tab2 of xmltype xmlschema "tab2_schema.xsd" element "car";
#3 add primary keys
alter table tab1 add constraint tab1_pk primary key (xmldata."man_id"); alter table tab2 add constraint tab2_pk primary key (xmldata."car_id");
#4 QUESTION! How add foreign key for table tab1 (element "/cars/car/car_id") references on table tab2 (element "/car_id")
alter table tab1 add constraint tab1_fk foreign key (xmldata."/cars/car/car_id") references tab2(xmldata."car_id");
-37640586 0 You can combine the Where
and the FirstOrDefault
, as FirstOrDefault
allows you to specify a predicate. This will save you going through the entire list only to take the first, if it's there. Then you use the null coalescing operator ??
, which will only evaluate the right side if the left side is null:
WordForm wordForm = db.WordForms .FirstOrDefault(w => w.Definition == result.definition) ?? addWordForm(result, word);
-23200836 0 Unfortunately, it is illegal to reference a variable/param in a match pattern in XSLT 1.0. However, you can reference your $lang
parameter any time you apply templates. So, for example, in the root template (i.e. a template that matches /
or some other sufficiently top-level node), you could specify that you only want to apply templates to elements that have an xml:lang
attribute equal to the value of your param (or no xml:lang
at all):
<xsl:apply-templates select="*[not(@xml:lang) or @xml:lang=$lang]" />
This won't process any undesired elements and no other templates need to specify the language to match.
-6727570 0ColumnAttribute with IsPrimaryKey=true missing in EmployeePhoneNumber
-24728748 0There are somethings that can help a lot here. First opening a second window can be a painful experience both for the user and the programmer. Unless you have an absolute need I would recommend manipulating the current window's DOM to display a popup instead.
Next if you can use DOM methods to change the page contents. document.write
comes with a lot of problems which in your case are not apparent. Mainly it can erase you current DOM. You don't notice this in your example because the new window is blank so rewriting it is incidental.
Finally your use of allInfo
is a quirky way to reference a global variable. It is not easily understood that this is happening from the style of code. In fact any linter will throw an error for your use of the global and will case an error if you declare "use strict"
in your functions. Best to learn the good coding practises way.
Since we will want to interact with a variable (allInfo
) in your case we should encapsulate the value in an object. This object can hold the state of that reference and offer some abstracted interactions with it. By doing so you avoid polluting the global name space and allow you to swap out your implementation without having to rewrite the parts of your program that depend on it.
// Our welcome window object function WelcomeWindow() { // save a reference to the content of your new window // to be printed when ready. (Lazy execution) this.innerHTML = ''; } WelcomeWindow.prototype.open = function() { this.win = window.open("", "displayWindow"); return this; }; WelcomeWindow.prototype.close = function() { this.win.close(); return this; }; WelcomeWindow.prototype.write = function(html) { this.innerHTML += '' + html; return this; }; WelcomeWindow.prototype.render = function() { if (!this.win) { throw new Error("window has not been opened yet."); } this.win.open(); this.win.write('<!doctype html><html><head><link rel="stylesheet" type="text/css" href="mystyle_invite.css"><title>Resume</title><meta charset="utf-8"> </head><body>'); this.win.write(this.innerHTML); this.win.write('</body></html>'); this.win.close(); return this; };
This allows us to declaratively manipulate the window before it is opened. For example if we want to add the name to the window:
function NameField(id) { this.element = document.getElementById(id); } NameField.prototype.toString = function() { var name = this.element.value; switch (name) { case 'Michael': return 'Mr. Michael'; case 'Sam': return 'Mrs. Sam'; default: return 'Sir ' + name; } }; NameField.prototype.toHtml = function() { return '<strong>' + this.toString() + '</strong>'; };
Linking it together using code instead because adding events into the DOM only confuses the separation of markup and code.
window.onload = function() { var form = document.getElementById('infoForm'); form.onsubmit = function(e) { e.preventDefault(); var name = new NameField('firstName'); new WelcomWindow() .write(name.toHtml()) .open() .render(); return false; }; };
-13247951 0 try this
for (NSDictionary *status in statuses) { NSString *Tstatus = [status objectForKey:@"TStatus"] if([Tstatus isEqualToString:@"100001"){ //Do your code here } }
Refer this More about json
-1570792 0 Where can I find information on how to customize the user registration process of Liferay + Sun Web Space PortalI need to quickly customize the user registration form of the liferay/web space portal? Have not found any direct information on this so would appreciate any tips.
-37404996 0 NavigationController title doesn't appear swift/storyboardThis is my story board. I want to set the ttitle for this FrontViewController
So I did this in my FrontViewController
override func viewDidAppear(animated: Bool) { super.viewDidAppear(true) self.navigationController!.navigationBar.topItem!.title = "Home"; }
I have also tried:
self.title="Home" self.navigationItem.title = "Home"
But it doesn't set any title. Why is that? Pleasehelp me. Thanks
-18986357 0Select columns, join tables by order_id, order by Status_Priority
-15916045 0I usually pronounce it as "lambda x to y". This is very short and matches how you would type it in TeX: \lambda x \to y
. (As a cute note, I have a TeX input mode in my editor, so I could type the above to get λ x → y
. :P)
That said, I'm sure that everyone would understand you if you said "lambda x dot y"--most people are at least familiar with that notation and the it's very easy to guess what you mean from context.
I've never heard anybody say "goes to", however.
-11928362 0Maybe you are looking at the wrong place. Check here, you will understand how to use a select
tag in jquery grid.
You can't do it with a LINQ join, basically - LINQ only directly supports equijoins.
You can however do:
var query = from trip in db.Trips from driver in db.Drivers where trip.DriverId == driver.DriverId || trip.CoDriverId == driver.DriverId select new { driver.DriverId, trip.TripId };
That may well end up with the same join in the converted SQL.
-2919227 0This answer may shed some light. How do you sort a dictionary by value?
They sort by value but could the linq statement be altered to sort by key?
-3759649 0Will work. but might have some performace issues on Editor / Designer. I had a machine with almost similar configuration. used it for silverlight developement. I always has problem in the design preview of the XAML file. - it gets loaded after some time then expected time.
-7118747 0 Change rails view output from helperI have rails helpers (hs_if
, hs_else
):
= hs_if :current_user do Hello, {{ current_user/name }}! = hs_else do = link_to 'Sign In', sign_in_path
...which produces handlebars templates:
{{#if current_user}} Hello, {{ current_user/name }}! {{else}} <a href="/signin">Sign In</a> {{/if}}
How can I render {{#if current_user}} ... {{else}} ... {{/if}}
without nesting hs_else
in hs_if
?
I think I should remove {{/if}}
from output, but I can't find way to do it in helper.
It is hard to help unless you post a bit more detail and some code. Without that here are some suggestions that might help.
You will need a submit button or some JavaScript to post the form inside the partial. If you have another form on the page which you are submitting, it will not include data from other forms and inputs on the page.
Also to form has to post back to a controller action, a partial just a helper to render a view inside another view.
-14081491 0I wait for response from server for 1 second and check for it in console but [...]
Changing the model manually (click the button using your mouse) instead of programmatically (click()
) is the crucial part here.
I assume you do not return the final model from your server, as Backbone update's your model with that data.
See section 53 and
if (options.wait) { if (attrs && !this._validate(attrs, options)) return false; current = _.clone(this.attributes); }
options.success = function(resp, status, xhr) { done = true; var serverAttrs = model.parse(resp); if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs); if (!model.set(serverAttrs, options)) return false; if (success) success(model, resp, options); };
of the Backbone.js documentation. Especially these lines:
var serverAttrs = model.parse(resp);
(Parse model data from response)
if (!model.set(serverAttrs, options)) return false;
(Update your model's attributes)
When your first code (the one where you click()
the buttons) runs, it increases your models attribute and loggs it before the server returns. Thats
Note: using the wait
option or a setTimeout()
in your 2nd press of button three in your first code would equal the behaviour.
But what you want, is to return a valid model from your server (after persisting it).
Off topic tip: you should not bind your model and your view in the models initialize
r or constructor
as it would couple them too tight and they wouldn't be interchangable. (For this question, it is certainly acceptable. ;)
You can debug with the library installed on your host, provided the debugging machine is also the development machine. In that case, you use set sysroot instead of set sysroot-on-target. For example :
set sysroot /home/username/.../rootfs/
where /home/username/.../rootfs/
contains a copy of your target filesystem
I think you should also specify /
instead of /lib
No. You see, switch
statements are for comparing many different values of the same type for a match to a certain other value.
A switch
statement is formed like this:
switch (var){ case 5: //var == 5 break; case 10: //var == 10 break; default: //var is not 5 nor 10 break; }
Which only allows comparisons to constant values, thus making it useless towards data types. An if statement is a much better choice for this purpose, as the only solution for using a switch statement (getting the instance name and comparing it in that format) would be writing too much extra (and unnecessary) code that is not needed and can more easily be done in another manner.
-27217764 0When you add the content you are doing it in the wrong order:
contents.add(chickP); contents.add(numChick); contents.add(fishP); contents.add(burgerP); contents.add(numFish); contents.add(numBurger);
Move numFish up.
-15966295 0Use this code to copy textarea values
clonedObject.find(textareaObject).val(originalObject.find(textareaObject).val());
-35579637 0 Gap in auto-increment IDs on Heroku Postgres I've got a Ruby web app running on Heroku with a Postgres database. I've noticed the auto-incremented IDs have a gap in them around the time that the Postgres database was under "maintenance" by Heroku.
The gap is a one-time thing, and then the IDs increment by 1 again. Like so:
ID | Created at | 2959 | 2016-02-14 21:07:05.149797 | 2960 | 2016-02-14 21:15:05.03284 | 2961 | 2016-02-14 22:59:19.634962 | 2994 | 2016-02-15 09:25:30.969881 | 2995 | 2016-02-15 09:44:38.49678 | 2996 | 2016-02-15 09:51:00.282624 |
The maintenance by Heroku happened in between the two records (2961
and 2994
) being created, at 2016-02-15 04:00:00
.
I've seen an explanation that a failed transaction will result in an ID being skipped over on the next successful commit, but I can't see anything in the application logs to indicate that any records were being created around the time.
-679976 0 Large dataset (SQL to C#), long load time fixI have a site I'm building, it's an application that creates mail merges (more or less...) based on a couple of user preferences. It can generate Cartesian joins worth of data without a problem, but in comes the needs of enterprise to make life a bit more difficult...
I have to build the application so that, after verifying zip codes of remote employees, it creates emails to media targets based on how far from that employee the media target is. Let's say for instance employees are well known volunteers where they work. The enterprise wants to email media within a 5 mile radius of these employees a message about the work the employee is doing. This is where things get messy... I have several choices here, which I will outline the attempts and the failures:
The largest radius is 20 miles. I create a database table that holds records of every zip code in the US, joined to every zip code within 20 miles of that zip code. The dataset looks something like (The names are different this is for the sake of argument):
[SourceZip] | [City] | [State] | [CloseZip] | [City] | [State] | [Distance]
Fails: As an example, NY has 350k records from the above dataset (and other states are worse!). Average load time on that page? 6 minutes... Not happening. I verified this by setting breakpoints, it is during the dataadapter.fill() stage that the disconnect occurs.
(This one was never implemented due to a logistics problem) I make a database connection for each employee zip to media target zips with a distance of x or less. Except that the source files and the media targets combined can reach upwards of 34k individualized emails. 34k DB connections? even if I could devise a way to reuse zip code searches, I did some test checks in the DB and found that there are 500 distinct zip codes in NY where employees worked. 500 db connections? I doubt that would work but I could be surprised.
My latest scheme to get around the problem is in that hoping the web server runs a better game then the .net dataset object by getting a new dataset looks like:
[zip] | [longitude] | [latitude]
Then doing a distance formula to figure out if the data works. This relies heavily on the processors on the web server. Is this a worthwhile gamble, or will I find the same load time damage on this attempt as well?
Is there a better way?
I appreciate any input, even if it confirms my fears that this project just might not work.
Additional notes: I don't have control of the server, and I'm running SQL2k :(. I'm programming the site in visual studio 2005, framework 2.0. Might get upgraded to SQL2005 and VS2008 within the next few months though.
-34920853 0You need to use System.Messaging.Message.CorrelationId
property.
Gets or sets the message identifier used by acknowledgment, report, and response messages to reference the original message.
Source: https://msdn.microsoft.com/en-us/library/system.messaging.message.correlationid(v=vs.110).aspx
var msgToSend = new Message(); // ... set message props including admin queue var targetQueue = new MessageQueue(...); targetQueue.Send(msgToSend); // Read acknowledgment var adminQueue = new MessageQueue(ackPath); var msgAck = adminQueue.ReceiveByCorrelationId(msgToSend.Id, new TimeSpan(0, 0, 2)); if (msgAck) { return msgAck.Acknowledgment; }
There is PeekByCorrelationId
method too, or overload forms of ReceiveByCorrelationId
which you should check for more information.
With the advent of dynamic parallelism in 3.5 and above CUDA architectures, is it possible to call linear algebra libraries from within __device__
functions?
Can the CUSOLVER library in CUDA 7 be called from a kernel (__global__
) function?
Using the following dataset:
temp <- structure(list( GENDER = structure(c(1L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 2L, 2L), .Label = c("F", "M"), class = "factor"), EVERFSM_6 = c(0L, 0L, 0L, 1L, 0L, 1L, 0L, 1L, 0L, 1L), `0001` = c(0, 11, 22, 33, 33, 55, 66, 77, 88, 0), n = c(20L, 13L, 4L, 13L, 36L, 94L, 28L, 50L, 27L, 1L)), .Names = c("GENDER", "EVERFSM_6", "0001", "n"), class = c("tbl_df", "data.frame"), row.names = c(NA, -10L))
And I'm trying to perform the following spread_ operation to summarise the data:
DiscID <- "0001" colID <- as.name(DiscID) cols <- c("GENDER", colID, "n") gender_results <- temp %>% select_(.dots=cols) %>% group_by_(.dots=cols[1:2]) %>% summarise(gender_n = sum(n)) %>% spread_(paste0("`",DiscID,"`"), "gender_n") %>% rename(type = GENDER)
But it says:
Error: Key column '`0001`' does not exist in input.
I'm having to use the _ version of select_, group_by_ and spread_ as I am using a variable to refer to column names. The desired output is below, achievable by using the hard coded:
spread(`0001`, gender_n) %>% type 0 11 22 33 55 66 77 88 (fctr) (int) (int) (int) (int) (int) (int) (int) (int) 1 F 20 13 4 36 94 28 NA NA 2 M 1 NA NA 13 NA NA 50 27
-31003874 0 Using Azure management Libraries for deploying a service. Error: "The given path's format is not supported." Here is the code which I am using for deploying a service in Azure,
internal async static Task DeployCloudService(this SubscriptionCloudCredentials credentials) { try { using (var _computeManagementClient = new ComputeManagementClient(credentials)) { Console.WriteLine("Deploying a service..."); var storageConnectionString = await GetStorageAccountConnectionString(credentials); var account = CloudStorageAccount.Parse(storageConnectionString); var blobs = account.CreateCloudBlobClient(); var container = blobs.GetContainerReference(ConfigurationManager.AppSettings["containerName"]); if (!container.Exists()) { Console.WriteLine("Container not found"); }; await container.SetPermissionsAsync( new BlobContainerPermissions() { PublicAccess = BlobContainerPublicAccessType.Container }); var blob = container.GetBlockBlobReference( Path.GetFileName(ConfigurationManager.AppSettings["packageFilePath"])); var blob1 = container.GetBlockBlobReference( Path.GetFileName(ConfigurationManager.AppSettings["configFilePath"])); await _computeManagementClient.Deployments.CreateAsync(ConfigurationManager.AppSettings["serviceName"], DeploymentSlot.Production, new DeploymentCreateParameters { Label = ConfigurationManager.AppSettings["label"], Name = ConfigurationManager.AppSettings["serviceName"], PackageUri = blob.Uri, Configuration = File.ReadAllText((blob1.Uri).ToString()), StartDeployment = true }); Console.WriteLine("Deployment Done!!!"); } } catch (Exception e) { throw; } }
The Idea is that package and config file is already there in blobs within some container and I can deploy my service when I am using Configuration = File.ReadAllText(ConfigurationManager.AppSettings["configFilePath"])
(which takes the file from the local path and working fine as expected), but since I don't wanna do that I am trying to use the config file from Azure blobs, but File.ReadAllText
is not taking the Uri of my file which I checked is fine and giving System.SystemException {System.NotSupportedException}
withbase {"The given path's format is not supported."}
.(as its looking for string parameter)
-22447062 0 How do I create a CocoaPods podspec that has a dependency that exists outside of Specs?My Question is that how can we use the config file (.cscfg) from the server
I have a public fork of a library that already exists in CocoaPods/Specs. In a Podfile, I can reference this forked pod by doing this:
pod 'CoolLibrary', :git => 'git@github.com:myname/CoolLibrary-Forked.git', :commit => 'abcdef1234567890abcdef1234567890'
I tried putting this in my MyLibrary.podspec
:
s.dependency 'CoolLibrary', :git => 'git@github.com:myname/CoolLibrary-Forked.git', :commit => 'abcdef1234567890abcdef1234567890'
But get the following error message:
-> MyLibrary.podspec - ERROR | The specification defined in `MyLibrary.podspec` could not be loaded. [!] Invalid `MyLibrary.podspec` file: [!] Unsupported version requirements. Updating CocoaPods might fix the issue.
Is it possible to specify a dependency in a .podspec in this way (i.e. for a pod that has a podspec, but which isn't in CocoaPods/Specs)?
-40648993 0 "grunt tests” task throws error as Fatal error: spawn EACCEScommand 'grunt tests'
throws following errors:
Running "tests" task (node:956) DeprecationWarning: process.EventEmitter is deprecated. Use require('events') instead.
Running "karma:unit" (karma) task INFO [karma]: Karma v0.12.37 server started at http://localhost:9876/ INFO [launcher]: Starting browser Firefox Fatal error: spawn EACCES
i have following setup: FIREFOX_BIN=/usr/bin -- where firefox exists
and have following grunt tools installed on Centos 6. grunt-cli v1.2.0 grunt v0.4.5
-31983292 0Angular is having normal url as href:mailto as whitelist. But few attribute need to loaded from the security point of view. To start an IM through angular we need to add sip to whitelist like this
var app = angular.module( 'myApp', [] ) .config( [ '$compileProvider', function( $compileProvider ) { $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|sip|chrome-extension):/); } ]);
It will add sip to whitelist and the Lync application will start when clicked in the Icon. This change is to be made in app.js.
-40383333 0you only have configured what pathes to use you should create a task like so:
grunt.task({ // Do Stuff here })
There is more information on grunt tasks here: http://gruntjs.com/api/grunt.task
-20084006 0 MS Access / SQL : Invalid Use of PropertyThe code below is supposed to insert a new record into the transactions table. However, it results in a compile erro "Invalid Use of Property" on the SET QDF line. What could cause such an error?
Private Sub cmdCharge_Click() Dim vblMealType As String Dim vblMealQual As String Dim dbs As DAO.Database If txtMealID.ItemsSelected.Count = 0 Then MsgBox "Please Select a Meal Type", _ vbOKOnly + vbInformation Else MsgBox "Customer Charge Succesfull.", _ vbOKOnly + vbInformation Set dbs = CurrentDb Dim QDF As DAO.QueryDef QDF = dbs.CreateQueryDef("", _ "PARAMETERS prmCustomerID Text(255), prmMealID Text(255), prmTransactionAmount Currency, prmTransactionDate Text(255);" & _ "INSERT INTO dbo_Transactions (CustomerID, MealID, TransactionAmount, TransactionDate) " & _ "VALUES ([prmCustomerID], [prmMealID], [prmTransactionAmount], [prmTransactionDate])") QDF!prmCustomerID = txtCustomerID.Value QDF!prmMealID = txtMealID.Value QDF!prmTransactionAmount = txtCharge.Value QDF!prmTransactionDate = Date QDF.Execute dbFailOnError MsgBox "Customer Charge Succesfull.", _ vbOKOnly + vbInformation Set QDF = Nothing Set dbs = Nothing DoCmd.OpenForm "Charge Form" DoCmd.Close acForm, Me.Name End If End Sub
-1383838 0 I used this article, on javaworld when I first started JDBC programming. And may I suggest using pure Java DB's or MySQL's or Oracle's personal editions unless you have a specific need for MS Access.
-9435266 0You can use the :path
option for that,
resources :posts, :path => "/my-dir/posts"
Check out this guide for more information.
-40617115 0SQL strings should use single quotes:
sqlContext().sql("SELECT *, '\"' AS quoteCol FROM tempdf");
-14973356 0 Displaying list of data from online text file in Android App Inventor I'm trying to create a little weather app for home weather station. The weather station outputs a .txt file on an ongoing basis and I'm trying to make an android application using app inventor to read the data in the file and display it appropriately.
File is located here: http://uregina.ca/~hodder2k/realtime.txt
I am able to load the entire string into the application, but I haven't figured out a way to read and label certain columns of data within the file (ex. temperature etc).
Can this be done in App Inventor? Or should I try and switch to using the Android SDK?
Thanks
-35478154 0The problem was that the below variables initialization code was never getting executed:
env.shell = '/bin/ksh' env.user = config.user_app2 env.password = config.password_app2
Creating an init function that had the above lines and running that function before any others like execute() worked.
-39262346 0Why not design your date column as date ?
If you want to keep your current design, try this:
SELECT * FROM tbl_produce WHERE status = 0 AND concat(years, if(months > 9, months, concat('0', months))) BETWEEN '201512' AND '201608'
OR
SELECT * FROM tbl_produce WHERE status = 0 AND ( (years = 2015 AND months = 12) OR (years = 2016 AND months < 9) )
-12644292 0 First, you are right, you get value of 0, because the screen didn't draw yet when you try to get the button width
.
As I see it, the only possibility to do it like you want, is to give them pre defind value in the XML file.
For example:
<Button android:id="@+id/b1" android:layout_width="25dip" android:layout_height="25dip" android:gravity="center" />
Set the width and height programmally:
DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); btnWidth = metrics.heightPixels/3 - 50;//gap btnHeight = btnWidth; Button b1 = (Button) findViewById(R.id.b1); b1.setHeight(btnWidth); b1.setWidth(btnWidth);
-38727168 0 Try this
If Right(Field2, 3) = "A-1" Or _ Right(Field2, 3) = "A-2" Or _ Right(Field2, 3) = "B-1" Or _ Right(Field2, 3) = "B-2" Or _ Right(Field2, 3) = "C-1" Or _ Right(Field2, 3) = "C-2" Or _ Right(Field2, 3) = "D-1" Or _ Right(Field2, 3) = "D-2" Or _ Right(Field2, 3) = "D-3" Then Cells(i, 50).Value = "OtherPrtnrs /Dcrs & Dept heads" End If
Or better still... this
Select Case Right(Field2, 3) Case "A-1","A-2","B-1","B-2","C-1","C-2","D-1","D-2","D-3" Cells(i, 50).Value = "OtherPrtnrs /Dcrs & Dept heads" End Select
Note: I am assuming that i
is a valid row number
Explanation:
When comparing using an If
statement, you cannot say If A = B or C
. You are supposed to compare is separately. If A = B or A = C Then
. Here each OR
is its own Boolean
statement i.e it will be evaluated separately.
When you have multiple such comparisons, it is better to use a Select Statement as shown in the example above.
-8265018 0You have not Googled your question. If you do so you'll get a lot of content about it. The link below will teach you how to check the integrity of a downloaded file.
https://help.ubuntu.com/community/HowToMD5SUM
You may also check the following link, which shows that it is very difficult to modify or replace the .md5
and .sh1
files.
The correct way to use each
is
$('.equ').each(function(){ adjustHeight(this); });
-2217483 0 How to convert array to string and vice versa? How to convert a array <-> string?
I've a bi dimensional array and i need to save to database and retrieve.
Dim myarray(,) as string = {{"some","some"},{"some","some"}}
-40992682 0 var latLong = place.geometry.location; /** latLong will have { "lat" : -33.8669710, "lng" : 151.1958750 } */
Most likes your place may not have this
geometry
property in which case, you have to fire new query usingplace_id
(deprecated) orreference
(preferred).
reference
contains a unique token that you can use to retrieve additional information.
A Place Details request is an HTTP URL of the following form:
https://maps.googleapis.com/maps/api/place/details/output?parameters
-11724492 0 The fact that the jars don't have the same name does not mean they cannot contain the exact same classes.
Hibernate and SLF4J usually require only one jar to be used. The other jars usually contain part of the classes from the large main jar and maybe some extra classes for a specific task.
I would start by removing hibernate-tools.jar
and slf4j-api-1.6.6.jar
and maybe even commons-logging-1.0.4.jar
and then see if you get ClassNotFoundException
you can add the specific required jar.
I don't suggest using numerical indexes if you don't have to, as in this case, they can be unpredictable. Instead, use the column names from your database, like this...
$videoFile = $row['videoFile']; $views = $row['views'];
Also, you say you want the ONE entry with MOST views, so I believe you want...
$q="select videoFile, views from videos ORDER BY views DESC LIMIT 1";
-4170697 0 Capturing gestures from MacBook Pro touchpad with Flex (Flash) Want to use in my drawing web app (Flex/Flash) capability to capture finger movements from macbook pro touch pad (or magic trackpad) to use it as drawing surface (like Wacom scrapbooks). Something like autograph app for MacOS X. Main idea is map coordinates system of touchpad and application canvas. Any help (advices) are welcome! Thanks
-37798972 0 VBA merge and unmerge according to if statementI am having an issue with merging data in excel using VBA.
Basically, I would like every cell row to be the same size and when a cell matches with a specific name, I want certain cells (specific 2 sets of rows preceding the name) to merge and center while others just merge across but that way some cells in the column have one number while others have a percentage and fraction as seen in this picture example above.
I'm wondering if offset could be useful here as well?
Here is some pseudo ish code to give you an idea: basically, if a cell in the A range matches a color (or whatever I put), then we want to merge and center two rows of cells and the 3 columns. Else if the cell in the A range matches a name (or whatever I put), then leave the cells separate but merge across maybe.
sub example1() if (cell in A range) = "red", "orange", "yellow", "green", "blue", then offset ( , 1) and merge¢er else if (cell in A range) = "sarah", "mark", "bob", "steve", "Brittany", then offset (, 1) and leavealone or merge just across end if end sub
-87310 0 The lovely built in regular expression evaluator.
-39192896 0Finally to solve I REDIRECTED with flash msg..
$em = $this->getDoctrine()->getManager(); $user = $this->get('security.token_storage')->getToken()->getUser(); $entity = $em->getRepository('ApplicationSonataUserBundle:User')->find($user->getId()); if (!$entity) { throw $this->createNotFoundException('Unable to find User entity.'); } $form = $this->createForm(ProfileType::class, $entity); if ($request->getMethod() === 'POST') { $form->handleRequest($request); if ($form->isValid()) { $em->flush(); return $this->redirectToRoute('fz_user'); } $em->refresh($user); $this->flashMSG(1, '' . $form->getErrors(true, false)); return $this->redirectToRoute('fz_user_profile_edit'); }
-1324197 0 Along with boosting during search, you can also boost fields differently during indexing. This means that a general search for a term that could show up in either field would still give a better score for those that match your preferred field without overtly stating where you're looking for the term.
-8947114 0That's pretty vague, but this is the concept if the child is nested:
$('.menu').find('.class')
I had the same issue and imported my own input.h version containing all the missing declarations.
You can do same thing and replace your input.h (you can search for input.h with those undefine identifiers in linux kernel sources), but easier way is to remove lines containing undefined identifiers from EventInjector.h. Just comment all lines that highlighted red in eclipse, and it should work.
-12566831 0 Display all records with an id smaller than 100 fails due to 'comparison of Symbol with 100 failed'I have a user model and I need to display all users that have an id of smaller than 100. My code is
User.where(:id < 100)
The error message is "comparison of Symbol with 100 failed". How can I just get all users with ids smaller than 100? How will it be if I need ids between 100 and 200?
-14733579 0$(function(){ $('#mainNewsBody .news img').attr('rel', 'superbox[image]'); });
-338630 0 We run Apache listening on port 443 (https) for Trac and Svn (WebDAV), and IIS listening on port 80 (http) for public web pages. Setting up Apache for Trac and Svn was very easy and well documented.
-27445408 0 enhanced ecommerce conversion issuesThis is the code being sent from our confirmation page for GA universal using enhanced ecommerce:
ga("create", "UA-XXXXXXX-xx", "auto"); ga("require", "displayfeatures"); ga("require", "ec"); ga("ec:addProduct", { Id: null, Name: "ProductNameTest", Brand: "Foo", Category: null, Variant: null, Price: 5.49, Quantity: 1, Coupon: "", Position: 0 }); ga("ec:setAction", "purchase", { Id: "33558", Affiliation: "Foo", Revenue: 5.49, Tax: 0, Shipping: 0, Coupon: "", List: null, Step: 4, Option: null }); ga("send", "pageview");
I'm not seeing any issues in the GA debugger or in the Tag Assistant plugin for Chrome.
What am I missing here that our conversion data/transactions aren't showing up?
EDIT:
Here is the output from the GA debugger that I stripped for the above:
Initializing Google Analytics. Loading resource for plugin: ec Loading script: "http://www.google-analytics.com/plugins/ua/ec.js" Running command: ga("create", "UA-XXXXXXX-xx", "auto") Creating new tracker: t0 Running command: ga("require", "displayfeatures") Set called on unknown field: "dcLoaded". Plugin "displayfeatures" intialized on tracker "t0". Running command: ga("require", "ec") Waiting on require of "ec" to be fulfilled. Executing Google Analytics commands. Registered new plugin: ga(provide, "ec", Function) Running command: ga("require", "ec") Plugin "ec" intialized on tracker "t0". Running command: ga("send", "pageview")
-21560232 0 OnCreate() of first tab gets called even when second tab is defined as CurrentTab I have an activity on which I have a TabHost
and a TabWidget
like this:
<TabHost xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/tabhost" android:layout_gravity="bottom" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="5dp"> <FrameLayout android:id="@android:id/tabcontent" android:layout_width="fill_parent" android:layout_height="0dip" android:padding="5dp" android:layout_weight="1" /> <TabWidget android:id="@android:id/tabs" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </LinearLayout> </TabHost>
I use the following code to add three tabs and their respective activities to the TabHost
:
private void CreateTabs() { TabHost.TabSpec spec; // Resusable TabSpec for each tab Intent intent; // Reusable Intent for each tab String strJson = Intent.GetStringExtra (Constants.JSON_RESPONSE); // Create an Intent to launch an Activity for the tab (to be reused) intent = new Intent (this, typeof (FirstActivity)); if (strJson != null) { intent.PutExtra (Constants.JSON_RESPONSE, strJson); } intent.AddFlags (ActivityFlags.NewTask); // Initialize a TabSpec for each tab and add it to the TabHost spec = TabHost.NewTabSpec ("first"); spec.SetIndicator ("First", Resources.GetDrawable (Resource.Drawable.FirstIcon)); spec.SetContent (intent); TabHost.AddTab (spec); // Do the same for second tab intent = new Intent (this, typeof (SecondActivity)); if (strJson != null) { intent.PutExtra (Constants.JSON_RESPONSE, strJson); } intent.AddFlags (ActivityFlags.NewTask); spec = TabHost.NewTabSpec ("second"); spec.SetIndicator ("Second", Resources.GetDrawable (Resource.Drawable.SecondIcon)); spec.SetContent (intent); TabHost.AddTab (spec); // Do the same for third tab intent = new Intent (this, typeof (ThirdActivity)); if (strJson != null) { intent.PutExtra (Constants.JSON_RESPONSE, strJson); } intent.AddFlags (ActivityFlags.NewTask); spec = TabHost.NewTabSpec ("third"); spec.SetIndicator ("Third", Resources.GetDrawable (Resource.Drawable.third_icon)); spec.SetContent (intent); TabHost.AddTab (spec); //Set the tab you want to show TabHost.CurrentTab = 1; }
As you can see that at the last line I am making the second tab to be shown when I open this tabbed activity and that is what it does but actually it first calls the OnCreate
of FirstActivity
and then calls OnCreate
of SecondActivity
before showing the SecondActivity
. (The OnCreate
of ThirdActivity
is only called when I tap on the third tab to actually see that activity, which is absolutely fine).
I want that the OnCreate
of FirstActivity
to be only called when I tap on the first tab because:
FirstActivity
gets the user's current location and if I get it before the user actually navigates to the required screen then it may not be correct if the user has already changed his location.Please let me know how to achieve that?
-16183164 0import numpy a_width = 9 a_height = 9 data_file = "matrix.dat" a = numpy.array(open(data_file).read().split(),dtype=int).reshape((a_width,a_height)) #or another alternative below a = numpy.fromfile("matrix.dat",dtype=int,sep=" ").reshape(9,9) print a
a different solution
with open(data_file) as f: a = map(str.split,f) print a
which is just a slightly more terse version of Nick Burns Code
-17632611 0No, you cannot change the current query string without reloading. You could use the frgament portion of the url though (#
). Setting the fragment portion might allow you to add some entries to the browser history without reloading.
For example if your current url is http://example.com/foo
you could change it to http://example.com/foo#bar=baz
without reloading the current page.
I want to display the content of a file in a tabview. Each value of the file is in an extra line.
With this I am already able to read the file line for line:
public class Tab1Activity extends Activity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.infolayout);
String line = ""; TextView text = new TextView(this); try { BufferedReader b = new BufferedReader(new FileReader("/sdcard/com.unitnode/debug.txt")); while ((line = b.readLine()) != null) { // liest zeilenweise aus Datei text.setGravity(Gravity.CENTER_VERTICAL); Log.d("zeile", "zeile " + line ); text.setText(line + "\r"); // setContentView(text); } b.close(); } catch (IOException e) { Log.d("fehler", "fehler "); } // ViewGroup mContainerView = (ViewGroup) findViewById(tabco); // mContainerView.addView(text); }
}
And this is the corresponding Layout xml:
TabHost xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@android:id/tabhost">
<LinearLayout android:id="@+id/LinearLayout01" android:orientation="vertical" android:layout_height="fill_parent" android:layout_width="fill_parent"> <TabWidget android:id="@android:id/tabs" android:layout_height="wrap_content" android:layout_width="fill_parent"> </TabWidget> <FrameLayout android:id="@android:id/tabcontent" android:layout_height="fill_parent" android:layout_width="fill_parent"> </FrameLayout> <TextView android:id="@+id/text1" android:text="test" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </LinearLayout>
How to display the whole file in a TabView?
EDIT: The question is not about how to create Tabs. Just how to display the file in a tab. The Tabs already exists. But my problem is, that I am only able to display one line. I want to display all lines of the file.
Thanks
-26289812 0Based on your updated info we can convert the commented out join to this:
and ( ( PRMA_Purchase_Request_Type_ID != 145 AND TBL_Purchase_Request_Master.PRMA_Purchase_Request_No *= TBL_Parts_In_Txn_Master.PITM_Related_Request_No ) OR ( PRMA_Purchase_Request_Type_ID = 145 AND TBL_Purchase_Request_Details.PRDE_MR_No *= TBL_Parts_In_Txn_Master.PITM_Related_Request_No ) )
This means we need a left outer join between
TBL_Purchase_Request_Master
and TBL_Parts_In_Txn_Master
TBL_Purchase_Request_Details
and TBL_Parts_In_Txn_Master
You have already defined the first one in your existing FROM clause. You just have to add the condition to it. It doesn't make sense to AND it so try an OR:
So I think your FROM should be like this (but it is very difficult to work out without seeing the data model)
FROM TBL_Purchase_Request_Details Inner Join TBL_Purchase_Request_Master ON PRMA_Purchase_Request_No = PRDE_Purchase_Request_No Left Join TBL_Parts_In_Txn_Master M ON ( ( M.PRDE_Parts_Spec_ID = PITM_Parts_Spec_ID AND M.PRDE_Service_Center_ID = PITM_Service_Center_ID AND M.PRDE_Required_Delivery_Date = PITM_Expected_Arrival_Date ) OR ( TBL_Purchase_Request_Master.PRMA_Purchase_Request_Type_ID != 145 AND TBL_Purchase_Request_Master.PRMA_Purchase_Request_No = M.PITM_Related_Request_No ) OR ( TBL_Purchase_Request_Master.PRMA_Purchase_Request_Type_ID = 145 AND TBL_Purchase_Request_Details.PRDE_MR_No = M.PITM_Related_Request_No )
I know it's annoying working with old code but it's worth keeping in mind that if it's a complex transformation, the code to transform it is going to be complicated. Would you rather have a bunch of different views pieced together (each of which you can unit test), or one HUMUNGOUS SQL statement representing all of those views in one go? Often stuff is built this way under tight constraints too. Managers are not interested in doing things properly, only coders are, but we don't pull the strings.
-7957062 0 using SQL to directly delete CoreData data from my DBThere are times when i will need to delete say 10,000 rows from my CoreData data store and looping through those records individually each time takes way too long.
Is there a way to use SQL to directly delete from my data store quickly?
-7182792 0 Is this HTML valid?Does this code contain anything invalid. I have a form with a table inside. Is that alright?
<form name="myForm" id="myForm"> <table id="myTab"> <tr> <td> <label for="id">User ID:</label> <input type="text" id="id" /> </td> </tr> <tr> <td> <label for="pass">Password:</label> <input type="password" id="pass" name="pass" /> </td> <td> <button type="button" class="submit">Submit</button> </td> </tr> <tr><td><input type="reset" /></td></tr> </table> <div class="error"></div><div class="correct"></div> </form>
For the result -- http://jsfiddle.net/mBwAh/
-16566533 0 Browser GET request returning old imagesI'm trying to use a GET request to retrieve an image from a server. The image is constantly changing, so I want to grab the image a few times every second (with the intent of displaying the images and imitating video eventually). However, there's something going wrong with the GET request. No matter how rapidly I try to GET the image (tried every 1s, 100ms, etc), it only returns a new image every 5 seconds. It's acting like there's a cached image somewhere and it's only updating the cache every 5 seconds, returning old, duplicate images all other times.
I've done the following to try to isolate the problem:
And yet it is still only actually retrieving new images every 5 seconds.
Example Request Headers: Cache-Control: no-cache Connection: keep-alive <-- Could this be the problem? Pragma: no-cache Example Response Headers: Cache-Control: no-cache Cache-Control: no-store Connection: close Pragma: no-cache Server: Apache-Coyote/1.1
My query (executed after a time delay every time image is loaded):
document.getElementById("videoDisplay").src = filename + "?random="+(new Date()).getTime();
-26950159 0 You just need to cast irand
from an int
to a str
, apart from that your code is fine:
text_file.write(str(irand) + "\n")
-28410992 0 var worker=new Worker("js/uga_db_worker.js");
worker.postMessage(ugaName); worker.onmessage=function(event){ } };
it my call in main.js
i have find a fix, if in my worker i do not use a number version for opendatabase, all is working
db = openDatabase('kpisselencro', '', 'dashboard kpisselincro', 5 * 1024 * 1024);
the version number is empty, i don't know why , but it seem really fix it.
-29470389 0 How can I pass variable when render view to script tag in Node.jsI'm using hbs as a template engine along with html. This is my setting.
app.set('view engine', 'html'); app.engine('html', hbs.__express);
In my route.js
router.get('/home', isAuthenticated, function(req, res){ res.render('home', { user: data something }); });
In my home.html I want to use user variable not as a template but to do something
<script> var user = {{user}}; // It don't recognize user variable /* do something about user variable */ </script>
-16906445 0 Is this what you want?
d = as.Date('2001-01-15') d - as.POSIXlt(d)$mday #[1] "2000-12-31"
-14753411 0 Why does data.table lose class definition in .SD after group by? I've tried to attach my own class to a numeric
, to alter the output format
. This works fine, but after I do a group by
the class reverts back to numeric.
Example: Define a new format function for my class:
format.myclass <- function(x, ...){ paste("!!", x, "!!", sep = "") }
Then make a small data.table
and change one of the columns to myclass:
> DT <- data.table(L = rep(letters[1:3],3), N = 1:9) > setattr(DT$N, "class", "myclass") > DT L N 1: a !!1!! 2: b !!2!! 3: c !!3!! 4: a !!4!! 5: b !!5!! 6: c !!6!! 7: a !!7!! 8: b !!8!! 9: c !!9!!
Now perform a group by and the N column reverts to integer:
> DT[, .SD, by = L] L N 1: a 1 2: a 4 3: a 7 4: b 2 5: b 5 6: b 8 7: c 3 8: c 6 9: c 9 > DT[, sapply(.SD, class), by = L] L V1 1: a integer 2: b integer 3: c integer
Any idea why?
-34450319 0something like this?
$(document).ready(function() { $('ul').each(function(){ var $thisUl = $(this); $thisUl.find('input').change(function(){ var total = 0; $thisUl.find('input:checked').each(function() { total += parseInt($(this).val()); }); $thisUl.find('li:last span').html(total + ' €') }); }); $('input').change(function(){ var overAllPrice = 0; $('input:checked').each(function(){ overAllPrice += parseInt($(this).val()); }) $('.overallprice').html(overAllPrice); }) });
-12048844 0 You can create a Map of JButton's Name to the JButton Object
Map<String, JButton> mbutt = new HashMap<String, JButton>();
And you can access the String and JButton by iterating over it like this.
for(Map.Entry<String,JButton> map : mbutt.entrySet()){ String k = map.key(); // Key JButton bu = map.value(); // JButton }
-10212149 0 Empty space with 100% webpage Someone noticed me today that my webpage has a empty space on the right on smaller screens. I am working hard to find the problem but I haven't found it yet.
As you see, there is a grey empty space next to my website. With the width set to 100% and the minimal width set to 1020px.
On bigger screens, the problem resolves itself and the website has the correct width of 100%.
Does someone recall this problem, or know how to solve it?
Website viewable on http://tinyurl.com/c2ohcpu
CSS CODE
html,body { margin:0px; width: 100%; min-width:1020px; background-color: #eaeeef; padding: 0px; font-family: Arial; font-size: 12px; color: #7f8386; } img { border: 0; } #f-container { width: 100%; height: auto; } #h-container { width: 100%; } #container { width: 1020px; height: auto; margin: 0 auto; padding-top: 10px; margin-top: -1px; background-image: url('../images/container_bg.png'); background-repeat: repeat-y; border: 1px solid #d4d6d7; margin-bottom: 10px; } #header { width: 100%; height: 59px; background-image: url('../images/header-repeat.png'); background-repeat: repeat-x; min-width: 1020px; z-index: 10000; float: left; } #header #h-container { width: 1020px; height: 59px; margin: 0 auto; } #header #logo-container { width: 414px; height: 40px; margin-left: 10px; border: 0; float: left; } #header h1 { margin:0; padding:0; } #header #logo-container #logo { width: 414px; height: 40px; } #header #topMenu { width: 580px; height: 50px; margin-right: 10px; float: right; } #header #topMenu ul.menu { height: 50px; margin: 0; padding: 0; float: right; } #header #topMenu ul.menu li { list-style-type: none; float: left; padding-left: 10px; padding-right: 10px; height: 50px; } #header #topMenu ul.menu li:hover, #header #topMenu ul.menu li.current { background-image: url('../images/menu_active.png'); background-repeat: no-repeat; background-position: center; } #header #topMenu ul.menu li a { text-decoration: none; display: block; height: 50px; } /* Home */ #header #topMenu ul.menu .item-102 a { background-image: url('../images/menu/home.png'); width: 58px; } /* Nieuws */ #header #topMenu ul.menu .item-103 a { background-image: url('../images/menu/nieuws.png'); width: 71px; } /* Diensten */ #header #topMenu ul.menu .item-104 a { background-image: url('../images/menu/diensten.png'); width: 80px; } /* Portfolio */ #header #topMenu ul.menu .item-105 a { background-image: url('../images/menu/portfolio.png'); width: 81px; } /* Contact */ #header #topMenu ul.menu .item-106 a { background-image: url('../images/menu/contact.png'); width: 75px; } /* Hosting */ #header #topMenu ul.menu .item-115 a { background-image: url('../images/menu/hosting.png'); width: 72px; } #content-left { width: 750px; height: auto; float: left; padding: 10px; } p { padding: 0px; margin: 0px; } #content-left h2.title { color: #33393e; font-size: 13pt; width: 100%; } #content-left h2 a { display: block; color: #33393e; text-decoration: none; font-size: 13pt; } #content-left ul.actions{ display: none; } #content-left .item-block { width: 100%; height: auto; border-bottom: 1px dashed #d4d6d7; padding-bottom: 20px; } #content-left .item-block .published { width: 745px; background: #CCEBF5; color: black; padding-top: 3px; padding-left: 5px; height: 17px; margin-bottom: 5px; } #content-right { width: 230px; height: auto; float: right; padding: 10px; } #content-right h2.title { color: #33393e; font-size: 13pt; width: 100%; } #content-right h2 a { display: block; color: #33393e; text-decoration: none; font-size: 13pt; } h2 a:hover { font-weight: bold; cursor: pointer; } #footer { width: 100%; text-align: center; margin-top: 5px; height: auto; } #content-right .item-block { width: 100%; height: auto; border-bottom: 1px dashed #d4d6d7; padding-bottom: 20px; } a { color: #0099cc; text-decoration: none; font-weight: bold; } a:hover { font-weight: normal; } .portfolio-image { margin: 0 auto; width: 700px; height: auto; display: block; }
HTML CODE
<?xml version="1.0" encoding="utf-8?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="nl-nl" lang="nl-nl" dir="ltr" > <head> <link rel="stylesheet" href="/templates/hiddenhidden/css/template.css" /> <link href="/templates/hiddenhidden/css/uni-form.css" rel="stylesheet" type="text/css" /> <link href="/templates/hiddenhidden/css/default.uni-form.css" rel="stylesheet" type="text/css" /> <link href="/templates/hiddenhidden/jqueryui/css/pepper-grinder/jquery-ui-1.8.16.custom.css" rel="stylesheet" type="text/css" /> <link href="/templates/hiddenhidden/css/screen.css" rel="stylesheet" type="text/css" /> <link rel="stylesheet" type="text/css" href="/templates/hiddenhidden/css/jquery.lightbox-0.5.css" media="screen" /> <link rel="shortcut icon" href="/templates/hiddenhidden/images/favicon.ico" /> <script type="text/javascript" src="/templates/hiddenhidden/js/jquery.js"></script> <script type="text/javascript" src="/templates/hiddenhidden/js/uni-form.jquery.min.js"></script> <script type="text/javascript" src="/templates/hiddenhidden/js/uni-form-validation.jquery.min.js"></script> <script type="text/javascript" src="/templates/hiddenhidden/js/jquery.lightbox-0.5.min.js"></script> <script type="text/javascript" src="/templates/hiddenhidden/jqueryui/js/jquery-ui-1.8.16.custom.min.js"></script> <script type="text/javascript" src="/templates/hiddenhidden/js/easySlider1.7.js"></script> <script type="text/javascript"> $(function () { $('a.lightbox').lightBox({ imageLoading:'/templates/hiddenhidden/images/lightbox-ico-loading.gif', imageBtnPrev:'/templates/hiddenhidden/images/lightbox-btn-prev.gif', imageBtnNext:'/templates/hiddenhidden/images/lightbox-btn-next.gif', imageBtnClose:'/templates/hiddenhidden/images/lightbox-btn-close.gif', imageBlank:'/templates/hiddenhidden/images/lightbox-blank.gif' }); }); </script> <base href="http://hiddenhidden.nl/" /> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <meta name="keywords" content="" /> <meta name="description" content="" /> <meta name="generator" content="Joomla! - Open Source Content Management" /> <title>hidden hidden</title> <link href="/?format=feed&type=rss" rel="alternate" type="application/rss+xml" title="RSS 2.0" /> <link href="/?format=feed&type=atom" rel="alternate" type="application/atom+xml" title="Atom 1.0" /> <link rel="stylesheet" href="/modules/mod_portfolio/portfolio.css" type="text/css" /> <script src="/media/system/js/mootools-core.js" type="text/javascript"></script> <script src="/media/system/js/core.js" type="text/javascript"></script> <script src="/media/system/js/caption.js" type="text/javascript"></script> <script type="text/javascript"> window.addEvent('load', function() { new JCaption('img.caption'); }); </script> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', '']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> </head> <body> <div id="fb-root"></div> <script type="text/javascript">(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/nl_NL/all.js#xfbml=1"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script> <div id="f-container"> <div id="header"> <div id="h-container"> <h1> <a href="/" id="logo-container" title="hidden hidden"> <img src="/templates/hiddenhidden/images/logo_with_slogan.png" id="logo" alt="hidden hidden" /> </a> </h1> <div id="topMenu"> <ul class="menu"> <li class="item-102 current active"><a href="/" ></a></li><li class="item-103"><a href="/nieuws" ></a></li><li class="item-104"><a href="/diensten" ></a></li><li class="item-115"><a href="/hosting" ></a></li><li class="item-105"><a href="/portfolio" ></a></li><li class="item-106"><a href="/contact" ></a></li></ul> </div> </div> <div style="clear:both;"></div> </div> <div id="container"> <div id="content-left"> <div id="system-message-container"> </div> <div class="blog-featured"> <div class="items-leading"> <div class="leading-0"> <h2 class="title"> <a href="/7-home/1-welkom-op-hidden-hidden"> Welkom op hidden hidden!</a> </h2> <!-- BEGIN --> <div class="item-block"> <div class="item-text"> <div class="item-separator"></div> </div></div> <div class="item-bottom"></div> </div> </div> </div> <h2 class="title">Onze Portfolio</h2> <div class="item-block"> <div class="item-text"> <div id="portfolio-slider" > </div> <div style="clear:both;"></div> <ul class="ui-tabs-nav"> </ul> </div> <script type="text/javascript"> jQuery(function() { jQuery("#portfolio-slider").tabs({fx:{opacity: "toggle"}}).tabs("rotate", 5000, true); });</script> <div style="clear:both;"></div> </div> </div> <div class="item-bottom"></div> <div id="footer"> Copyright© 2010 - 2012 hidden hidden. Alle rechten voorbehouden. | <a href="/component/xmap/?view=html&id=2">Sitemap</a> </div> </div> <div id="content-right"> <h2 class="title">Contact</h2> <div class="item-block"> <div class="item-text"> <div class="custom" > </div> </div> </div> <div class="item-bottom"></div> <h2 class="title">Offerte aanvragen</h2> <div class="item-block"> <div class="item-text"> <div class="custom" > <p>Offerte aanvragen? Dat kan via ons <a href="/contact/?view=form">contactformulier</a>.</p></div> </div> </div> <div class="item-bottom"></div> <h2 class="title">Sociaal</h2> <div class="item-block"> <div class="item-text"> <div id="facebook-container"></div><br /> <a href="http://facebook.com/hiddenhidden/" title="hidden hidden op Facebook"> <img src="/modules/mod_social/networks/facebook.png" style="border: 0;" alt="hidden hidden op Facebook" /> </a> <a href="http://twitter.com/hiddenwebsolution" title="hidden hidden op Twitter"> <img src="/modules/mod_social/networks/twitter.png" style="border: 0;" alt="hidden hidden op Twitter" /> </a> <a href="http://linkedin.com/company/hidden-hidden" title="hidden hidden op Linkedin"> <img src="/modules/mod_social/networks/linkedin.png" style="border: 0;" alt="hidden hidden op Linkedin" /> </a> <script type="text/javascript" src="/modules/mod_social/mod_social.js"></script> </div> </div> <div class="item-bottom"></div> </div> <div style="clear:both;"></div> </div> </div> </body> </html>
-12949716 0 For Microsoft SQL, I'd recommend the books by Kalen Delaney (et al) called "Inside SQL Server". They offer a good insight into the internals of SQL Server, thus allowing readers to educate themselves on why particular statements might be faster than others.
Inside SQL Server 7.0
Inside SQL Server 2000
Inside Microsoft SQL Server 2005
Microsoft SQL Server 2008 Internals
There's also a book dedicated to performance tuning of SQL Server 2008 queries: SQL Server Performance Tuning Distilled
I also like the blogs by Paul Randal and Kimberly Tripp on SQLSkills.com. They are full of solid SQL advice:
-14154884 0I would highly suggest operating line-by-line instead of reading in the entire file all at once (in other words, don't use .read()
).
with open('tweets.txt', 'r') as fileinput: for line in fileinput: line = line.lower() # ... do something with line ... # (for example, write the line to a new file, or print it)
This will automatically take advantage of Python's built-in buffering capabilities.
-2546748 0URL url= getClass().getResource("Resources/SartreIcon.jpg"); ImageIcon imageIcon = new ImageIcon(url); Image image = imageIcon.getImage(); this.setIconImage(image);
-23072707 0 Are Aggregate Roots just Entities with invariants over their contents? A Network
is composed of Node
s that are connected with Fiber
s. The Network
is responsible for making sure that:
Node
; Node
;Both the Network
, the Node
and the Fiber
are information-rich (they have a name, a date when they were deployed, etc), and it looks to me as if Network
is an Aggregate Root (as its the container of both Node
s and Fibers
and forces invariants between them).
I'm at this point also sure that Node
and Fiber
are entities, and that they are also probably Aggregate Roots.
One possible implementation of the Network
class might be as follows:
class Network { private final NetworkId id; private String name; private Location location; ... private final Map<FiberId, Fiber> fibers = new HashMap<FiberId, Fiber>(); private final Map<NodeId, Fiber> nodes = new HashMap<NodeId, Node>(); }
which poses a big problem if my use case is just to edit the location or the name of the Network
. In that case I just don't care about fibers and nodes and realistically, it is expected them to be quite possible for their numbers to be on the order of 10k-100k nodes/fibers! How should I approach this issue? Should I separate the definition of a Network
(containing fibers
and nodes
and their invariants) from the rest of the fields?
I've always thought of Aggregate Roots as Entities that have a set of invariants to hold over its attributes, in contrast with Entities that just don't care abouts the state of their attributes (for instance, a Person defined with a name and age wouldn't probably need to have any kind of checking for invalid combinations of name and age).
Following this philosophy, I generally tend to decide whether some domain concept is either a Value, Entity, Value or Event and then if it's an Entity, if it's an Aggregate Root. Is my assumption flawed?
Thanks
-24943335 0 PureScript does not compose `trace` and `show`So the following works
main = do trace $ show $ 5
but this does not
main = do (trace . show) 5
in psci the type of trace is
forall r. Prim.String -> Control.Monad.Eff.Eff (trace :: Debug.Trace.Trace | r) Prelude.Unit
and the type of show is
forall a. (Prelude.Show a) => a -> Prim.String
since the return value of show is Prim.String
and the first input into trace is Prim.String
they should be composable. This is further evidenced by that trace $ show
passes the type checking. But instead I get this error:
Error at line 1, column 10: Error in declaration it Cannot unify Prim.Object with Prim.Function Prim.String.
What am I missing here? Right now my mental model is that trace
is very like putStrLn
in Haskell, and that one can definitely be composed with show
. (putStrLn . show) 5
works.
Expected type of composed result of trace and show:
forall a r. (Prelude.Show a) => a -> Control.Monad.Eff.Eff (trace :: Debug.Trace.Trace | r) Prelude.Unit
-4447932 1 AttributeError: 'str' object has no attribute 'attack' "'Help!" I have q quick question regarding an Attribute Error regarding a basic Arena battler I am writing for my Intro to Programming Class. Here is the chunk of code that I am having trouble with upon running the program,
class Enemy: def __init__(self,player,weapons,armor): self.name = "Bad Guy" self.health = 100 self.attackPower = (player.attack + randint(-5,5)) self.defensePower = (player.defense + randint(-5,5)) self.weapon = player.weapon self.armor = player.armor def name_generator(self): import random element = ["Thunder","Lightning","Wind","Fire", "Stone"] tool = ["Hammer","Drill","Cutter","Knife", "Saw"] randomNumber1 = random.randrange(0,len(element)) randomNumber2 = random.randrange(0,len(tool)) self.randomname = element[randomNumber1] + " " + tool[randomNumber2] return self.randomname
Lol, ignore the Name Generator for now, thats an idea Ill try to work out later. The Current problem I am having now is that when I run the program through IDLE i get the following error;
File "C:\Users\Caleb Walter\Downloads\Arena_Battler.py", line 150, in __init__ self.attackPower = int(player.attack + randint(-5,5)) AttributeError: 'str' object has no attribute 'attack'
Any Help would be appreciated on the program error, as I have done research and tried to find the answer but all of the other casses of 'str' error involved lists. Thank You in Advance!
-19098890 0 Creating a SQL view with columns from other table recordsI have a table with data like:
A1 FID A2 0 0 39 1 0 23 0 1 16 1 1 64 2 1 12 0 2 76 0 3 11 0 4 87
And I want to create a view that will list this:
FID Col0 Col1 Col2 0 39 23 null 1 16 64 12 2 76 null null 3 11 null null 4 87 null null
How can this be possible in T-SQL?
-23278172 0In Python 2, writing
class MyClass(object):
would suffice. Or you switch to Python 3, where
class MyClass:
would be just fine.
The inheritance list usually gives a list of base classes (see Customizing class creation for more advanced uses), so each item in the list should evaluate to a class object which allows subclassing. Classes without an inheritance list inherit, by default, from the base class object; hence
class Foo: pass
is equivalent to
class Foo(object): pass
See also: https://docs.python.org/3/reference/compound_stmts.html#class
Also, as @Kevin pointed out in a comment, method resolution is not trivial and might lead to unexpected behavior when using multiple inheritance: http://python-history.blogspot.com/2010/06/method-resolution-order.html
-32720555 0 $(...).draggable is not a functionI have got this code:
$(document).ready( function(){ var potv = $("#FUWTEHOHS").position().top; var spotv = $("#FUWTEHOHS").position().left; $("#TTFTGTHIWW").css("top", potv + 50).css("left", spotv + 450); $(function() { $("#TTFTGTHIWW").draggable(); }); });
#TTFTGTHIWW { background: black; border: 1px dashed white; width: 100px; height: 100px; position: absolute; }
<div id="TTFTGTHIWW"></div>
But it is not working it gives an error:
-4930035 0$(...).draggable is not a function
You could use cpuidpy, which uses x86 CPUID instruction to get CPU information.
-36343103 0When you pipe objects to Select-Object [propertyname(s)]
, the Select-Object
cmdlet creates a new object for you, with the properties from the input object that you specified. This object in turn ends up being rendered as @{PropertyName1=PropertyValue1[;PropertyNameN=PropertyValue2]}
when converted to a string.
To grab the value of a single property, and nothing else, use the -ExpandProperty
parameter:
$GivenName = Get-ADUser -Identity $user |Select-Object -ExpandProperty GivenName
Since you need multiple properties from the same user, better store the the user in a variable and use the .
dereference operator to access the GivenName
and Surname
properties:
$UserObject = Get-ADUser -Identity $user $GivenName = $UserObject.GivenName $Surname = $UserObject.Surname
-20459799 0 Are you using Python 2? If so, print
is a keyword, not a function. There are two ways to solve your problem:
Write print foo, bar
instead of print(foo, bar)
.
The difference is that print(foo, bar)
is actually printing out the tuple (foo, bar)
, which uses the repr()
representation of each element, rather than its str()
.
At the very top of your file, write from __future__ import print_function
. This will magically convert print
from a keyword into a function, causing your code to work as expected.
If you are using Python 3, my answer is irrelevant.
-6378529 0 Trying to consolidate jQuery codeI have loads of code that most need to be loaded BEFORE the other piece of code in order for it to work correctly. In order for me to achieve this I have multiple scripts over and over again. Is there a way I can clean some of this up? I will try and give examples:
//This needs to load first to add class <script> $(function(){ if (typeof(global_Current_ProductCode) !="undefined") { if ($('#pt494').length == 0 ) { $('font[class="text colors_text"]:eq(0)').closest('table').addClass('thePrices'); } } }); </script> //This needs to load 2nd because it has to add the class first before it does this <script> $(function(){ if (typeof(global_Current_ProductCode) !="undefined") { if ($('#pt490').length == 0 ) { $('table[class="thePrices"]:eq(0)').closest('table').before($('font[class="productnamecolorLARGE colors_productname"]:eq(0)').addClass('toptitle'));} } }); </script>
There is so much more code similar to this, there has got to be a way to throw it all under the same IF statement?
-10427349 0Your class's constructor method should be called __construct()
, not __constructor()
:
public function __construct(EntityManager $entityManager) { $this->em = $entityManager; }
-5213630 0 Suspend and Resume thread (Windows, C) I'm currently developing a heavily multi-threaded application, dealing with lots of small data batch to process.
The problem with it is that too many threads are being spawns, which slows down the system considerably. In order to avoid that, I've got a table of Handles which limits the number of concurrent threads. Then I "WaitForMultipleObjects", and when one slot is being freed, I create a new thread, with its own data batch to handle.
Now, I've got as many threads as I want (typically, one per core). Even then, the load incurred by multi-threading is extremely sensible. The reason for this: the data batch is small, so I'm constantly creating new threads.
The first idea I'm currently implementing is simply to regroup jobs into longer serial lists. Therefore, when I'm creating a new thread, it will have 128 or 512 data batch to handle before being terminated. It works well, but somewhat destroys granularity.
I was asked to look for another scenario: if the problem comes from "creating" threads too often, what about "pausing" them, loading data batch and "resuming" the thread?
Unfortunately, I'm not too successful. The problem is: when a thread is in "suspend" mode, "WaitForMultipleObjects" does not detect it as available. In fact, I can't efficiently distinguish between an active and suspended thread.
So I've got 2 questions:
How to detect "suspended thread", so that i can load new data into it and resume it?
Is it a good idea? After all, is "CreateThread" really a ressource hog?
Edit
After much testings, here are my findings concerning Thread Pooling and IO Completion Port, both advised in this post.
Thread Pooling is tested using the older version "QueueUserWorkItem". IO Completion Port requires using CreateIoCompletionPort, GetQueuedCompletionStatus and PostQueuedCompletionStatus;
1) First on performance : Creating many threads is very costly, and both thread pooling and io completion ports are doing a great job to avoid that cost. I am now down to 8-jobs per batch, from an earlier 512-jobs per batch, with no slowdown. This is considerable. Even when going to 1-job per batch, performance impact is less than 5%. Truly remarkable.
From a performance standpoint, QueueUserWorkItem wins, albeit by such a small margin (about 1% better) that it is almost negligible.
2) On usage simplicity : Regarding starting threads : No question, QueueUserWorkItem is by far the easiest to setup. IO Completion port is heavyweight in comparison. Regarding ending threads : Win for IO Completion Port. For some unknown reason, MS provides no function in C to know when all jobs are completed with QueueUserWorkItem. It requires some nasty tricks to successfully implement this basic but critical function. There is no excuse for such a lack of feature.
3) On resource control : Big win for IO Completion Port, which allows to finely tune the number of concurrent threads, while there is no such control with QueueUserWorkItem, which will happily spend all CPU cycles from all available cores. That, in itself, could be a deal breaker for QueueUserWorkItem. Note that newer version of Completion Port seems to allow that control, but are only available on Windows Vista and later.
4) On compatibility : small win for IO Completion Port, which is available since Windows NT4. QueueUserWorkItem only exists since Windows 2000. This is however good enough. Newer version of Completion Port is a no-go for Windows XP.
As can be guessed, I'm pretty much tied between the 2 solutions. They both answer correctly to my needs. For a general situation, I suggest I/O Completion Port, mostly for resource control. On the other hand, QueueUserWorkItem is easier to setup. Quite a pity that it loses most of this simplicity on requiring the programmer to deal alone with end-of-jobs detection.
-5565087 0Try to stick with eclipse, if you're having problems there, it will be worse trying to do things on the command line. The built in tools like log cat and the debugger are of great value.
-15233168 0I think you've got things a bit mixed up here. The server's encoding does not matter to the client, and it shouldn't. That is what RFC 2109 is trying to say here.
The concept of cookies in http is similar to this in real life: Upon paying the entrance fee to a club you get an ink stamp on your wrist. This allows you to leave and reenter the club without paying again. All you have to do is show your wrist to the bouncer. In this real life example, you don't care what it looks like, it might even be invisible in normal light - all that is important is that the bouncer recognises the thing. If you were to wash it off, you'll lose the privilege of reentering the club without paying again.
In HTTP the same thing is happening. The server sets a cookie with the browser. When the browser comes back to the server (read: the next HTTP request), it shows the cookie to the server. The server recognises the cookie, and acts accordingly. Such a cookie could be something as simple as a "WasHereBefore" marker. Again, it's not important that the browser understands what it is. If you delete your cookie, the server will just act as if it has never seen you before, just like the bouncer in that club would if you washed off that ink stamp.
Today, a lot of cookies store just one important piece of information: a session identifier. Everything else is stored server-side and associated with that session identifier. The advantage of this system is that the actual data never leaves the server and as such can be trusted. Everything that is stored client-side can be tampered with and shouldn't be trusted.
Edit: After reading your comment and reading your question yet again, I think I finally understood your situation, and why you're interested in the cookie's actual encoding rather than just leaving it to your programming language: If you have two different software environments on the same server (e.g.: Perl and PHP), you may want to decode a cookie that was set by the other language. In the above example, PHP has to decode the Perl cookie or vice versa.
There is no standard in how data is stored in a cookie. The standard only says that a browser will send the cookie back exactly as it was received. The encoding scheme used is whatever your programming language sees fit.
Going back to the real life example, you now have two bouncers one speaking English, the other speaking Russian. The two will have to agree on one type of ink stamp. More likely than not this will involve at least one of them learning the other's language.
Since the browser behaviour is standardized, you can either imitate one languages encoding scheme in all other languages used on your server, or simply create your own standardized encoding scheme in all languages being used. You may have to use lower level routines, such as PHP's header()
instead of higher level routines, such as start_session()
to achieve this.
BTW: In the same manner, it is the server side programming language that decides how to store server side session data. You cannot access Perl's CGI::Session
by using PHP's $_SESSION
array.
I need to pass a C++ vector of vectors to OpenCL kernel, for exemple, I have the follow data:
3 1 9 1 3 8 5 1 3 8 4
3 9 4 0 7 4 3
1 0 4 8 2 8 3 1 2
1 9 3 2
8 3 9 4
4 9 3 9 5 4 3
My structure of data in C++ is a vector of vectors:
So, my structure is a vector of vectos with size 6 and the size of the vector 'i' is dynamic.
How can I pass the data to OpenCL kernel?
Any idea?
Thank you.
-5127139 0Seems like you call the wrong constructor that doesn't pass a Context.
final MapItem itemizedStoreOverlay = new MapItem(storePic); // No context.
-38342551 0 You should have reviewed previous TR. It is having two columns and as per Table view specification, you can not have two different rows with different columns without using colspan attribute.
Change the line and add colspan="2" as follow. You will have full width row. Also make sure your TD_16 style have width=100%
-39297017 0
Only if you put the "nested select" (THis is referred to as a subquery) in the From Clause:
select FN from (select First_Name as FN from PERSON) z
-25460329 0 Difference from compiler perspective between passing by const value or const ref In the context of c++.
I wonder what is the difference, between this:
T f(T const val);
and this:
T f(T const & val);
I do know one is a pass by value, but, from the compiler's pespective, this is a value that is not going to change, so my questions are:
Mostly likely you don't have your app selected in the package explorer tree at the left.
Just click on the top-most item in the tree (ie. "MyFirstApp") and then try running again. Chances are you had "activity_main.xml" selected as it's the default selection when you built your test app.
-24657872 0 Trigger Maven Plugin Execution if module has direct dependency on specific artifactCan maven trigger or skip a plugin execution if the module directly depends on another module? For example,
I want a & b to perform a maven-dependency-plugin extraction of connector followed by an antrun to move files around. I want to put the execution in the parent so I define it once.
I want c to automatically skip the extraction.
Please let me know if you think this is possible and how you'd approach it.
Thanks
Peter
-22515779 0From here:
The function will read and ignore any whitespace characters encountered before the next non-whitespace character (whitespace characters include spaces, newline and tab characters -- see isspace). A single whitespace in the format string validates any quantity of whitespace characters extracted from the stream (including none).
So change
scanf(" %d ",&a);
to
scanf("%d",&a);
-501990 0 Preventing the user from using the functionality of Screen is bad form (unless you have a shared login which runs your application).
Instead, make your application deal with the use case you've shown by autologout, warning new connecting users and giving them the option to boot the other user, handling multiple users, etc.
-30856681 0According to your description in comments, try this:
select key,keyword from table1 where key='a=1' union all select product_id,store_id from table2 where product_id='1' and store_id='7'
-2301991 0 C++ Portable way of programmatically finding the executable root directory Possible Duplicate:
how to find the location of the executable in C
Hi,
I am looking for a portable way to find the root directory of a program (in C++). For instance, under Linux, a user could copy code to /opt, add it to the PATH, then execute it:
cp -r my_special_code /opt/ export PATH=${PATH}:/opt/my_special_code/ cd /home/tony/ execution_of_my_special_code
(where "execute_my_special_code" is the program in /opt/my_special_code).
Now, as a developer of "execution_of_my_special_code", is there a portable programmatical way of finding out that the executable is in /opt/my_special_code?
A second example is on MS Windows: What if my current working directory is on one hard drive (e.g. "C:\") and the executable is placed on another (e.g. "D:\")?
Ultimately, the goal is to read some predefined configuration files that are packaged with the program code without forcing the user to enter the installation directory.
Thanks a lot in advance!
-14501002 0You could setup a service that runs periodically, and checks the server if an update is available (check the timestamp of the APK would be one way to check this).
Then download the APK. Install it, and send a notification.
This is a complicated thing to accomplish, and probably not something you would want to do yourself if you can help it. (Why isn't it in the Play Market?)
-2755397 0You are in fact getting your results in what is known as "table order", which may look like it's in the order that data was added to the table but that order is not stable. There are a number of operations that can change the order you are receiving results without changing the data in the table itself.
To reproduce the sort of order you are seeing I'd suggest adding a column to your table of type ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP
. This will give you a column to specifically order on and therefore reverse that order. You should probably add an index on that column as well if this operation is a frequent one.
It looks like you're somehow sending a pushBetter method call to your view controller which it is apparently not prepared for (according to your code and the error):
-[HBFSViewController pushBetter]: unrecognized selector sent to instance 0x693ccb0'
Can you to a global search for "pushBetter" and see where it is in your project??
-30243385 0 Query a duplicate data from two different tablesI have two tables on DBA.
Table1: name_id | id | lastupdated | name Table2: user_id | action_view | mob_no | process | result
These two tables are related with name_id=user_id.
I want to query all the users, that have the same mobile number for whom column result
is 1 (meaning successful).
Lets say for Name(John in Table1) we have 3 different mobile numbers in table 2 and for each the result
is 1.
I am using pyodbc python module.
when I use SELECT = "SELECT k.Poznámka as poznamka from karta as k"
I get error
Error: ('07002', '[07002] [Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 1. (-3010) (SQLExecDirectW)')
Problem is with name "Poznámka" and "á" in it. When I use the same select with field title without diacritics for example k.Name everything works.
What with this please?
-22279207 0 Can't see full key names in registry using Format-Table commandI am trying to see full key names in registry because I want to copy them to a text file later but I can't see the full name. So first I enter to the registry hive I need:
cd HKLM:
cd SOFTWARE\Microsoft\Windows\CurrentVersion\ModuleUsage
And now I run: Get-ChildItem | format-table name But this is what I received:
I tried to copy it to text file thought maybe it doesn't show it full because of the GUI but it didn't help. So I tried to replace 'Format-Table' with 'Format-List' and it show me the full name:
But now I need to run some functions to cut the 'Name : ' off which shouldn't be a problem but I wonder if it possible to show me the full name with 'Format-Table'
Thanks
-4131353 0Besides storing latitude and longitude as double, you'd definitely want to index those fields. However you should be aware of the fact that index operations are most efficient in case of integer fields - and this is an important consideration when it comes to large data volumes.
I guess the following algorithm might help you:
What you achieve with *Idx columns and ScaleFactor is actually breaking your data into cells of equal size. Size of the cell is actually 1/ScaleFactor geo degrees, i.e. roughly 111 km/ScaleFactor.
So when you retrieve the data with particular LatitudeIdx and LongitudeIdx values you're actually getting all points that fall into the cell defined by those values, i.e. filter your data points. After that you calculate distances to the point of interest and select closest one (you can actually do that directly in query and sort by distance to get the point you need in a single pass).
-11149404 0 Android Scrollview not catching longclickAs said in the title, I have a scrollview that should be listening for longclicks, but isn't catching any. Nothing happens when I hold the scrollview- no logs, no haptic feedback, & no dialog.
Thanks in advance!
JAVA:
... ScrollView text_sv = (ScrollView) findViewById(R.id.text_sv); text_sv.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View v) { MMMLogs.i("click", "long-click recognized"); AlertDialog.Builder builder = new AlertDialog.Builder(_this); builder .setTitle(name) .setMessage(DHMenuStorage.notification) .setCancelable(false) .setNegativeButton("Close", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = builder.create(); alert.show(); return true; } }); ...
XML:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:padding="5dp" > <ScrollView android:id="@+id/text_sv" android:layout_width="match_parent" android:layout_height="75dp" android:hapticFeedbackEnabled="true" android:clickable="true" android:longClickable="true" > <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" > <TextView android:id="@+id/name" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@color/Gray" android:focusable="false" android:gravity="center" android:padding="4dp" android:text="-- Dining Hall Name --" android:textColor="@color/Black" android:textSize="28dp" android:textStyle="bold" /> <TextView android:id="@+id/note" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@color/Gray" android:focusable="false" android:gravity="center" android:padding="4dp" android:text="-- Special note here --" android:textColor="@color/Black" android:textSize="14dp" android:textStyle="normal" /> </LinearLayout> </ScrollView> <TabHost android:id="@android:id/tabhost" android:layout_width="fill_parent" android:layout_height="fill_parent" > <LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:padding="5dp" > <TabWidget android:id="@android:id/tabs" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <FrameLayout android:id="@android:id/tabcontent" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="5dp" /> </LinearLayout> </TabHost>
-10937998 0 I don't see any relationship between those two tables.
In your uploads
table definition change this
`member_school_id` int(11) NOT NULL DEFAULT 1
Remove quote from member_school_id
since it's a INT
field.
SELECT uploads.*, audienceuploadassociation.* FROM uploads JOIN audienceuploadassociation ON uploads.upload_id = audienceuploadassociation.upload_id WHERE uploads.member_id = '1' AND uploads.member_school_id=1 AND uploads.subject = 'ESL' AND uploads.topic = 'Poetry' LIMIT 20
-31259097 0 Solution 1 : You have a complicated image with transparent border and don't want the transparent part to be clickable :
Draw the image into the canvas and use getImageData(x,y,width,height)
to check if the pixel under the click is transparent.
var pointMap = [], canvas, ctx, img; $(document).ready(function () { img = $('#bodyImageFront'); img[0].onload = init; }); $(window).resize(function () { canvas.width = img[0].width; canvas.height = img[0].height; drawCanvas(); var tempArray = pointMap; pointMap = []; for (var i = 0; i < tempArray.length; i++) { addPointToMap(tempArray[i]); } }); function init(){ canvas = document.createElement("canvas"); canvas.id="bodyMapFrontCanvas"; canvas.width = img[0].width; canvas.height = img[0].height; $(canvas).css('position:relative'); $(canvas).click(addPointToMap); ctx = canvas.getContext('2d'); img.parent().append(canvas); img.css('opacity:0'); drawCanvas(); } function drawCanvas() { if(!canvas) return; ctx.drawImage(img[0], 0,0,canvas.width,canvas.height); } function addPointToMap(evt) { var target = evt.target, x = evt.offsetX ? evt.offsetX : evt.pageX - target.offsetLeft, y = evt.offsetY ? evt.offsetY : evt.pageY - target.offsetTop; // get the image data of our clicked point var pointData = ctx.getImageData(x,y,1,1).data; // if its alpha channel is 0, don't go farther if(pointData[3]===0) return; ctx.fillRect(x-5, y-5, 10, 10); if(evt.type){ pointMap.push({target: target, offsetX: x, offsetY: y}); } }
#bodyImageFront { display:block; max-height: 75vh; max-width: 90%; height:auto; width: auto; margin-bottom: 10px; z-index:-1; position:absolute; } canvas { z-index:20; background:#AAFFAA; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form id="mainForm"> <div id="canvasContainer"></div> <div id="bodyMapFrontContainer"> <img src="https://dl.dropboxusercontent.com/s/nqtih1j7vj850ff/c6RvK.png" id="bodyImageFront" crossorigin="Anonymous" /> </div> </form>
Solution 2 : You really only want to draw a simple shape like in the example you gave :
Draw this shape directly onto the canvas and use isPointInPath()
to detect whether it should activate the click or not.
var canvas = document.querySelector('canvas'), ctx = canvas.getContext('2d'); function draw(){ var w = canvas.width, h = canvas.height; ctx.fillStyle = "#5b9bd5"; ctx.beginPath(); var radius = w/3, x= canvas.width/2, y = radius, a= 11; for ( var i = 0; i <= 4 * Math.PI; i += ( 4 * Math.PI ) / 5 ) { ctx.lineTo( x + radius * Math.cos(i + a), y + radius * Math.sin(i + a)); } ctx.closePath(); ctx.fill(); } function clickHandler(e){ var target = e.target, x = e.clientX, y = e.clientY; if(ctx.isPointInPath(e.clientX, e.clientY)){ ctx.fillStyle="#000"; ctx.fillRect(x-5,y-5,10,10); } } canvas.addEventListener('click', clickHandler, false); draw();
canvas{background:#AAFFAA;} *{margin:0; overflow: hidden;}
<canvas height=500 width=500/>
Solution 3: Once again you only want a simple shape, and you don't really need <canvas>
:
Draw it with svg and add the event listener only to the svg element you want to listen to.
document.getElementById('star').addEventListener('click', clickHandler, false); var svg = document.querySelector('svg'); function clickHandler(e){ var vB = svg.getBBox(), bB = svg.getBoundingClientRect(), ratio = {w:(vB.width/bB.width), h:(vB.height/bB.height)}; var x = e.clientX*ratio.w, y = e.clientY*ratio.h; var rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect'); rect.setAttribute('x', x); rect.setAttribute('y', y); rect.setAttribute('width', 10*ratio.w); rect.setAttribute('height', 10*ratio.w); rect.setAttribute('fill', "#000"); var parent = e.target.parentNode; parent.appendChild(rect); }
*{margin: 0; overflow: hidden;} svg{ height: 100vh; }
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" viewBox="0 0 100 100" enable-background="new 0 0 100 100" xml:space="preserve"> <rect fill="#AAFFAA" width="100" height="100"/> <polygon id="star" fill="#29ABE2" points="50,16.5 60.9,40.6 85.2,42.1 65.6,59.3 71.8,83.5 50,70.1 28.2,83.5 34.4,59.3 14.8,42.1 39.1,41.6 "/> </svg>
I am trying to build a shell command (on Mac OSX El Capitan) to recursively rename all my DOCX files to have extension ZZZZ and then to immediately rename them back again to the DOCX extension. This is a workaround to hopefully fix a problem as follows:
I am doing this to try to get around a Mac Spotlight bug which doesn't search for content inside Mac Word 2011 files correctly. It gives intermittent results and seem to miss a lot of hits (this issue seem to be well-known for a few years on Apple Mac Forums). Renaming a file seems to kick-start Spotlight into action.
Mac Shell doesn't have the BASH Rename command so I am trying to iteratively use the "MV" command. I've had partial success with the following code but don't know how to tie it together...
cd ~/Documents/TESTING/ # FINDS MY DOCX'S RECURSIVELY IN TOP-LEVEL FOLDER AND IT'S SUBFOLDERS. NOT SURE OF SYNTAX TO USE FOR "MV" COMMAND TO RENAME DOCX FILES # find . -wholename '*.docx' -type f -exec mv UNSURE1HERE UNSURE2HERE \; # WORKS BUT ONLY IN TOP-LEVEL FOLDER - I NEED IT TO WORK RECURSIVELY ON DOCX'S IN TOP-LEVEL FOLDER AND IT'S SUBFOLDERS: # for files in *.docx; do mv "$files" "${files%.docx}.zzzz"; done
-14118997 0 How to Upload With ASP.NET I know I might get a lot of downvotes for this, but I cannot find the information anywhere. I am trying to upload my compiled web application to the internet. I was told that all I need is the dll file which is supposed to go into the bin folder? Is this true or do I need to upload both the dll file and the bin folder?
Also, is there a better way to build so that I dont have to intermix my image, css, and so on into my project folder? Maybe a way to copy the dll file to a bin folder and all my aspx pages?
I got it to work but it seems like I keep duplicating a bunch of files and I know eventually some problem will arise.
Thanks and happy new year to everyone.
-3489273 0Take a look at pdb++ - it is a drop-in replacement for pdb that fills all your requirements and adds some other nice features such as tab completion and new commands such as watch and sticky.
-33267144 0 Finding duplicates in 2D array - Row and ColumnI would like to know how do I find duplicates separately - Row and Column.
So far I think I have this for the row, haven't really tested it out. But I am kinda confuse how to find duplicates for a 2D array in column fashion? I need to implement 2 functions one to find duplicate for row and the other one to find duplicate for column.
bool uniqueRow(int square[][MAX_SIZE], int sqrSize, int i) { int j; for(i = 0; i < sqrSize; ++i) { for(j = i; i < sqrSize && square[i][i] != square[i][j]; ++j) { if(square[i][i] == square[i][j]) return false; else return true; } } return false; } bool uniqueCol(int square[][MAX_SIZE], int sqrSize, int i) { int j; for(i = 0; i < sqrSize; ++i) { for(j = i; i < sqrSize && square[i][i] != square[j][i]; ++j) { if(square[i][i] == square[j][i]) return false; else return true; } } }
-40485019 0 Use Array#sort
method with custom compare function.
var data=[{"user":"a", "msg":"Hi ", "msg_count":1, "unix_time":"1474476800000"}, {"user":"b", "msg":"Hi ", "msg_count":1, "unix_time":"1478776800000"}, {"user":"c", "msg":"Hi ", "msg_count":5, "unix_time":"1479276800000"}, {"user":"d", "msg":"Hi ", "msg_count":1, "unix_time":"1478416800000"}, {"user":"e", "msg":"Hi ", "msg_count":3, "unix_time":"1478476800000"}]; data.sort(function(a, b) { // return the difference of `msg_count` property to sort based on them // if they are equal then sort based on unix_time prop return b.msg_count - a.msg_count || b.unix_time - a.unix_time; }) console.log(data)
Mat1b
and Mat3b
are just two pre-defined cases of Mat
types, which are defined in core.hpp
as follows:
typedef Mat_<uchar> Mat1b; ... typedef Mat_<Vec3b> Mat3b;
That said, conversion between Mat and Mat1b
/Mat3b
should be quite natural/automatic:
Mat1b mat1b; Mat3b mat3b; Mat mat; mat = mat1b; mat = mat3b; mat1b = mat; mat3b = mat;
Back to your case, your problem should not be attributed to their conversions, but the way you define the SubMain()
and how you use it. The input parameter of SubMain()
is a const cv::Mat3b &
, however, you're trying to modify its header to change it to be a Mat1b
inside the function.
It will be fine if you change it to, e.g.:
cv::Mat1b SubMain(const cv::Mat3b& img) { cv::Mat tmp = img.clone(); OperateImage opImg(tmp); opImg.Trafo(tmp); return tmp; }
-24759648 0 Thanks, my error was just that.
But i solved it like this
fil1 = "<=" & Month(rev_date) & "/" & Day(rev_date) & "/" & Year(rev_date)
-30765925 0 show / hide form fields based on a select option (dropdown) I have a select dropdown menu with many options to choose from.
When a person chooses an option, I need the form fields to change according to the select menu.
For some reason, I am stuck. I would like to blame the culprit on the fact that I have classes which are hidden in the element which should be shown. The problem with that is that I cannot think of the proper way to approach this.
It is probably worth mentioning that I am using WordPress and these fields are used for extra user registration fields.
Here is a fiddle for method 1
Here is a fiddle for method 2
html
<div id="reg_mem_type" class="form-row form-row-wide"> <label for="reg_mem_type">'Member Type' </label> <select id="reg_mem_type" name="mem_type" value="'.esc_attr($_POST['mem_type']).'"> <option value="ARENA">ARENA</option> <option value="ARO">ARO</option> <option value="BUILD">BUILD</option> <option value="RM">RM</option> <option value="CLUBINS">CLUBINS</option> <option value="AFFL">AFFL</option> <option value="HOCKEY">HOCKEY</option> <option value="HOCKEYA">HOCKEYA</option> <option value="PRO">PRO</option> <option value="SKATER">SKATER</option> <option value="WE">WE</option> <option value="LINS">LINS</option> <option selected disabled value="Member">Member Type</option> </select> </div> <div class="member-type bs-member-type form-row form-row-wide"> <h2>personal info</h2></div> <div class="member-type bs-member-type form-row form-row-wide"><label for="reg_first_name">'.__('First Name', 'woocommerce').'</label> <input type="text" class="input-text" name="first_name" id="reg_first_name" size="10" value" '.esc_attr($_POST['first_name']).'" /></div> <div class="member-type bs-member-type form-row form-row-wide"><label for="reg_last_name">'.__('Last Name', 'woocommerce').'</label> <input type="text" class=" input-text" name="last_name" id="reg_last_name" size="10" value" '.esc_attr($_POST['last_name']).'" /></div> <div class="arena-member-type bs-member-type form-row form-row-wide"> <h2>company info</h2></div> <div class="bs-member-type arena-member-type form-row form-row-wide"> <label for="reg_website">'.__('Website' , 'woocommerce').'</label> <input type="text" class="input-text" name="website" id="reg_website" value" '.esc_attr($_POST['website']).'"/></div> <div class="arena-member-type bs-member-type form-row form-row-wide"> <label for="reg_fax">'.__('Fax' , 'woocommerce').'</label> <input type="text" class="input-text" name="fax_num" id="reg_fax" value" '.esc_attr($_POST['fax_num']).'"/></div>
css- method 1
.member-type { display: none; } .pro-member-type { display: none; } .bs-member-type { display: none; } .arena-member-type { display: none; } .show-fields { display:block; } .hidden-fields { display:none; }
css method2
.member-type { display: none; } .pro-member-type { display: none; } .bs-member-type { display: none; } .arena-member-type { display: none; } .show-fields { display:block; } .hidden-fields { display:none; }
js method 1
jQuery(document).ready(function ($) { $('select[name=mem_type]').change(function () { // hide all optional elements $('.member-type').css('display', 'none'); $('.arena-member-type').css('display', 'none'); $('.bs-member-type').css('display', 'none'); $('.pro-member-type').css('display', 'none'); $("select[name=mem_type] option:selected").each(function () { if ($(this).val() == "SKATER" || "HOCKEY" || "HOCKEYA") { $('.member-type').css('show-fields'); } else if ($(this).val() == "BUILD") { $('.bs-member-type').addclass('show-fields'); } else if ($(this).val() == "ARENA") { $('.arena-member-type').addclass('show-fields'); } else if ($(this).val() == "PRO") { $('.pro-member-type').addclass('show-fields'); } }); }); });
js method 2
jQuery(document).ready(function ($) { $('select[name=mem_type]').change(function () { // hide all optional elements $('.member-type').css('display', 'none'); $('.arena-member-type').css('display', 'none'); $('.bs-member-type').css('display', 'none'); $('.pro-member-type').css('display', 'none'); $("select[name=mem_type] option:selected").each(function () { if ($(this).val() == "SKATER" || "HOCKEY" || "HOCKEYA") { $('.member-type').css('display', 'block'); } else if ($(this).val() == "BUILD") { $('.bs-member-type').css('display', 'block'); } else if ($(this).val() == "ARENA") { $('.arena-member-type').css('display', 'block'); } else if ($(this).val() == "PRO") { $('.pro-member-type').css('display', 'block'); } }); }); });
-32960721 0 Using Split function with Cells, Range, Rows.count, and xlup on excel-vba Will this code work?
lr = RD.Cells(Rows.Count, 8).End(xlUp).Row wArray() = Split(RD.Range(Cells(2, 8), Cells(Rows.Count, 8).End(xlUp).Row)) RD.Cells(2, 8).Value = wArray(0) RD.Cells(2, 9).Value = wArray(1)
I want the code to go through each of the cells in the range and split the data in that range and put the 2nd string on the cell next to it. Like for example, I have a A1:A15
cell range that has the cell value of "01/01/2015 09:43 GMT", after I run the the code, I expect that "01/01/2015" will remain at range A1:A15 while "09:43" will be moved to cell range B1:B15
. I have tried the same code by defining a single cell on the Split(RD.Cells)
function and it worked beautifully. Now I need it to keep on going on the next row as long as that row has an input.
Try reading pixels right after
GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
Also make sure that glReadPixels is called from the right thread, i.e. in your renderer subclass.
And another thing, i see that you are binding the texture used for the FBO as input to the shader, you cannot do that.
I suppose that after RTT, you are rendering the result to a quad or something on screen is that right ?
Can you show the rest of the code that you are using to read the pixels ?
-40721738 0I think you need to specify a "data" attribute on each column that needs to be populated from the returned data. Otherwise it doesn't know what attribute on the json object goes to each column. If you defined your data as an array of arrays instead of an array of objects this wouldn't be required.
Additionally you aren't specifying a "dataSrc" option which isn't required but if it isn't set I believe it expects the returned JSON to be of the form:
{ data: [ {...}, {...} ] }
So it would be helpful if you could add in the raw response to the ajax request.
EDIT1:
Ok so double checked and yes it does want an object array assigned to the "data" attribute on the JSON object so you can do something like this to fix this without having to modify anything on the server. Just change your ajax option to this:
"ajax": { "url": "Player/GetSetPlayers", "dataSrc": function ( json ) { // We need override the built in dataSrc function with one that will // just return the object array instead of looking for a "data" // attribute on the "json" object. Note if you ever want to add // serverside sorting/filtering/paging you will need to move your table // data to an attribute within the JSON object. return json; } }
So you will probably be good once you do both of the fixes above.
-31129867 0 iterating object keys inside array iterationThis is my fiddle of getting all values of input in a table. I am getting the value if and only if on set of data is available I also happened to have add
meaning I can add new set of data. My question is how to iterate again through the new added set. Currently I am not iterating to the new set I am only getting the last set of data
im using an object to store input values , how can i iterate over this object to store every input value as object key ?
UPDATE
Output expected
[{ "First Name": "John", "Last Name": "Smith", "Middle Name": "Lee", "Suffix": "Jr", "City/Province": "JohnCity", "Town/Municipality": "JohnTown", "Barangay/District": "JohnDistrict", "Contact Number": "8973897923", "Street": "123", "member": "complainant" }, { "First Name": "James", "Last Name": "Harden", "Middle Name": "Lin", "Suffix": "III", "City/Province": "JamesCity", "Town/Municipality": "JamesTown", "Barangay/District": "JamesDistrict", "Street": "123", "Contact Number": "1234123421", "member": "complainant" }]
It is an array of 1 element of type struct nsq1. Something like: int x[1];
-21026035 0 Error when changing user name in ApigeeI have a space in the user name in my organization's Apigee account. I use the User Settings page to attempt to update the user name by deleting the space and keeping only the alphabet characters, but I keep getting the error "Username should contain only alphanumerals, dot, dash and underscore. Please try again." This has to be a bug in the Apigee UI. How else can one change the user name?
-18826516 0 Numeric Overflow exception with collection.EXISTS(n) methodI'm getting ORA-01426: numeric overflow when running the following piece of code on Oracle 11g database:
DECLARE TYPE my_type IS RECORD ( a NUMBER, b VARCHAR2(10) ); TYPE my_table IS TABLE OF my_type INDEX BY BINARY_INTEGER; my_var my_table; my_num1 NUMBER; my_num2 NUMBER; BEGIN my_num1 := 1; my_num2 := 781301042106240; IF NOT my_var.EXISTS(my_num1) THEN dbms_output.put_line('my num1 works'); END IF; IF NOT my_var.EXISTS(my_num2) THEN dbms_output.put_line('my num2 works'); END IF; END;
It appears that EXISTS method can not handle the large number. But shouldn't it accept a NUMBER data type as input? Oracle documentation doesn't help much as it doesn't mention parameter's data type.
Does anyone knows what is max precision that EXISTS can accept?
-12209065 0 Allow users to create a new table but one table for each topic onlyI am trying to create something where the user can create a table for a topic, but only one topic table and in that topic table other users will be able to add to that topic table.
I need the topic table to be only created once. So for ex:
User A creates a a new topic which is a new table about oranges.
Then other users will be able to add to that oranges table, but no other users can create another table called oranges.
How should I approach this matter?
What is the code for letting the users create the table but only once?
Also how safe is it to give the users the ability to create tables?
Here is some code I have that lets users add and displays data from the database.
<?php include 'connection.php'; $query = "SELECT * FROM people"; $result = mysql_query($query); While($person = mysql_fetch_array($result)) { echo "<h3>" . $person['Name'] . "</h3>"; echo "<p>" . $person['Description'] . "</p>"; echo "<a href=\"modify.php?id=" . $person['ID']. "\">Modify User</a>"; echo "<span> </span>"; echo "<a href=\"delete.php?id=" . $person['ID']. "\">Delete User</a>"; } ?> <h1>Create a User</h1> <form action="create.php" method="post"> Name<input type ="text" name="inputName" value="" /><br /> Description<input type ="text" name="inputDesc" value="" /> <br /> <input type="submit" name="submit" /> </form>
You advice will be great help!
-30807312 0 Looping issues? jQueryI have a dynamic table which has three textboxes and a select dropdown in each row that is added. On the click of a button, more rows can be added dynamically. Once I click submit I want to the loop through each cell but in the tbody section ONLY; when trying the loop is just skipped over. I have already tried debugging in console but no issues were found.
Here is my HTML:
<table id= "tb1" class="norm sideBG" name="recordTable" align="center" cellpadding="4" cellspacing="0" border="1" bordercolor="lightgrey" width="600px"> <tr class="norm"> <td> <b><u>LMV PART #</u></b> </td> <td> <b><u>LOCATION</u></b> </td> <td> <b><u>QUANTITY</u></b> </td> <td> <b><u>WHERE USED</u></b> </td> </tr> <tbody class="theRow" id="theRow"> <tr> <td class="norm"> <label id="partLabel" style="color : red;"></label> <br /> <input type='text' name='txtbox0[]' id='txtbox0[]' onchange="javascript: changeLabel(this)" /> </td> <td class="norm"> <select id="txtbox1[]" name="txtbox1[]" > <% strSQL1 = "myQuery" Set oRs1 = oConn1.Execute(strSQL1) Do while not oRs1.eof Response.Write("<OPTION VALUE='" & Mid(oRs1(0),4) & "'") Response.Write(">" & Mid(oRs1(0),4) & "</OPTION>") oRs1.movenext loop oRs1.Close oConn1.Close %> </select> </td> <td class="norm"> <input type='text' name='txtbox2[]' id='txtbox2[]' /> </td> <td class="norm"> <input type='text' name='txtbox3[]' id='txtbox3[]' /> </td> </tr> </tbody> </table>
Along with my jQuery loop which is processed on submit()
var cellVal; $("#tb1 > tbody.theRow > tr").each(function() { cellVal = $(this).text(); if (cellVal.length == 0 || cellVal == null) { alert("there's a blank field"); blankFields = true; } });
-15966057 0 You said you set a custom image for the UIControlStateHighlighted
state. This should disable the default behaviour.
If you still have problems you can disable this effect by setting the adjustsImageWhenHighlighted
property to NO
and use whatever custom effect you want.
i wanto dynamic add 5 TLable in my iOS app.
like this
Procedure Form1.FormCreate(Sender: TObject) var I: Integer; begin for I := 1 to 5 do begin with TLabel.Create(Self) do begin Parent := self; Align := TAlignLayout.Top; Height := 50; Text := IntToStr(I); end; end; end;
i think the order is 12345, but I get 15432.
What can I do to get the desired results?
-32126213 0Despite the presence of a redirect parameter, the access token will generate a standard 200 response, not a 301 redirect. Depending on how you issue and handle the request/response, you can preserve your state.
According to section 4.1.4 of the OAuth 2.0 spec document (RFC 6749), the response to an Access Token Request should be an "HTTP/1.1 200 OK".
In other words, the server will not perform a redirect, meaning you can issue a request and process the response in the same scope (either in the client or server, whatever your situation), so your database user ID need only be in local memory.
This is different from the Authorization Request, which is supposed to result in an "HTTP/1.1 302 Found" (redirect). See section 4.1.2.
So why is the redirect_uri
parameter required?
According to section 4.1.3, the server must:
In other words, the redirect_uri
acts as a sort of secret or password which the server must use to verify the access token request. If the client fails to provide a redirect_uri
parameter, or the parameter value is different from the original request, then the server must reject the access token request.
Implement a echoing system on the server on a specific port say 8070
i have done Broadcast of message to a given port using following code.
broadCastSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()]; if ([broadcastSocket enableBroadcast:true error:&error] == false) { NSLog(@"Failed to enable broadcast, Reason %@:",[error userInfo]); } NSData *data = [QueryString dataUsingEncoding:NSUTF8StringEncoding]; [broadcastSocket sendData:data toHost:@"255.255.255.255" port:8070 withTimeout:-1 tag:5];
your all the server will receive data on the port and echoing system reply to given port. Now you can listen to those port and get the ip of all the server which will reply.and ofcourse this trick will only work if sever is yours.
NOTE :: I was using GCDAsyncSocket Library but you can use whatever you want.
So, a friend had a similar problem, and the library I needed was msvcprt.lib .
-16255556 0Install db
sudo -u _mysql /opt/local/lib/mariadb/bin/mysql_install_db
Change root password
/opt/local/lib/mariadb/bin/mysqladmin -u root password 'new-password'
Alternatively you can run:
/opt/local/lib/mariadb/bin/mysql_secure_installation'
You can start the MariaDB daemon with:
cd /opt/local; /opt/local/lib/mariadb/bin/mysqld_safe --datadir='/opt/local/var/db/mariadb'
-28957976 0 Elapsed time column - how to refresh only one part of StructuredViewer I have a StructuredViewer
(in this example a TreeViewer
with columns) that refreshes its interior through some callbacks I don't want to get into, by calling setInput()
and refresh()
on it when the callbacks occur.
I need to introduce a Time Elapsed cell that will need to refresh every second, and this will only be in one cell of the Viewer.
What would be the best way to make a light-weight refresh on only one cell/column?
Thanks in advance
-25640211 0$( document ).ready(function() { paypal.use(["login"], function (login) { login.render({ "appid": "-************", "authend": "sandbox", "scopes": "profile email address phone", "containerid": "paypalLogin", "locale": "en-us", "text": "Verify your account with Paypal", "redirect_uri": "http://localhost:57559/" }); }); });
while creating the button request as a text attribute, we can set the button text
-8156114 0You can pass your array as a JSON string to JavaScript inside the loaded page by calling UIWebView stringByEvaluatingJavascriptFromString:
.
First, use a JSON library to encode the contents of your array into a JSON-encoded string. If you use SBJSON then something like this:
NSString* json = [myArray JSONRepresentation];
(this will work with your simple array of strings. If you have a more complicated array of other objects, they will have to be compatible with the JSON serializer)
Then, pass this to your webview:
NSString* js = [NSString stringWithFormat: "myJavaScriptFunction( '%@' );", json]; [myWebView stringByEvealuatingJavascriptFromString: js];
In your HTML file you will have to implement a JavaScript function (in this example, "myJavaScriptFunction") that accepts the passed JSON, and decodes it into a Javascript array.
-9417759 0 history.js back button in chromeI use history.js nearly everything works fine and as expected. But I have a problem in this situation:
Does anyone has a solution for this problem? FF and IE are working fine here...
-3650458 0Check that the CSS file path you are provided in page is right.
for example :
<link href="css/site.css" rel="stylesheet" type="text/css" />
the above line should be inside head tag
here "css" folder is inside project root directory, and site.css is inside that "css" folder
so check the path of css file
-23969768 0 <div data-target="#bs_id" data-toggle="modal" class="carousel-content" > <div class="content_wrapper modal fade" id="bs_id" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div> There is a lot of content here </div> <div> I like to show all of the content in a modal window </div> </div> </div>
-39957696 0 In your case, control will go to the while-condition after sorting all the elements.so no need to add do-while.Only set size you want. int i,j,n=4,k,temp; int arr[]={3,5,1,7,9,1,2};
for(i=0; i<n; i++){ for(j=i+1; j<n; j++){ if(arr[j] < arr[i]){ temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } }
-18367032 0 Is there any good reason to merge a short-term, tagged change in the software? Suppose I've got some software whose last released version is 1.1. Development from there has continued on two tracks:
master
april_fools
branch.My plan is to tag the temporary code as v1.2
and release it, but never merge it to master. This is because if I did merge it:
Version 1.3 would be tagged and released based on the latest commit on master
when the time came.
This seems like the cleanest solution, but I'm a little hesitant. Should I worry about having a lineage of commits where versions 1.1 and 1.3 have no intervening commit tagged 1.2? Could this cause confusion for later developers looking at the commit history?
-7243888 0 How to list out all the subviews in a uiviewcontroller in iOS?I want to list out all the subviews in a UIViewController
. I tried self.view.subviews
, but not of the subviews are listed out, for instance, the subviews in the UITableViewCell
are not found. Any idea?
if you order your points like this:
int smX = startPoint.X < finalPoint.X ? startPoint.X : finalPoint.X; int bgX = startPoint.X < finalPoint.X ? finalPoint.X : startPoint.X; int smY = startPoint.Y < finalPoint.Y ? startPoint.Y : finalPoint.Y; int bgY = startPoint.Y < finalPoint.Y ? finalPoint.Y : startPoint.Y;
You can imagine a rectangle with the points:
(smX, smY) (smX, bgY) (bgX, smY) (bgX, bgY)
So you could use the middle of the rectangle to set a point of triangle, than draw a triangle with the points:
(smX, bgY) (bgX, bgY) (smX + ((bgX - smX) / 2), smY)
-22961422 0 Jquery Accordion UI control error hi i am trying to learn and use a accordion control of Jquery UI with the below
HTML CODE
<div id="accordionTest"> <div> <div id="dvError"> </div> <div id="divbody"> </div> </div> <div id = "new"> </div> </div>
and
JS CODE:
$('#accordionTest').accordion();
but i am getting an error which says
'object doesn't support this property or method'
please help me in resolving this..
-31191462 0You can't copy a range with more than one area. You will have to transfer the data over one range at a time. Using Range.Areas
you can see that you have multiple areas in multipleRanges.
Apparently you can use this trick.
<title> My title</title>
That icon-alike is actually a text.
-37409435 0For finding out amount from bank transaction message.
(?i)(?:(?:RS|INR|MRP)\.?\s?)(\d+(:?\,\d+)?(\,\d+)?(\.\d{1,2})?)
For finding out merchant name from bank transaction message.
(?i)(?:\sat\s|in\*)([A-Za-z0-9]*\s?-?\s?[A-Za-z0-9]*\s?-?\.?)
For finding out card name(debit/credit card) from bank transaction message.
(?i)(?:\smade on|ur|made a\s|in\*)([A-Za-z]*\s?-?\s[A-Za-z]*\s?-?\s[A-Za-z]*\s?-?)
-39659726 0 This will sort based on dynamic last field which is separated by /
. First it will append last field to the start of the line and then sort
. First field which is appended earlier is removed by second awk
.
awk -F'/' '{ $0= $NF " " $0;print $0 |"sort -k1"}' fil |awk '{print $2}' /Volumes/Location/Workers/Bill/2016-03-17_Bill_PC/DOCS/1998816.doc /Volumes/Location/Workers/Andrew/2015-09-17_Andrew_PC/DOCS/2130419.doc /Volumes/Location/Workers/Andrew/2015-08-12_Andrew_PC/DOCS/3177109.doc /Volumes/Location/Workers/Charlie/2016-07-06_Charlie_PC/DOCS/4744123.doc
-39966857 0 First Time In and Last Time Out with Excel I have a data below where I want to get the unique ID number and only get the first time in and last time out. The data looks something like this:
The result should be something like this:
-39401365 0You can do something like this:
func ==(lhs: Pet, rhs: Pet) -> Bool { if case let Pet.cat(l) = lhs, case let Pet.cat(r) = rhs where l == r { return true } if case let Pet.dog(l) = lhs, case let Pet.dog(r) = rhs where l == r { return true } return false }
But a switch
probably looks better and is definitely easier to maintain.
You are facing with a very common problem that most developers should know about: Integer overflow.
Your year variable is an int, the constant for second->year conversion is constant int, so int*int is... int. Except if your year is larger than approx 68, the result cannot fit into an int. Hence - overflow and silly results.
You have a couple of options available to you:
TimeUnit
class from concurrent
package. It doesn't have years, but does have days and does conversion nicely (JodaTime would be even nicer though)You can try another hook system like http://github.com/jtek/git-hook-update-notify-email
-14062700 0 Refactor code with return statementsThe "if" blocks with checkcustomers are exactly used in other methods in this class, so there is a lot of code dublication for same checks. But I cant also directly extract this checksomethings to one single method because they have return values.
Some good ideas to refactor this code? I just modified this code to simplify here, so dont get caught on minor issues in this code(if any), Basically question is how to a extract a piece of code to a method(because it is dublicated on other methods) when there are many returns in that current method.
public Details getCustomerDetails(){ if(checkifcustomerhasnoboobs){ ..worry about it.. return new Details("no"); } if(checkifcustomerplaytenniswell){ ..do find a tennis teacher return new Details("no cantplay"); } //...ok now if customer passed the test, now do the some real stuff // // CustomerDetails details= getCustomerDetailsFromSomewhere(); return details; }
-14100837 0 You were updating a piece of code outside of angular and needed to let angular know to reprocess itself.
$scope.selectPage = function(pageIndex) { $scope.currentPage = pageIndex; $scope.draw(); $scope.$apply(); }
I added the $scope.$apply(); and now the currentPage updates correctly in the input. Here are the docs on the $apply method: http://docs.angularjs.org/api/ng.$rootScope.Scope#$apply
jsfiddle: http://jsfiddle.net/zZURe/14/
-7233660 0 Rep values from a data frame to another data frame. apply? sapply?I have the following data frame
data<-data.frame(ID=c("a", "b", "c", "d"), zeros=c(3,2,5,4), ones=c(1,1,2,1)) ID zeros ones 1 a 3 1 2 b 2 1 3 c 5 2 4 d 4 1
and I wish to create another data frame with 2 columns:
First column(id) the ID is repeated (zero+ones) times Second column value should be the c(rep(0, zeros), rep(1, ones))
so that the result would be
id value 1 a 0 2 a 0 3 a 0 4 a 1 5 b 0 6 b 0 7 b 1 8 c 0 9 c 0 10 c 0 11 c 0 12 c 0 13 c 1 14 c 1 15 d 0 16 d 0 17 d 0 18 d 0 19 d 1
I tried data.frame(id=(rep(data$ID, (data$zeros+data$ones))), value=c(rep(0, data$zeros), rep(1, data$ones)))
but doesnt work. Any ideas? Thank you in advance
I want to rewrite www.domain.com/s/index.php?s=test into test.domain.com
I did it successfully in local host using the following.
RewriteCond %{HTTP_HOST} ^([^\.]+)\.localhost$ [NC] RewriteRule ^$ /s/index.php?s=%1 [L]
However, when i put it live on my server, it didnt work. below is the code
RewriteCond %{HTTP_HOST} ^([^\.]+)\.domain\.com$ [NC] RewriteRule ^$ /s/index.php?s=%1 [L]
What went wrong? Appreciate advices.
-21501198 0\t
is a special character in C/C++ you need to pass D:\\transaction.list
as a filename
This should do it for you:
Path.GetPathRoot(Environment.SystemDirectory)
-17185389 1 How would I get the detailed version of my Python interpreter via a one-liner or command-line option? The output of --version itself is a little too brief:
C:\>python --version Python 2.7.5
However, if I run Python from the command prompt, I get something similar to the following, with verbose version info for the interpreter all on one line:
C:\> python Python 2.7.5 (default, May 15 2013, 22:44:16) [MSC v.1500 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information.
Is there a simple way, in a one-line command or via some options to get that same verbose version info line as a string that I could use to populate an environment variable or such?
In effect, is there a more verbose variant of --version I'm unaware of?
-12437439 0 How do I consistently size a font that is itself smaller than the standard?My problem is that I am using a locally-hosted webfont (which we'll call Gothic) and the font-size I apply in the stylesheet has a dramatic effect on the backup fonts declared.
Example, using imaginary numbers for ease:
Gothic is sized at 48, px or em, takes up about a width of 300px. Backup font Arial, if it loads instead for whatever reason, at 48 px or em, loads at a width of about 1200 pixels.
I have never seen a typeface behave like this which makes me wonder if the strangeness is due to the construction of the file format, but I am unsure. Any help would be welcome.
-3021205 0 Requirement to deploy the .NET frameworkHas the requirement to deploy the .NET framework with a .NET application caused programmers to go back to languages such as C++ where more standalone applications can be created?
-189196 0This won't work unless you use implementation-specific/platform-specific stuff to force the correct calling convention. For some calling conventions the called function is responsible for cleaning up the stack, so they must know what's been pushed on.
I'd go for the check for NULL then call - I can't imagine it would have any impact on performance.
Computers can check for NULL about as fast as anything they do.
-37004405 0 WebApi - Autofac cannot resolve parameter HttpRequestMessageI have an issue with RegisterHttpRequestMessage
not working for me and cannot figure out what I'm doing wrong. This is specifically when I try to manually resolve a service that accepts the HttpMessageRequest as a parameter.
I'm using modules to register components in my builder, and currently my module in the main web project looks like this:
builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); builder.RegisterHttpRequestMessage(GlobalConfiguration.Configuration); builder.RegisterType<SourceSystemViewModel>().AsImplementedInterfaces().InstancePerRequest(); builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()) .Where(t => t.Name.EndsWith("ViewModelValidator")) .AsImplementedInterfaces() .PropertiesAutowired(); // Etc etc etc
SourceSystemViewModel
is currently quite simple and looks like this:
public interface ISourceSystemViewModel { SourceSystem Value { get; } } public class SourceSystemViewModel : ISourceSystemViewModel { public SourceSystemViewModel(HttpRequestMessage request) { Value = request.Headers.GetSourceSystem(); } public SourceSystem Value { get; } }
GetSourceSystem is just an extension method that pulls out the header value. I have tried both registering SourceSystemViewModel
with and without InstancePerRequest
but it doesn't make a difference. The moment autofac tries to resolve ISourceSystemViewModal
(and ultimately HttpRequestMessage
) it throws this:
An exception of type 'Autofac.Core.Registration.ComponentNotRegisteredException' occurred in Autofac.dll but was not handled in user code
Additional information: The requested service 'System.Net.Http.HttpRequestMessage' has not been registered. To avoid this exception, either register a component to provide the service, check for service registration using IsRegistered(), or use the ResolveOptional() method to resolve an optional dependency.
Using autofac 3.5 (webapi dll is quoted as autofac.webapi2 3.4).
Any ideas much appreciated!
Notes
I'll add any findings as I come across them...
Update 1
I took a look at how RegisterHttpRequestMessage
works and it does indeed add a message handler called CurrentRequestHandler
to HttpConfiguration
. When my request comes in I can see that this message handler still exists. So the method seems to do what it's supposed to, it's just not resolving the request message for me...
Update 2
I have noticed that while in the context of a controller and therefore have access to the HttpRequestMessage
I can resolve both objects. Like this:
ILifetimeScope requestLifetimeScope = Request.GetDependencyScope().GetRequestLifetimeScope(); var h = requestLifetimeScope.Resolve<HttpRequestMessage>(); var sourceSystemViewModel = requestLifetimeScope.Resolve<ISourceSystemViewModel>();
Update 3
It's important to note that I am manually trying to resolve a service that is expecting the HttpMessageRequest as an injected parameter. For example, this fails for me:
using (var httpRequestScope = IocProxy.Container.Context.BeginLifetimeScope("AutofacWebRequest")) { var sourceSystemViewModel = httpRequestScope.Resolve<ISourceSystemViewModel>(); }
-8146024 0 Controlling color and width of HTML input box The box diameter created by the code below is gray and about 1 pixel wide. Is there any way I could make it 3 pixels wide and this color: #DE2A00
?
<div class="usernameformfield"><input tabindex="1" accesskey="u" name="username" type="text" maxlength="35" id="username" /></div>
-9537642 0 How to improve JDBC performance with my application Here is the basic outline of my application (which connects to a SQlLite DB):
It scans a directory a creates a list of 8-15 different flat files that need to be read.
It identifies the flat file and chooses a generic prepared statement based on the file extension.
It then reads the flat file line by line and adds the prepared statement with the strings having been set to a batch. The batch is executed each 1,000 statements. Some of the files in question have 200,000 lines that need to be read.
Once all files have been inserted in the database (there is a different table for each file type), the program updates a certain column for each table to a common value.
The program creates a new file for each file type and extracts the information in the database to the new file.
Currently one run on a directory with about 9 very small files (less than 50 rows) and one very large file (more than 200,000 rows) takes about 1.5 minutes to run. I am hoping to get this faster.
A few first questions:
Should I close and open the database connection for each part of the program (loading, updating, extracting) or leave the connection open and pass it off to each different method.
Should I close the prepared statement after each file that is processed? Or just clear the parameters after each file and close it at the end of method (essentially after all the jobs are loaded)?
I am interested in any other comments about things that I should be focusing on the maximize the performance of this application.
Thanks.
-29982410 0I think it would be better if you create another class that can display a hint, that way it will be easier whenever you need to do this again. Here's an example of how it could work, taken from another question on SO
class HintTextField extends JTextField implements FocusListener { private final String hint; private boolean showingHint; public HintTextField(final String hint) { super(hint); this.hint = hint; this.showingHint = true; super.addFocusListener(this); } @Override public void focusGained(FocusEvent e) { if(this.getText().isEmpty()) { super.setText(""); showingHint = false; } } @Override public void focusLost(FocusEvent e) { if(this.getText().isEmpty()) { super.setText(hint); showingHint = true; } } @Override public String getText() { return showingHint ? "" : super.getText(); } }
You can use this and then set your JTextField to new HintTextField("What you want your hint to be"). You can modify this class for your own needs, but it's a good starting point.
Update: And if you want to use your current code for whatever reason, change the mouse listener to a focus listener and override focusGained.
-23464040 0 Eclipse version control - problems with project no longer showing in workspaceI'm trying to figure out which files to check in to version control when using Eclipse for Android development. I have a workspace with a single project. I found this which suggested that the .metadata folder did not need to be controlled (minus the comment there about launch params, however I don't mind re-picking those again on a different machine).
If I remove the .metadata folder then open Eclipse the project is no longer shown. I searched for posts on this symptom and they suggest re-importing the project. This solution doesn't make sense here, I'm trying to check in whatever is needed so another developer can open the workspace and see the project and work on it. Having them move the project then re-import it would be a bit messy.
So which files should I be version controlling so that someone else can get the latest and be able to open the project without controlling a bunch of user specific preferences?
-14851124 0The framebuffer sources have nothing to do with the stuff you render. You can attach multiple render targets to each framebuffer and switch between them. However, this is something you don't need actually and it has nothing to do with the rendering step itself until you use multiple passes or need some other render to texture stuff.
I would skip this part of your OpenGL learning and start directly with VBO's and shaders and just use some template for the framebuffers at this point. Later you may need them but not now.
-35386714 0 Why is my code not displaying the string value attached to an integer?I'm totally new to programming and Swift is the first language I'm learning.
I've been researching this issue, but I'm not really sure I'm researching the right thing. Until now all my research has been about converting integers to strings etc, but I suspect that I'm barking up the wrong tree. And perhaps my question title is misleading too, but here's my scenario.
I am working on a quiz app that stores all the questions and answers in a .json file in the following format:
{ "id" : "1", "question": "Earth is a:", "answers": [ "Planet", "Meteor", "Star", "Asteroid" ], "difficulty": "1" }
The correct answer is always the one listed first within the .json file.
The app presents the question with the four possible answer buttons (which have been shuffled using the following code):
func loadQuestions(index : Int) { let entry : NSDictionary = allEntries.objectAtIndex(index) as! NSDictionary let question : NSString = entry.objectForKey("question") as! NSString let arr : NSMutableArray = entry.objectForKey("answers") as! NSMutableArray //println(question) //println(arr) labelQuestion.text = question as String let indices : [Int] = [0,1,2,3] //let newSequence = shuffle(indices) let newSequence = indices.shuffle() var i : Int = 0 for(i = 0; i < newSequence.count; i++) { let index = newSequence[i] if(index == 0) { // we need to store the correct answer index currentCorrectAnswerIndex = i } let answer = arr.objectAtIndex(index) as! NSString switch(i) { case 0: buttonA.setTitle(answer as String, forState: UIControlState.Normal) break; case 1: buttonB.setTitle(answer as String, forState: UIControlState.Normal) break; case 2: buttonC.setTitle(answer as String, forState: UIControlState.Normal) break; case 3: buttonD.setTitle(answer as String, forState: UIControlState.Normal) break; default: break; } }
Once a button is pressed, the app checks the answer chosen with the following code:
func checkAnswer( answerNumber : Int) { if(answerNumber == currentCorrectAnswerIndex) { // we have the correct answer labelFeedback.text = "Correct!" labelFeedback.textColor = UIColor.greenColor() score = score + 1 labelScore.text = "Score: \(score)" totalquestionsasked = totalquestionsasked + 1 labelTotalQuestionsAsked.text = "out of \(totalquestionsasked)" accumulatedquestionsasked = accumulatedquestionsasked + 1 percentagecorrect = score / totalquestionsasked SaveScore() SaveBestScore() // later we want to play a "correct" sound effect PlaySoundCorrect() } else { // we have the wrong answer labelFeedback.text = "Wrong!" labelFeedback.textColor = UIColor.blackColor() totalquestionsasked = totalquestionsasked + 1 labelTotalQuestionsAsked.text = "out of \(totalquestionsasked)" accumulatedquestionsasked = accumulatedquestionsasked + 1 SaveScore() SaveBestScore() // we want to play a "incorrect" sound effect PlaySoundWrong() } }
So, what I'd like to do is change the labelQuestion text to present the correct answer if the user was wrong.
I've tried a few options as follows:
labelQuestion.text = "The correct answer was: \(currentCorrectAnswerIndex)"
and
labelQuestion.text = "The correct answer was: \(currentCorrectAnswerIndex)" as string
and
let answertext = String(currentCorrectAnswerIndex) labelQuestion.text = "The correct answer was: \(answertext)"
All of these attempts have the same outcome - they provide the integer value corresponding to the button with the correct answer. For example, the user is presented with a message like:
The correct answer was: 2 instead of The correct answer was: Planet
I know I must be making a newbie mistake, but any direction would be much appreciated. I'm using the latest version of Xcode / Swift.
-11870157 0 Knockout, ViewModel inside an other object and data-bindingI'm doing a javascript application for a game, the goal is to make a "build calculator" for a MMORPG. I want to synchronize the view with data already stocked in my application. I searched and tested different framework, and knockout-js appeared to be the best solution for me
Html:
<script> var simulatorTool = new SimulatorTool(); </script> <body> <p data-bind="text: test"> </p> <p data-bind="text: test2"> </p> </body>
Javascript Tool:
function SimulatorTool() { meSim = this; this.config = new Config(); this.data = new Data(); this.stuff = new Stuff(); this.traits = new Traits(); this.view = new AppViewModel(); $(function(){ ko.applyBindings(meSim.view); }); ... functions }
View Model:
function AppViewModel() { this.test = "Test!"; this.test2 = ko.computed(function() { return meSim.data.selectedData['profession'] }, this); }
The problem is that i don't know how to bind the html to the view in an other object. I don't even know if it's possible. I'd like to do something like that
<p data-bind="simulatorTool.view, text: test"> </p>
If not, how can i access to the data inside "SimulatorTool" if the view is separated from the application ?
-15100492 0You could do the following. This would set up the toggle function to fire on click of any label with the class toggle
. It would look for the div and checkbox directly within that label.
HTML:
<label class="toggle" for="color_Black"><div style="background-color: #000000" class="color"><div class=CheckMark>✓</div> <input type="checkbox" name="color[]" value="Black" id="Checkbox1" class="cbx"/></div>Black</label>
JS:
$(".toggle").on("click", function toggle_colorbox() { $div = $(this).children('div'); $cb = $(this).find('input'); $innerdiv = $div.find('div'); if (!$cb.is(':checked')) { $innerdiv.show(); $div.addClass("ColorboxSelected"); $cb.prop('checked', true); } else { $innerdiv.hide(); $div.removeClass("ColorboxSelected"); $cb.prop('checked', false); } return false; });
Fiddle: http://jsfiddle.net/aLJwH/1/
EDIT: Answer now featuring working code!
-14593610 0 SELECT rows where seconds since epoch from NOWI am wondering is there a way to select only rows where time since epoch and "now()" is greater than a certain amount of seconds.
I store the rows with a field holding seconds since epoch created from the php function time()
.
So something like this:
SELECT * FROM table WHERE (now - field_time) > 60 seconds
The columns in the output array from predict_proba
are the probabilities of the different labels being predicted by your classifier. In your case, you've built a binary classifier, so the first column modl.predict_proba(X_test)[:,0]
is the probability of the label being 0
and the second column modl.predict_proba(X_test)[:,1]
is the probability of the label being 1
.
Why use dojo? You can use javascript and HTML5
-39840630 0I think there is some issues due to incorrect conversion from factor to numeric variable in your data column 2, the following should fix it (not the point 1.5, 5 is not there anymore):
data[,2] <- as.numeric(as.character(data[,2])) well <- data1[2] bin <-data1[1] data<-data.frame(bin, well) lines(data, type="p", lwd=2.5, lty=1, col=colors, pch=plotchar, grid())
-33420535 1 why doesn't work registration user? i can't registration of user work, just relog the page, someone can help me
form.py
class RegistroUserForm(forms.Form): username = forms.CharField(min_length=5,widget=forms.TextInput(attrs={'class': 'form-control'})) email = forms.EmailField(widget=forms.EmailInput(attrs={'class': 'form-control'})) password = forms.CharField(min_length=5,widget=forms.PasswordInput(attrs={'class': 'form-control'})) password2 = forms.CharField(min_length=5,widget=forms.PasswordInput(attrs={'class': 'form-control'})) def clean_username(self): """Comprueba que no exista un username igual en la db""" username = self.cleaned_data['username'] if AdministracionUsuarios.objects.filter(nombre_de_usuario=username): raise forms.ValidationError('Nombre de usuario ya registrado.') return username def clean_email(self): """Comprueba que no exista un email igual en la db""" email = self.cleaned_data['email'] if AdministracionUsuarios.objects.filter(email=email): raise forms.ValidationError('Este E-mail ya se encuentra registrado.') return email def clean_password2(self): """Comprueba que password y password2 sean iguales.""" password = self.cleaned_data['password'] password2 = self.cleaned_data['password2'] if password != password2: raise forms.ValidationError('Las contraseñas no coinciden.') return password2
i use this to register a user and call in a a page HTML
view.py
def index(request): notifi = Notificaciones.objects.filter(user=request.user.id, Estado=False) usuarios = MiUsuario.objects.filter(nombre_de_usuario=request.user.id) if request.method == 'POST': form = RegistroUserForm(request.POST, request.FILES) if form.is_valid(): # En caso de ser valido, obtenemos los datos del formulario. # form.cleaned_data obtiene los datos limpios y los pone en un # diccionario con pares clave/valor, donde clave es el nombre del campo # del formulario y el valor es el valor si existe. cleaned_data = form.cleaned_data username = cleaned_data.get('username') password = cleaned_data.get('password') email = cleaned_data.get('email') # E instanciamos un objeto User, con el username y password user_model = AdministracionUsuarios.objects.crear_usuario(nombre_de_usuario=username,email=email, password=password) # Y guardamos el objeto, esto guardara los datos en la db. user_model.save() # Ahora, creamos un objeto UserProfile, aunque no haya incluido # una imagen, ya quedara la referencia creada en la db. user_profile = MiUsuario() # Al campo user le asignamos el objeto user_model user_profile.user = user_model # Por ultimo, guardamos tambien el objeto UserProfile user_profile.save() else: # Si el mthod es GET, instanciamos un objeto RegistroUserForm vacio form = RegistroUserForm() context = { 'form': form, 'notifi': notifi, 'usuarios': usuarios } return render(request,'app/index.html',context)
models.py
class AdministracionUsuarios(BaseUserManager): def crear_usuario(self,nombre_de_usuario,nombre_completo,email,Cargo_de_Contacto,Celular,Pagina_web,Numero_de_identificacion,Nombre_de_la_empresa,Telefono,Ext,Genero,Ciudad,password=None): if not email: raise ValueError('Usuario deben tener una dirección de e-mail') if not nombre_de_usuario: raise ValueError('Usuario necesita tener un nombre de usuario') user = self.model( nombre_completo=nombre_completo, nombre_de_usuario=nombre_de_usuario, email=self.normalize_email(email), Cargo_de_Contacto=Cargo_de_Contacto, Celular=Celular, Pagina_web=Pagina_web, Numero_de_identificacion=Numero_de_identificacion, Nombre_de_la_empresa=Nombre_de_la_empresa, Telefono=Telefono, Ext=Ext, Genero=Genero, Ciudad=Ciudad, ) user.set_password(password) user.save(using=self._db) return user def crear_superusuario(self,nombre_de_usuario, email,telefono,password): user = self.crear_usuario(email, nombre_de_usuario=nombre_de_usuario, password=password, telefono=telefono, ) user.is_admin = True user.save(using=self._db) return user
why is wrong with the code, because i don't find the mistake. thanks so much
-40704400 0You can set the data
attribute, by using javascript's setAttribute()
like so:
var theDiv = document.createElement("div"); theDiv.setAttribute('data-x', '4'); theDiv.setAttribute('data-y', '6');
Access them:
console.log(theDiv.getAttribute('data-y'));
And also access the same with jQuery:
$(theDiv).data("x");
-27065370 0 $comics = Comic::orderBy('published_at', 'DESC')->take(2)->get(); $newest_comic = $comics[0]; $previous_comic = $comics[1];
-21536860 0 Both MvvmCross IoC and MvvmCross binding rely on Reflection.
Because of this, users often use "Link SDK assemblies only" and often use "LinkerPleaseIgnore" files.
You can read more about this on:
The MvvmCross nuget packages ship with default "LinkerPleaseIgnore" files - e.g. https://github.com/MvvmCross/MvvmCross/blob/v3.1/nuspec/TouchContent/LinkerPleaseInclude.cs.pp
-20244172 0The problem was in drawer_list_item.xml. In Android 2.x the style attributes starting with "?android:attr/" were not available. Removing them fixed the problem.
-22830370 0 Is there a way to make Spring Thymeleaf process a string template?I would like to write something like :
@Autowired private SpringTemplateEngine engine; .... // Thymeleaf Context WebContext thymeleafContext = new WebContext(request, response, request.getServletContext(), locale); // cached html of a thymeleaf template file String cachedHtml=.... // process the cached html String html=engine.process(cachedHtml, thymeleafContext);
By default, the [process] method can't do that. I can understand from the docs that I need a special Template Resolver :
In order to execute templates, the process(String, IContext) method will be used: final String result = templateEngine.process("mytemplate", ctx); The "mytemplate" String argument is the template name, and it will relate to the physical/logical location of the template itself in a way configured at the template resolver/s.
Does anyone know how to solve my problem ?
The goal is to cache the Thymeleaf templates (files) in strings and then process theses strings rather than the files.
-13486351 0[Solved] Just update Java for Windows plugin for your browser (Firefox, Chrome...) Go to Java site and update Java Firefox plugin.
One more solution is install and use SQLyog;
-32629979 0 How to cancel Picasso requests after fragment transitions in androidI have a fragment with a gridview, which loads say 20 images simultaneously using an adapter. I want to make sure that unfinished Picasso requests terminate gracefully when fragment has disappeared/disposed.
Question
Nothing. Hashing the password on the client is a terrible idea.
Communication between the browser and server should be properly encrypted using SSL (via HTTPS).
Hashing on the client side has two effects:
I am wondering, because I got a website login script and it uses this command:
if(document.getElementById('linkreg')) document.getElementById('linkreg').onclick = function () { ajaxSend(php_fileusr, 'susr='+texts['register'], adboxshow); objLogare.adLogInr(); return false; };
Anyways, this function is triggered when the register for a new account (same thing for recovering account but different script). Anyways, some users weren't able to register because the window never popped up. I figured out that this is caused by the adblock extension. I am wondering if there is any way to replace the command adboxshow
. Does anyone know any alternatives that work the same but won't be blocked?
I am attempting to use a select form that has fields populated from an SQL database. There is a table of stores in the database and I used this method to get those distinct fields into the select tool.
echo '<select name="StoreName" />'."\n"; while ($row = mysqli_fetch_assoc($distinctResult)){ echo '<option value="'.$row["StoreID"].'">'; echo $row["StoreName"]; echo '</option>'."\n"; }; echo '</select>'."\n";
The correct store names show up on the select tool but when I submit the form data, the value of the form doesn't get passed properly. Here in the initial page:
<?php require_once 'login.php'; $connection = mysqli_connect( $db_hostname, $db_username, $db_password, $db_database); if(mysqli_connect_error()){ die("Database Connection Failed: " . mysqli_connect_error() . " (" . mysqli_connect_errno() . ")" ); }; $query = "SELECT * from PURCHASE"; //echo $query; $result = mysqli_query($connection,$query); if(!$result) { die("Database Query Failed!"); }; $distinct = "SELECT DISTINCT StoreName FROM PURCHASE"; $distinctResult = mysqli_query($connection,$distinct); if(!$result) { die("Database Query Failed!"); }; echo '<title>Output 1</title>'; echo '</head>'; echo '<body>'; echo '<h1>Required Output 1</h1>'; echo '<h2>Transaction Search</h2>'; echo '<form action="output1out.php" method="get">'; echo 'Search Store:<br/>'; echo '<br/>'; echo '<select name="StoreName" />'."\n"; while ($row = mysqli_fetch_assoc($distinctResult)){ echo '<option value="'.$row["StoreID"].'">'; echo $row["StoreName"]; echo '</option>'."\n"; }; echo '</select>'."\n"; echo '<input name="Add Merchant" type="submit" value="Search">'; echo '</form>'; mysqli_free_result($result); mysqli_close($connection); ?>
And this is the output page:
<?php $transaction = $_REQUEST["StoreName"]; require_once 'login.php'; $connection = mysqli_connect( $db_hostname, $db_username, $db_password, $db_database); $sql = "SELECT * FROM PURCHASE WHERE StoreName LIKE '%".$transaction."%'"; $result = $connection->query($sql); ?> Purchases Made From <?php echo $transaction ?> <table border="2" style="width:100%"> <tr> <th width="15%">Item Name</th> <th width="15%">Item Price</th> <th width="15%">Purchase Time</th> <th width="15%">Purchase Date</th> <th width="15%">Category</th> <th width="15%">Rating</th> </tr> </table> <?php if($result->num_rows > 0){ // output data of each row while($rows = $result->fetch_assoc()){ ?> <table border="2" style="width:100%"> <tr> <td width="15%"><?php echo $rows['ItemName']; ?></td> <td width="15%"><?php echo $rows['ItemPrice']; ?></td> <td width="15%"><?php echo $rows['PurchaseTime']; ?></td> <td width="15%"><?php echo $rows['PurchaseDate']; ?></td> <td width="15%"><?php echo $rows['Category']; ?></td> <td width="15%"><?php echo $rows['Rating']; ?></td> </tr> <?php } } ?>
I am calling the select
name StoreName
in the output page but it is not passing the value from the drop down. I need to run a query with that term on the second page so I can pull the relevant data for it. If anyone can see what I'm doing wrong, please advise. Thank you.
"hunger"
isn't in the dictionary (that's what the KeyError
tells you). The problem is probably your make_happiness_table
function. I don't know if you've posted the full code or not, but it doesn't really matter. At the end of the function, you return an empty dictionary ({}
) regardless of what else went on inside the function.
You probably want to open your file inside that function, create the dictionary and return it. For example, if your csv file is just 2 columns (separated by a comma), you could do:
def make_happiness_table(filename): with open(filename) as f: d = dict( line.split(',') for line in f ) #Alternative if you find it more easy to understand #d = {} #for line in f: # key,value = line.split(',') # d[key] = value return d
-18848154 0 If you create your layout using Bootstrap grid system it will automatically align the container div to horizontally center, there is no need to any thing. Just follow this code:
<div class="container"> <div class="row"> <div class="span8"> <!-- left column --> </div> <div class="span4"> <!-- right column --> </div> </div> </div>
Further you can check out this page to know how Bootstrap grids works - http://www.tutorialrepublic.com/twitter-bootstrap-tutorial/bootstrap-grid-system.php
-30575424 0 ProGuard not working as expected after Android Studio updateSince I updated Android Studio to version 1.2.1.1
I have the following problem:
Whenever I build a release version / build variant of my app, I get a NoClassDefFoundError
on the Adjust library I have included in the project as a library module.
The stracktrace:
java.lang.NoClassDefFoundError: com.adjust.sdk.AdjustConfig at de.myapp.GlobalApp.prepareAdjust(GlobalApp.java:111) at de.myapp.GlobalApp.onCreate(GlobalApp.java:71) at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:999) at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4151) at android.app.ActivityThread.access$1300(ActivityThread.java:130) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1255) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:4745) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:511) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) at dalvik.system.NativeStart.main(Native Method)
Corresponding part of my code:
AdjustConfig config = new AdjustConfig(this, someString, otherString);
When I turn off Proguard with minifyEnabled false;
in my build.gradle
, the error is gone.
My proguard-rules.pro looks like this:
-keepattributes ** -keep class !android.support.v7.internal.view.menu.**,** {*;} -dontpreverify -dontoptimize -dontshrink -dontwarn **
These Proguard rules might look a bit strange because they do but one thing: obfuscate classes in the android.support.v7.internal.view.menu
package. This procedure is a workaround for a a known issue of the Android Support library on Samsung devices.
Even more confusingly, the NoClassDefFoundError
only occurs only devices running Android < 5.0
.
Any ideas on what the reason could be or how to fix this?
-32935209 0 Why do these RegExes not scraping whole words/strings?I am trying to use the Google Regex Scraper extension to web scrape some items from the Yelp! website. Trying to use this regex to match both US street addresses without parsing. Sorry for the previous confusion
6805 Vista Del Mar Ln
1320 E 200 S
\<span\sitemprop\=\"streetAddress\"\>\"?(\d{1,5}\s[NEWS]?\s?\w*\s\w*\s?\w*?\s?\w*?\"?)\<?b?r?\>?\"?\w+?\s?\w+?\"?\<\/span\>
Help anyone?
-11812394 0 Applescript- combine multiple IF statments and an abbreviation for home foldersI'm trying to make an applescript to make a backup of some files to dropbox. My question was if it was possible to combine multiple IF statmens in my script and if it was possible to make a shorten SET name TO path, like Macintosh HD:Users:svkrzn:Dropbox to ~:Dropbox.
Here is my script:
set destination to "Macintosh HD:Users:svkrzn:Dropbox:Backup" set safari to "Macintosh HD:Users:svkrzn:Library:Safari:Bookmarks.plist" set safariplist to "Macintosh HD:Users:svkrzn:Dropbox:Backup:Safari_Bookmarks.plist" set things to "Macintosh HD:Users:svkrzn:Library:Application Support:Cultured Code:Things:Database.xml" set thingsxml to "Macintosh HD:Users:svkrzn:Dropbox:Backup:THINGS_Database.xml" tell application "Finder" try set S1 to duplicate file safari to folder destination with replacing set T1 to duplicate file things to folder destination with replacing if exists file safariplist then display dialog "It exists." delete file safariplist end if if exists file thingsxml then display dialog "It exists." delete file thingsxml end if set name of S1 to "Safari_Bookmarks.plist" set name of T1 to "THINGS_Database.xml" on error display dialog "Oops, a problem occurred duplicating the file." end try end tell
-14783690 0 Instead of immediately echoing out the responses, try stacking them an array and then outputting the JSON.
<?php //...... $result = arrray(); $result[] = $this->alerts->generate(); $result[] = $this->alerts2->generate(); echo json_encode($result);
-7725531 0 Learn rails first, and then do that application.
Don't try to do both at the same time.
-29826619 0 Adding fields depending on event message in Logstash not workingI have ELK installed and working in my machine, but now I want to do a more complex filtering and field adding depending on event messages.
Specifically, I want to set "id_error" and "descripcio" depending on the message pattern.
I have been trying a lot of code combinations in "logstash.conf" file, but I am not able to get the expected behavior.
Can someone tell me what I am doing wrong, what I have to do or if this is not possible? Thanks in advance.
This is my "logstash.conf" file, with the last test I have made, resulting in no events captured in Kibana:
input { file { path => "C:\xxx.log" } } filter { grok { patterns_dir => "C:\elk\patterns" match => [ "message", "%{ERROR2:error2}" ] add_field => [ "id_error", "2" ] add_field => [ "descripcio", "error2!!!" ] } grok { patterns_dir => "C:\elk\patterns" match => [ "message", "%{ERROR1:error1}" ] add_field => [ "id_error", "1" ] add_field => [ "descripcio", "error1!!!" ] } if ("_grokparsefailure" in [tags]) { drop {} } } output { elasticsearch { host => "localhost" protocol => "http" index => "xxx-%{+YYYY.MM.dd}" } }
I also have tried the following code, resulting in fields "id_error" and "descripcio" with both vaules "[1,2]" and "[error1!!!,error2!!!]" respectively, in each matched event.
As "break_on_match" is set "true" by default, I expect getting only the fields behind the matching clause, but this doesn't occur.
input { file { path => "C:\xxx.log" } } filter { grok { patterns_dir => "C:\elk\patterns" match => [ "message", "%{ERROR1:error1}" ] add_field => [ "id_error", "1" ] add_field => [ "descripcio", "error1!!!" ] match => [ "message", "%{ERROR2:error2}" ] add_field => [ "id_error", "2" ] add_field => [ "descripcio", "error2!!!" ] } if ("_grokparsefailure" in [tags]) { drop {} } } output { elasticsearch { host => "localhost" protocol => "http" index => "xxx-%{+YYYY.MM.dd}" } }
-17998905 0 Using
include 'includes/top.php';
and
include '../includes/top.php';
within the same file are trying to include different files.. If these statements are in a php page at /path/page.php
, the first line would try to include /path/includes/top.php
and the second would look for /includes/top.php
because ../
tells it to go to parent directory. Perhaps both of these files exist? The latter may not have the correct css or something.
There are quite a lot of tools to extract text from PDF files[1-4]. However the problem with most scientific papers is the hardship to get access PDF directly mostly due to the need to pay for them. There are tools that provide easy access to papers' information such as metadata or bibtex , beyond the just the bibtex information[5-6]. What I want is like taking a step forward and go beyond just the bibtex/metadata:
Assuming that there is no direct access to the publications' PDF files, is there any way to obtain at least abstract of a scientific paper given the paper's DOI or title? Through my search I found that there has been some attempts [7] for some similar purpose. Does anyone know a website/tool that can help me obtain/extract abstract or full text of scientific papers? If there is not such tools, can you give me some suggestions for how I should go after solving this problem?
Thank you
[1] http://stackoverflow.com/questions/1813427/extracting-information-from-pdfs-of-research-papers [2] https://stackoverflow.com/questions/6731735/extracting-the-actual-in-text-title-from-a-pdf [3] http://stackoverflow.com/questions/6731735/extracting-the-actual-in-text-title-from-a-pdf?lq=1 [4] http://stackoverflow.com/questions/14291856/extracting-article-contents-from-pdf-magazines?rq=1 [5] https://stackoverflow.com/questions/10507049/get-metadata-from-doi [6] https://github.com/venthur/gscholar [7] https://stackoverflow.com/questions/15768499/extract-text-from-google-scholar
-31531008 0 Looking at your explain output, it looks like you're fetching most of the contents in the documents
table so it's sensibly doing a sequential scan. Your rowcount estimates are reasonable, there doesn't seem to be any stats issue here.
It's doing an external merge sort on disk, so you might see a significant increase in performance by increasing work_mem
in the session, e.g.
SET work_mem = '12MB'
It's possible that an index on (reference_id ASC, created_at DESC) WHERE (approved)
might be useful, since it'll allow results to be fetched in the order required.
You could also experiment with adding viewable_at
to the index. I think it might have to be the last column, but I'm not sure. Or even making it into a covering index by appending viewable_at, id, content
and omitting the unnecessary approved
column from the result set. This may permit an index-only scan, though with DISTINCT ON
involved I'm not sure.
sawa's answer is ok, and also you can use a method like this to dynamically create logger for each class.
However, I prefer not to get all classes under a module. In able to create logger for every single class, you can do things as follow.
module Kernel ####### private ####### def logger Log4r::Logger[logger_name] end def logger_name clazz = self.class unless clazz.respond_to? :logger_name name = clazz.module_eval 'self.name' clazz.define_singleton_method(:logger_name) { name } end clazz.logger_name end end module A module B class C def hello logger.debug logger_name end end end end A::B::C.new.hello
For classes within a specific module you can write a filter in the logger_name
method, for example:
module Kernel ####### private ####### def logger Log4r::Logger[logger_name] end def logger_name clazz = self.class unless clazz.respond_to? :logger_name name = clazz.module_eval 'self.name' name = 'root' unless name.start_with?('A::B') clazz.define_singleton_method(:logger_name) { name } end clazz.logger_name end end module A module B class C def hello logger.debug logger_name end class << self def hello logger.debug logger_name end end end end class D def hello logger.debug logger_name end end end A::B::C.new.hello # A::B::C A::B::C.hello # A::B::C A::D.new.hello # root
And also, you can cache the logger:
def logger _logger = Log4r::Logger[logger_name] self.class.send(:define_method, :logger) { _logger } self.class.define_singleton_method(:logger) { _logger } return _logger end
Hope it helps.
-3429683 0I'd would dinamically set the limit by constantly checking the average load/cpu usage/query time of the database... That way when there are a few users online they can do their work faster. You could set a "maximum" like twitter and if total-load > max-load-you-want maximum=150% and so on...
On one of the service-based sites i've applied this method it actually removed 60% of the spikes after i told the users about the change...
It seems that method: 'feed' within FB.ui() using FB JavaScript SDK is broken. Consider the following example:
We always get the following error, now even with apps that formerly worked:
"An error occurred with xxx. Please try again later.
API Error Code: 191
API Error Description: The specified URL is not owned by the application
Error Message: redirect_uri is not owned by the application."
can anyone help me? I am trying to figure out how to get nice, smooth edges for this SVG path (currently drawing it with Raphael). Here is a CodePen mockup of the problem (you might need to scroll down to see the diagonal line in the window - it's a bit offset from the top).
http://codepen.io/anon/pen/qbxYOg
<DOCTYPE html> <body> <div style="width:3484px; height:2000px;"> <svg style="width:100%; height:100%;"> <path fill="#fe0000" stroke="#fe0000" d="M606.182,649.872L739.73,670.2349999999999M743.215,670.366C742.902,669.307,741.7900000000001,668.702,740.73,669.015C739.6700000000001,669.33,739.066,670.442,739.38,671.501C739.694,672.5609999999999,740.806,673.165,741.865,672.851C742.925,672.538,743.53,671.425,743.215,670.366ZM594.333,649L463.09799999999996,628.047M459.614,627.881C459.917,628.943,461.02299999999997,629.559,462.085,629.256C463.14799999999997,628.953,463.763,627.845,463.46,626.784C463.156,625.721,462.04999999999995,625.106,460.988,625.409C459.927,625.713,459.311,626.819,459.614,627.881Z" style="transform: scale(.75); fill: red; stroke: red; stroke-width: 4px"></path> </svg> </div> </body> </html>
Basically the issue is that the line appears very jagged with no smoothing/antialiasing and I need to be able to scale this SVG path from 100% zoom to 50% zoom for an interactive map. Scaling it down makes the edges look jagged, but I am only noticing this problem for lines on a diagonal...
Would anyone be able to help me fix this?
Thanks a bunch!
-16948146 0Made my own version without itertools.
def expander(inpt): ret = [] for token in inpt.split(','): if '-' in token: a, b = token.strip().split('-') ret.extend(range(int(a), int(b)+1)) else: ret.append(int(token)) return ret print(expander('1, 3-4, 7-9'))
Keep in mind it would be healthy to check this string with regex.
-14151028 0I know you didn't ask this, and I'm not sure about the problem you are solving, but your code where you manipulate the size of the FormItems outside of the standard lifecycle functions kind of smells funny. Just a suggestion.
-26966030 0 How to clear specific input field in jqueryI have a form. After getting a specific string from a jQuery Ajax request, I want to clear some input fields of a form by jQuery id selector. What should I do ?
My jQuery code:
$.post(site_url.concat('xml_request/cert.php') , { special_code:special_code , cert_id_name:cert_id_name , recive_date:sector_dob5 , about_cert:about_cert } , function(data){ $('#add_cert_feedback').html(data); if (data.indexOf('New Certificate is now Added') !== -1) { //Want to reset a Input field here } else { $('#the_heck').html('shit!'); } $.post(site_url.concat('xml_request/cert.php') , { special_code:'_get_array_cert' } , function(data){ $('#cert_load').html(data); }); });
-13008388 0 about service perform refresh operations in the background I have 3 activity:Act_1, Act_2 and Act_3
, and a service:RefreshService
.
I want when the user clicks the home button,RefreshService
stops refresh operations.
now,i override the Act_1.onStop()
method to stop refresh,but when Act_1
start to Act_2
,the refresh stop too,This is not what I want.
And i override the Act_1.onKeyDown()
method, it's not good too.
Do you have any good design
-14523834 0 Django Formset Not Cleaning/Saving ProperlyI'm using inlineformset_factory to create a formset. The parent object is a featured set and the child objects are featured items. I'm using the 'django-dynamic-formset' jQuery plugin on the front end to add/remove formset forms dynamically.
While each form in the formset is getting submitted with the proper data as expected, cleaned_data only contains the form's id.
View:
@login_required @csrf_protect def edit_featured_set(request, fset_id): ''' Edit a featured set and its items ''' c = {} c.update(csrf(request)) # get existing featured set for this id (if exists) if fset_id and int(fset_id) > 0: try: fset_obj = Featureditemset.objects.get(id=fset_id) except Featureditemset.DoesNotExist: # bad or no id passed return HttpResponse('ObjectDoesNotExist') else: # get new featured set object fset_obj = Featureditemset(id = get_next_auto_inc(Featureditemset)) # define formset to work with featured items FeaturedItemFormSet = inlineformset_factory(Featureditemset, Featureditem, extra=1, form=FeatureditemEditForm) if request.method == 'POST': form = FeatureditemsetEditForm(request.POST, request.FILES, instance=fset_obj, prefix='set') if form.is_valid(): featured_item_formset = FeaturedItemFormSet(request.POST, request.FILES, instance=fset_obj, prefix='item') if featured_item_formset.is_valid(): # save form form.save() # save formset print 'Formset: %s' % str(featured_item_formset) print 'cleaned_data: %s' % featured_item_formset.cleaned_data featured_item_formset.save() return HttpResponse('valid') else: form = FeatureditemsetEditForm(instance=fset_obj, prefix='set') featured_item_formset = FeaturedItemFormSet(instance=fset_obj, prefix='item') c['form'] = form c['formset'] = featured_item_formset return render_to_response('admin/edit_featured.html', c, context_instance = RequestContext(request))
Forms:
class FeatureditemEditForm(ModelForm): class Meta: model = Featureditem fields = ('id','img', 'name', 'folio') class FeatureditemsetEditForm(ModelForm): class Meta: model = Featureditemset fields = ('name', 'application')
Models:
class Featureditemset(models.Model): id = models.BigIntegerField(primary_key=True, db_column='FEATUREDITEMSET_ID') application = models.ForeignKey(Application, null=True, db_column='FEATUREDITEMSET_APPLICATION_ID', blank=True) htmlcontent = models.TextField(db_column='FEATUREDITEMSET_HTMLCONTENT', blank=True) modified = models.DateTimeField(db_column='FEATUREDITEMSET_MODIFIED', auto_now=True) viewer = models.ForeignKey(Viewer, null=True, db_column='FEATUREDITEMSET_VIEWER', blank=True) name = models.CharField(max_length=192, db_column='FEATUREDITEMSET_NAME', blank=True) class Meta: db_table = u'featureditemset' def __unicode__(self): return str(self.name) class Featureditem(models.Model): id = models.BigIntegerField(db_column='FEATURED_ITEM_ID', primary_key=True) img = models.FileField(upload_to='featured', db_column='FEATURED_ITEM_IMG_URL', blank=True) alt_title = models.CharField(max_length=768, db_column='FEATURED_ITEM_ALT_TITLE', blank=True) modified = models.DateTimeField(db_column='FEATURED_ITEM_MODIFIED', auto_now=True) folio = models.ForeignKey(Folio, db_column='FEATURED_ITEM_FOLIO_ID', blank=False) app = models.ForeignKey(Application, null=True, db_column='FEATURED_ITEM_APP_ID', blank=True) name = models.CharField(max_length=192, db_column='FEATURED_ITEM_NAME', blank=True) featureditemset = models.ForeignKey(Featureditemset, null=True, db_column='FEATUREDITEM_FEATUREDITEMSET_ID', blank=True) def __unicode__(self): return self.name class Meta: db_table = u'featureditem'
Output to console:
Formset: <input type="hidden" name="item-TOTAL_FORMS" value="1" id="id_item-TOTAL_FORMS" /><input type="hidden" name="item-INITIAL_FORMS" value="1" id="id_item-INITIAL_FORMS" /><input type="hidden" name="item-MAX_NUM_FORMS" id="id_item-MAX_NUM_FORMS" /> <tr><th><label for="id_item-0-id">Id:</label></th><td><input type="text" name="item-0-id" value="5" id="id_item-0-id" /></td></tr> <tr><th><label for="id_item-0-img">Featured Image:</label></th><td><input type="file" name="item-0-img" id="id_item-0-img" /></td></tr> <tr><th><label for="id_item-0-name">Name:</label></th><td><input id="id_item-0-name" type="text" name="item-0-name" value="item1" maxlength="192" /></td></tr> <tr><th><label for="id_item-0-folio">Folio:</label></th><td><select name="item-0-folio" id="id_item-0-folio"> <option value="1" selected="selected">0000054220110900000025</option> <option value="2">com.maned.kwmultitest</option> </select></td></tr> <tr><th><label for="id_item-0-DELETE">Delete:</label></th><td><input type="checkbox" name="item-0-DELETE" id="id_item-0-DELETE" /><input type="hidden" name="item-0-featureditemset" id="id_item-0-featureditemset" /></td></tr> cleaned_data: [{'id': 5}]
-33895965 0 Instead of triggering a login on every launch, you can check the status of the access token. If it's not expired, you skip login, and just start using the API. The following method can be used to check if the token is expired:
+(BOOL) accessTokenIsLocalyValid { return [FBSDKAccessToken currentAccessToken] && [[NSDate date] compare:[FBSDKAccessToken currentAccessToken].expirationDate] == NSOrderedAscending; }
If you have a valid token, you can refresh it using [FBSDKAccessToken refreshCurrentAccessToken:]
.
I am not sure why, but in an attempt to update my answer to a question here, I decided it might be best to hide the old answer as a spoiler.
I am having issues with this triggering a "Code Format" error that makes markdown think I am creating code that isn't properly formatted.
I found that leaving the text in a block quote workes fine, and that leaving a single spoiler line works, but trying to use multi-line spoilers with linebreaks (including the example posted on the page requesting/noting the feature), will cause the formatting error in question.
This error seams to result from having a block of code earlier in the answer, and then the multi-line spoiler seems to cause errors in MarkDown.
In the end I just put it in a block quote, but I wasn't sure if anyone knew of a way to resolve this.
-2244274 0Transliterate any relevant punctuation to words. C++ -> Cplusplus, C# -> Csharp, PL/SQL -> PLslashSQL
-12338176 0It is not possible.
I refer to the following part of Matlab documentation:
Valid Names
A valid variable name starts with a letter, followed by letters, digits, or underscores. MATLAB is case sensitive, so A and a are not the same variable. The maximum length of a variable name is the value that the namelengthmax command returns.
Letter is defined as ANSI character between a-z
and A-Z
. For example, the following hebrew letter Aleph
returns false
:
isletter('א')
By the way, you can always check whether your variable name is fine by using genvarname
.
genvarname('א') ans = x0x1A
-35120851 0 Just for those whom might encounter the same problem...
I just found the answer for it. Because of the database I am using is postgresql, I had to change the property "hibernate.dialect" in the persistence file. So, the result after the change was:
After that, the table was created!
Thank you.
-24659922 0 Can't boot into OSXI have two HDs in my Macbook Pro 15 in late 2009. I installed bootcamp and updated to Mavericks. My Windows partition in running Win7 Ultimate. I set the the boot disk in OSX to be my windows partition and now my laptop doesn't recognize me holding down the option key to choose which partition to boot. When windows boots i have to start the on screen keyboard and then close it for my keyboard presses to be recognized. The quote key causes the option and control keys to stick and delete doesn't work at all. I would use the bootcamp panel to switch back but it didn't install. i would really appreciate any help because i'm behind in my web dev projects and don't want to reinstall OSX because i'll lose my data, plus i took out the disc drive for my other HD.
-180545 0I create a database alias on each server to point to the database. I then use this alias in my web.config files. If I need to change which database the application points to, then I change the alias and not the web.config.
For SQL Server, go to SQL Server Configuration Manager > SQL Native Client Configuration > Aliases > Create New Alias.
You can do the same thing with Oracle with the tnsnames file.
-16232230 0Suggestion #1: The simplest way should be using TCP. You mentioned your data size is large. Unless your data size is too huge, you should be fine using TCP. Ensure you make separate threads in C and Python for transmitting/receiving data over TCP.
Suggestion #2: Python supports wrappers over C. One popular wrapper is ctypes - http://docs.python.org/2/library/ctypes.html
Assuming you are familiar with IPC between two C programs through shared-memory, you can write a C-wrapper for your python program which reads data from the shared memory.
Also check the following diccussion which talks about IPC between python and C++: Simple IPC between C++ and Python (cross platform)
-25814207 0Core Plot doesn't care where the data comes from. It's up to the datasource to translate it to numeric values before passing them to the plot. JSON parsing is outside the scope of a plotting library like Core Plot.
I'm not sure what you're asking in #2. It's easy to update the plot with new data and resize the visible parts of the plot area to display it, but that's the responsibility of the controller object and the datasource.
Core Plot is for display only. Any interaction with external services is the responsibility of the controller object.
library(data.table) library(reshape2) library(lubridate) df = fread("/storage/Downloads/Watertable_fluctuations_All_Original.txt", skip = 1, header = T) # dropbox file df = df[, date := dmy(date)] dfm = melt(df, id.vars = "date", value.name = "water.level") wl.threshold = -0.22 dfm[water.level < wl.threshold,.N, keyby = variable] # count per measuring station # bonus library(openair) timePlot(dfm[variable == "Yel342(2010)"], pollutant = "water.level", smooth = T, ref.y = wl.threshold)
I figured it out. The object is returned afterall. It can be accessed with:
results = indexer.search(word).prefetch() for hit in results: print hit.instance.model_attribute
where model_attribute
would be an existing variable of the object returned
I believe class functions can be called upon as well in the model_attribute spot, (with bracket added in the end)
but note that when searching cross-models, the 'model_attribute
' may or may not exist for different models. So that may lead to errors.
I wish djapian had more documentation on this, as I couldn't find it at all
-31193926 0 20 Crontab Messages In Order Staggered Every 15 MinutesI'm trying to send messages every 15 minutes. I have 20 messages, and I want each message to be sent about 15 minutes apart, i.e. message 3 is sent 15 minutes after message 2, message 4 15 minutes after message 3. Right now I'm just trying to stagger the contab jobs, but is there a more efficient/elegant solution? Thanks for the help!
14,29,44,59 10-21 * * * wget -q http://site/message2.php 13,28,43,58 10-21 * * * wget -q http://site/message3.php 12,27,43,57 10-21 * * * wget -q http://site/message4.php 11,26,42,56 10-21 * * * wget -q http://site/message5.php 10,25,41,55 10-21 * * * wget -q http://site/message6.php 9,24,40,55 10-21 * * * wget -q http://site/message7.php 8,23,39,54 10-21 * * * wget -q http://site/message8.php 7,22,38,53 10-21 * * * wget -q http://site/message9.php 6,21,37,52 10-21 * * * wget -q http://site/message10.php 5,20,36,51 10-21 * * * wget -q http://site/message11.php 4,19,35,50 10-21 * * * wget -q http://site/message12.php 3,18,34,49 10-21 * * * wget -q http://site/message13.php 2,17,33,48 10-21 * * * wget -q http://site/message14.php 1,16,33,47 10-21 * * * wget -q http://site/message15.php 0,15,32,46 10-21 * * * wget -q http://site/message16.php 14,31,45,59 10-21 * * * wget -q http://site/message17.php 13,30,44,58 10-21 * * * wget -q http://site/message18.php 12,28,43,57 10-21 * * * wget -q http://site/message19.php 11,27,42,56 10-21 * * * wget -q http://site/message20.php
-36238231 0 How to run supervised LDA I did topic modeling on my documents using topicmodels package. Now, I want to do supervised LDA. I used this function to convert my topicmodels output to lda package output. But, now I don't know how to run slda and interpret the results.
Here's the code I have so far:
# A function that converts topicmodels output to lda output topicmodels_json_ldavis <- function(fitted, corpus, doc_term){ # Required packages library(topicmodels) library(dplyr) library(stringi) library(tm) library(LDAvis) # Find required quantities phi <- posterior(fitted)$terms %>% as.matrix theta <- posterior(fitted)$topics %>% as.matrix vocab <- colnames(phi) doc_length <- vector() for (i in 1:length(corpus)) { temp <- paste(corpus[[i]]$content, collapse = ' ') doc_length <- c(doc_length, stri_count(temp, regex = '\\S+')) } temp_frequency <- inspect(doc_term) freq_matrix <- data.frame(ST = colnames(temp_frequency), Freq = colSums(temp_frequency)) rm(temp_frequency) # Convert to json json_lda <- LDAvis::createJSON(phi = phi, theta = theta, vocab = vocab, doc.length = doc_length, term.frequency = freq_matrix$Freq) return(json_lda) } ## end of function docs <- tm_map(docs, removePunctuation) docs <- tm_map(docs, removeNumbers) docs <- tm_map(docs, content_transformer(tolower)) docs <- tm_map(docs, removeWords, stopwords("english")) library(SnowballC) docs <- tm_map(docs, stemDocument) docs <- tm_map(docs, stripWhitespace) tfm <- DocumentTermMatrix(docs) # remove empty documents library(slam) tfm = tfm[row_sums(tfm)>0,] # Use topicmodels package to conduct LDA analysis. library(topicmodels) results5 <- LDA(tfm, k = 5, method = "Gibbs") ### converting topicmodels output to lda output ldaoutput = topicmodels_json_ldavis(lda,corpus, dtm)
Now I don't know how to run supervised lda and interpret it.
I really appreciate your help.
-37583068 0Include your card_view
after AppBarLayout
and setheight
for AppBarLayout
instead ImageView
and make ImageView
height
match_parent
I have searchDisplayController,which is table headerView of my tableView.My tableview scrolling works smooth and perfect and tableview consist of 3 rows.My issue is my tableView scrolls to top,then bounce back at that time my tableViewHeader(UIsearchbar) cannot seen it goes to behind the navigation bar.Then scroll to down i can see my tableViewHeader(UISearch bar). When first time view loading the contentOffset on my console is {0,0},then scroll to top and bounce back at that time my contentOffset last value on my console is {0,44}.How to solve this issue?Please help me..
-37444588 0You could probably do it in a line!
messages = [string for string in messages if not any(word in bannedWords for word in string)]
-7132657 0 The following should work:
<%# GetGreeting(DataBinder.Eval(Container.DataItem, "FullName").ToString()) %>
or a shorter form:
<%# GetGreeting(Eval("FullName").ToString()) %>
-28574002 0 1.First thing is to conform to the UISearchbarDelegate.
2.Set the search bar delegate to self.
You can find more on this here Swift iOS tutorial : Implementing search using UISearchBar and UISearchBarDelegate
-27661125 0 Unable to open XLSX file using Apache POI: NoClassDefFoundErrorI'm having problems trying to open an XLSX file with Apache POI.
My code:
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelTest { public static void main(String[] args) { try(FileInputStream f = new FileInputStream(new File("path/to/my/file.xlsx"))) { XSSFWorkbook wb = new XSSFWorkbook(f); // This is the line throwing the exception } catch(IOException e) { System.err.println(e.getMessage()); e.printStackTrace(System.err); } } }
Exception thrown:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/xmlbeans/XmlException at my.TEST.ExcelTest.main(ExcelTest.java:24) Caused by: java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlException at java.net.URLClassLoader$1.run(URLClassLoader.java:366) at java.net.URLClassLoader$1.run(URLClassLoader.java:355) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:354) at java.lang.ClassLoader.loadClass(ClassLoader.java:425) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) at java.lang.ClassLoader.loadClass(ClassLoader.java:358) ... 1 more
Background:
poi-3.11-20141221.jar
poi-ooxml-3.11-20141221.jar
poi-ooxml-schemas-3.11-20141221.jar
commons-codec-1.9.jar
log4j-1.2.17.jar
I can't even start doing the real stuff, since I can't even open the book! :(
When I saw the exception, I thought "Ok, let's get xmlbeans and see if it works", but xmlbeans is moved into Apache's attic.
Am I missing something? How can I open the workbook?
-30666492 0Use a delegated event handler :
$('#table').on('click', '.pay-btn', function(e) {
dataTables inject and remove table rows to the DOM in order to show pages. Thats why your event handler not is working except from page #1.
NB: Dont know what your <table>
id
is - replace #table
with your id
.
I'm trying to parse a json file and push fields to database jSON Source : http://graph.facebook.com/10153575791993298/
Parsing and Echo
<?php $json_file = file_get_contents('http://graph.facebook.com/10153575791993298/'); $info = json_decode($json_file); if ($info) { foreach ($info->likes->data as $obj){ echo $obj->id, "<br/>"; echo $obj->name, "<br/>"; } } ?>
Database part :
<?php // Create connection $mysqli = new mysqli('localhost', 'root', 'root', 'facebook'); $query = <<<SQL INSERT INTO Likes ('ID', 'Name') VALUES (?, ?) SQL; $stmt = $mysqli->prepare($query); foreach ($info['data'] as $key => $value) { $stmt->bind_param( // the types of the data we are about to insert: s = string, i = int 'ss', $value['id'], $value['name'], ); $stmt->execute(); } $stmt->close(); $mysqli->close(); ?>
I setup my tables correctly and I don't know why I can't push data to my database. Json part that I would like to retrieve data and push to my db http://graph.facebook.com/10153575791993298/likes
This should work:
$(".checkall").click(function(){ var $table = $(this).closest("table"); var col = $(this).closest("tr").children().index($(this).closest("td")); var index = col + 1; // offset for nth-child $table.find("td:nth-child("+index+") input:checkbox").attr("checked",$(this).is(":checked")); });
-13788974 0 iPhone: Can't scroll over a UIWebView contained in a tableView I've seen many similar questions on the web, i've tried many approaches but none worked.
I have a UITableview which contains custom cells and some UIWebViews, the problems is that i can't scroll the UITableView if the scroll starts on the UIWebview.
The closest I got is by setting webView.userInteractionEnabled to NO but then I can't access the link anymore...
Do you have any idea or pointers on how to do it ?
-36917116 0--ext
allows using custom javascript extensions, you can't force ESLint to work for languages other than JavaScript by passing a different file extension to it.
You can try using typescript-eslint-parser to enable ESLint for Typescript - it allows building a syntax tree from typescript code that can be passed to ESLint for linting.
But I'd suggest using Typescript linters for inspecting TypeScript code. You can try TSLint, for example.
-1588517 0For each column that has no default value or you want to insert the values other than default, you will need to provide the explicit name and value.
You only can use an implicit list (*
) if you want to select all columns and insert them as they are.
Since you are changing the PRIMARY KEY
, you need to enumerate.
However, you can create a before update trigger and change the value of the PRIMARY KEY
in this trigger.
Note that the trigger cannot reference the table itself, so you will need to provide some other way to get the unique number (like a sequence):
CREATE TRIGGER trg_mytable_bi BEFORE INSERT ON mytable FOR EACH ROW BEGIN :NEW.id := s_mytable.nextval; END;
This way you can use the asterisk but it will always replace the value of the PRIMARY KEY
.
Like Christian Conkle hinted at, we can determine if a type has an Integral
or Floating
instance using more advanced type system features. We will try to determine if the second argument has an Integral
instance. Along the way we will use a host of language extensions, and still fall a bit short of our goal. I'll introduce the following language extensions where they are used
{-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE OverlappingInstances #-}
To begin with we will make a class that will try to capture information from the context of a type (whether there's an Integral
instance) and convert it into a type which we can match on. This requires the FunctionalDependencies
extension to say that the flag
can be uniquely determined from the type a
. It also requires MultiParamTypeClasses
.
class IsIntegral a flag | a -> flag
We'll make two types to use for the flag
type to represent when a type does (HTrue
) or doesn't (HFalse
) have an Integral
instance. This uses the EmptyDataDecls
extension.
data HTrue data HFalse
We'll provide a default - when there isn't an IsIntegral
instance for a
that forces flag
to be something other than HFalse
we provide an instance that says it's HFalse
. This requires the TypeFamilies
, FlexibleInstances
, and UndecidableInstances
extensions.
instance (flag ~ HFalse) => IsIntegral a flag
What we'd really like to do is say that every a
with an Integral a
instance has an IsIntegral a HTrue
instance. Unfortunately, if we add an instance (Integral a) => IsIntegral a HTrue
instance we will be in the same situation Christian described. This second instance will be used by preference, and when the Integral
constraint is encountered it will be added to the context with no backtracking. Instead we will need to list all the Integral
types ourselves. This is where we fall short of our goal. (I'm skipping the base Integral
types from System.Posix.Types
since they aren't defined equally on all platforms).
import Data.Int import Data.Word import Foreign.C.Types import Foreign.Ptr instance IsIntegral Int HTrue instance IsIntegral Int8 HTrue instance IsIntegral Int16 HTrue instance IsIntegral Int32 HTrue instance IsIntegral Int64 HTrue instance IsIntegral Integer HTrue instance IsIntegral Word HTrue instance IsIntegral Word8 HTrue instance IsIntegral Word16 HTrue instance IsIntegral Word32 HTrue instance IsIntegral Word64 HTrue instance IsIntegral CUIntMax HTrue instance IsIntegral CIntMax HTrue instance IsIntegral CUIntPtr HTrue instance IsIntegral CIntPtr HTrue instance IsIntegral CSigAtomic HTrue instance IsIntegral CWchar HTrue instance IsIntegral CSize HTrue instance IsIntegral CPtrdiff HTrue instance IsIntegral CULLong HTrue instance IsIntegral CLLong HTrue instance IsIntegral CULong HTrue instance IsIntegral CLong HTrue instance IsIntegral CUInt HTrue instance IsIntegral CInt HTrue instance IsIntegral CUShort HTrue instance IsIntegral CShort HTrue instance IsIntegral CUChar HTrue instance IsIntegral CSChar HTrue instance IsIntegral CChar HTrue instance IsIntegral IntPtr HTrue instance IsIntegral WordPtr HTrue
Our end goal is to be able to provide appropriate instances for the following class
class (Num a, Num b) => Power a b where pow :: a -> b -> a
We want to match on types to choose which code to use. We'll make a class with an extra type to hold the flag for whether b
is an Integral
type. The extra argument to pow'
lets type inference choose the correct pow'
to use.
class (Num a, Num b) => Power' flag a b where pow' :: flag -> a -> b -> a
Now we'll write two instances, one for when b
is Integral
and one for when it isn't. When b
isn't Integral
, we can only provide an instance when a
and b
are the same.
instance (Num a, Integral b) => Power' HTrue a b where pow' _ = (^) instance (Floating a, a ~ b) => Power' HFalse a b where pow' _ = (**)
Now, whenever we can determine if b
is Integral
with IsIntegral
and can provide a Power'
instance for that result, we can provide the Power
instance which was our goal. This requires the ScopedTypeVariables
extension to get the correct type for the extra argument to pow'
instance (IsIntegral b flag, Power' flag a b) => Power a b where pow = pow' (undefined::flag)
Actually using these definitions requires the OverlappingInstances
extension.
main = do print (pow 7 (7 :: Int)) print (pow 8.3 (7 :: Int)) print (pow 1.2 (1.2 :: Double)) print (pow 7 (7 :: Double))
You can read another explanation of how to use FunctionalDependencies
or TypeFamilies
to avoid overlap in overlapping instances in the Advanced Overlap article on HaskellWiki.
Stolen from previous post: Finding untagged elements with javascript
var nodes = document.getElementsByTagName('body').childNodes for (i=0; i < nodes.length; i++) { if(nodes.childNode[i].nodeType == 3) { //THIS NODE IS A TEXT NODE OF THE BODY ELEMENT //DO WHAT YOU NEED WITH IT } }
-13480990 0 linkout failing with conflicting JSESSIONID I have an issue with the linkout of my application (say App2) on another application (say App1).
Both are web applications and so both are creating there own JSESSION IDs. The linkout opens in a pop up and single sign on works (siteminder passing the sm user cookie), but as soon as I perform any transaction on the linked application I am thrown out stating the session is either timed out or invalid.
I looked at the cookies present on the browser and found that both the JSESSION IDs are present. The only difference is in the domain scope of both the JSESSION IDs. App1 application has domain scope of say abc.com whereas App2 has app2.abc.com
I tried changing the name of the JSESSION ID cookie of App2 but the application did not work with the renamed JSESSION cookie.
Any suggestion on how can I fix this ?
Note : The environment for App2 is was5
Regards AVN
-34150023 0Although, moving the code to change colour inside the event handler will work, I'd suggest to use classList
API.
Create a CSS class to set the background color to blue and toggle this class when the box is clicked.
classList.toggle('className')
will add the class if it is not already added on the element otherwise it'll remove the class.
document.getElementById("box").addEventListener("click", function() { document.getElementById('circle').classList.toggle('blue'); });
#box { width: 50px; height: 50px; position: absolute; bottom: 0; right: 0; background-color: red; } #circle { width: 50px; height: 50px; background: orange; border-radius: 50px; position: absolute; top: 50%; left: 50%; } #circle.blue { background: blue; }
<div id="box"></div> <div id="circle"></div>
While building web applications I'm wondering how long of a secret I need (how many bits) for serving as the key in encryption - and whether I can just mash out a random sequence of characters on my keyboard or if I need some special software to generate something for me?
(i.e. stealing the private RSA from something like ssh-keygen)
Update: I manly will be using this key with PHP's mcrypt library but am also interested in c++ options (both on linux).
-4628503 0The answer is pretty simple, clearing the FLAG_FULLSCREEN
flag is all thats necessary:
if (isStatusBarVisible) getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); else getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
-4198356 0 Real-world Complex Rails applications? For my self-education purposes, I would like to investigate the code of a complex Ruby On Rails (preferably 3) business application(s) so that I can get the feel of how to do things in the real world with Rails.
There are tons of "another blog" or "another CMS", but I am really looking into a Rails app with pretty high complexity (in terms of business rules), but not only the CRUDs.
Something like Real-estate systems must be complex enough. Or maybe in the government area (which is always complex by definition :) ).
Thanks.
-18636556 0 Windows Phone MultiSelect ListBox selected itemsFor about three hours, I've been trying to get selected indexes of a multiselect listbox. I tried variety of solutions but they don't work. The final thing I've found is the following;
for (int i = 0; i < this.myListBox.Items.Count; i++) { ListBoxItem currentItem = this.myListBox.ItemContainerGenerator.ContainerFromIndex(i) as ListBoxItem; if (currentItem != null && currentItem.IsSelected) { ApplicationManager.Instance.getContactManager().addToIndexes(i); } }
This seems to work but when I scroll-down in the list for example, listboxitem of previously selected items returns null. How can I accomplish this task?
-41073589 0If the parts to remove are always the same you can use str_replace()
function passing as serach value an array with both parts you want to remove
function remove_strings($string) { return str_replace(array('LifeSteal ', ' \n'), '', $string); }
-30344069 0 Youtube PHP APi Check VIdeo Is Duplicate Or Not Hi I am using Google PHP API to upload video in PHP. I have followed this tutorial to implement this and it is working fine. But there is a problem if video is already exist in my channel it is also returning the video details and I can't find it is a rejected for duplicate.
So I cant find this is a duplicate video or not and if it is duplicate then what is the main video. Means the video details of main video from which it is compared as duplicate.
Please help me to find this is a duplicate video or not?
-9943617 0Do I understand it correctly? You want to invoke something like...
postUser(user); postFile(myFile);
and in the client, to process the two different requests in some stateful manner(the receiver is supposed to know that ).
@Post public void userPost(String name) { User.getInstance().addUser(name); } @Post public void filePost(File file) { //processing the file, ONLY IF the userPost method is already invoked }
Instead, can you encapsulate the two requests in one(one request with two parameters). Something like
postUserFile(user,file);
And in the request reciever...
@Post public void nameFilePost(String name, File file) { userPost(name); filePost(file) }
I don't recognize the framework which you are using, but in JAX-RS the method will looks something like this
@PATH("/yourPath/") public class YourClassNameHere{ @POST public void nameFilePost(@QueryParam("name") String name, @QueryParam("file") File file) { userPost(name); filePost(file) } }
One last thing: Don't use Singletons, they are global variables, and therefore bad. Why global variables are bad.
-29222313 0Your problem is that you are creating a local
variable in the first function and are referring to it in the second function which does not exist. if you make the icon variable global
, everything will work fine.
so your code may look like this:
var icon; $('li.social-list').hover( function(){ icon = $(this).html(); $(this).stop().animate({ width: "100px"}, 1000).text('Facebook'); }, function(){ $(this).stop().animate({ width: "50px"}, 1000).html(icon); } );
Update:
So here is the new code, which you should have two texts or one text and one image for each item and display one of them at a time:
HTML:
<div id="social-slide"> <ul> <li class="social-list"><a><i class="fa fa-facebook fa-2x"><span class="text1">1</span><span class="text2" style="display:none;">facebook</span></i></a></li> <li class="social-list"><a><i class="fa fa-twitter fa-2x"><span class="text1">2</span><span class="text2" style="display:none;">twitter</span></i></a></li> <li class="social-list"><a><i class="fa fa-instagram fa-2x"><span class="text1">3</span><span class="text2" style="display:none;">linkedin</span></i></a></li> <li class="activate"><a><i class="fa fa-bars fa-2x">click</i></a></li> </ul> </div>
JS:
$('li.social-list').hover( function(){ $(this).stop().animate({ width: "100px"}, 1000); $(this).find(".text1").hide(); $(this).find(".text2").show(); }, function(){ $(this).stop().animate({ width: "50px"}, 1000); $(this).find(".text2").hide(); $(this).find(".text1").show(); } );
I think you can get the idea from this sample code.
Hope it helps you
-36754045 01: Recently Cognito launched User Pools feature. This will enable you to do custom signup/login. See: Your user pools
2: An identity is a unique identifier for the end user. If you use Cognito sync to store the data, 1 identity can have 20 datasets each of max size 1 MB. You can have as many identities (end users) as you want. You can as well store data in S3 and use Cognito vended temporary and scoped credentials to access to S3 data.
-37254777 0Here is a nasty, hacky, quick-fix solution which will stop the nasty cropping by resizing Swing's own icons to 80%.
In main
, add this:
String[] iconOpts = {"OptionPane.errorIcon", "OptionPane.informationIcon", "OptionPane.warningIcon", "OptionPane.questionIcon"}; for (String key : iconOpts) { ImageIcon icon = (ImageIcon) UIManager.get(key); Image img = icon.getImage(); BufferedImage bi = new BufferedImage( img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB); java.awt.Graphics g = bi.createGraphics(); g.drawImage(img, 0, 0, (int) (img.getWidth(null) * 0.8), (int) (img.getHeight(null) * 0.8), null); ImageIcon newIcon = new ImageIcon(bi); UIManager.put(key, newIcon); }
You might want to first check whether this is actually required - Windows 8/10 defaults to 125% but some people will switch it back to 100%. I haven't found an elegant way to do this, but something along these lines will give you an idea:
java.awt.Font font = (java.awt.Font) UIManager.get("Label.font"); if (font.getSize() != 11) { //resize icons in here }
-36063051 0 nginx location match on ssl_client_verify I'm trying to setup nginx in order to match certain URL on server where conditional access is granted (i.e. only those with valid client certificate are allowed to access this area).
Right now, simple location block works fine preventing access to unauthorized users:
location ~ ^/protected/ticketing { if ($ssl_client_verify != SUCCESS) { return 401; } #need treatment of php files here after SUCCESS = $ssl_client_verify ?! }
So no one can access /protected/ticketing/anyThingHere
BUT. When you actually present a valid certificate, and this return 401 does not trigger, /protected/ticketing/index.php is not parsed by an upstream FPM server but instead is presented for download (i.e. content disposition is set to default octet stream).
Is there an elegant way of doing this?
My upstream is defined as:
upstream backend { server unix:/var/run/php5-fpm.sock; }
PHP handler location block:
location ~ [^/]\.php(/|$) { fastcgi_split_path_info ^(.+?\.php)(/.*)$; if (!-f $document_root$fastcgi_script_name){return 404;} fastcgi_pass backend; #pass request to the upstream fastcgi_index index.php; include fastcgi_params; }
-5700384 0 If I have understood the question correctly I think you just need a CASE statement in the SELECT e.g.
CASE WHEN blackLIST = TRUE OR optout = TRUE THEN 1 ELSE 0 END
-34271936 0 FYI, I was able to customize the watch face, using the extension code you provided. No problem there.
If you notice the bundle id in the crash log error, the system is reporting a problem with the watchkit app (which contains the watchkit extension).
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Application is required. bundleID: ql.ManaEU.watchkitapp ...
You'll need to track down what's wrong with the watchkit bundle. The first place to start would be the Xcode watchkit app build target log. If there are no errors or warnings there, check the iPhone and Apple Watch console logs.
If that doesn't point you to the problem, check the Info.plist
to make sure those values are valid, and the required keys are present. Also check the watchkit app target build settings.
You should be able to use the Version Editor to compare the Xcode project against its initial commit, to see if something was inadvertently changed or deleted.
-4030295 0 Asp.net Request.Url.AbsoluteUri return IPI've got problem: When I use
Request.Url.AbsoluteUri
to detect page url at runtime, I always get url with IP, although my site is deployed at adress: http://site.domain.com. How can I get url with http://site.domain.com instead of server ip.
Thanks.
-12124990 0You can do it like this (the ASCII codes are in order with the alphabet):
function check_str_for_sequences($str, $min = 3) { $last_char_code = -1; $total_correct = 0; $str = strtolower($str); for($i = 0; $i < strlen($str); $i++) { //next letter in the alphabet from last char? if(ord($str[$i]) == ($last_char_code + 1)) { $total_correct++; //min sequence reached? if($total_correct >= ($min - 1)) { return TRUE; } } else { $total_correct = 0; } $last_char_code = ord($str[$i]); } return FALSE; }
Usage:
$test = 'Lorem ipsum dolor abcsit amet'; echo '----->' . check_str_for_alpha($test); // ----->1
-24579200 0 Apparently, folders named _pre_production
are not added to the APK
.
I cannot take credit for this. Here is where I found the answer:
Ignoring files from Android APK
I'm duplicating the answer here in case someone comes by.
-9210083 0Ti.require uses the CommonJS specification. Although files accessed via Ti.require have access to the Ti namespace, they do not have access to the Global namespace - any variables or functions you have declared in the main program. Ti.include files do have access to the global space and can modify or add to it. Ti.require is preferred, but not always practical. See https://wiki.appcelerator.org/display/guides/CommonJS+Modules+in+Titanium for information on the Ti.require function and https://wiki.appcelerator.org/display/guides/Mobile+Best+Practices for more best practices.
-32721816 0 Variable-Less String reverseIn a recent interview, I was asked a very simple question to reverse a string (not just print) without any extra variable and any in-built function. The closest I could think of is:
#include<stdio.h> #include<string.h> int main() { char ch[100]; scanf("%s",&ch); int i=0; while(i<strlen(ch)/2) { ch[i]=ch[strlen(ch)-1-i]+ch[i]; ch[strlen(ch)-1-i]=ch[i]-ch[strlen(ch)-1-i]; ch[i]=ch[i]-ch[strlen(ch)-1-i]; i++; } printf("%s",ch); return 0; }
My solution was rejected as I used variable i
. How this is even possible without using a counter variable? Is there any other method to solve this?
EDIT
These were the exact words of question(nothing more or less):
Reverse a string without using any variable or inbuilt functions in C.
-38256774 0 Is a default-generated constructor not required to construct all base classes?I've come across a case in which type-safe c++ produces non-matching ctor/dtors. The following code generates two constructors for A. The default constructor also constructs its base (B), but the default-generated copy/move ctor does not construct B. Later, it destroys B, so we get non-matching ctor/dtor.
I've tried this with gcc and clang and both fail. In the gcc bug report forum they suggested this isn't a gcc problem. I may be missing something, but isn't there something odd when type-safe code results in a dtor call for a class that hasn't been constructed?
B() -> INSERT: 0x7fff55398b2f ~B() -> ERASE: 0x7fff55398b2f ~B() -> ERASE: 0x7fff55398b40 // <- unmatched dtor call Assertion failed: (!all.empty()), function ~B, file gcc_bug.c, line 20.
Code follows:
#include <set> #include <iostream> #include <cstdint> #include <cassert> #include <experimental/optional> std::set<std::uintptr_t> all; struct B { B() { std::cerr << "B() -> INSERT: " << this << "\n"; all.insert((std::uintptr_t)this); } ~B() { std::cerr << "~B() -> ERASE: " << this << "\n"; assert(!all.empty()); // FAILS assert(all.find((std::uintptr_t)this) != all.end()); // FAILS all.erase((std::uintptr_t)this); } }; struct A : B {}; static std::experimental::optional<A> f() { A a; return a; } int main() { auto a = f(); return 0; }
-24649853 0 The issue is You are Reading from Clients Input and Writing to Clients Output. Basically you are sending whatever client sends back just a Ping Server.
ServerHandler.java
while((msg = reader.readLine()) != null) { write.write(msg); }
This combined with you initializing the Socket at the Client constructor causes your UI to freeze.
Client.java
s = new Socket("localhost", 6633); reader = new BufferedReader(new InputStreamReader(s.getInputStream())); write = new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
And right below,
while ((msg = reader.readLine()) != null) { display(msg); }
Your design is wrong for a Connection Oriented (TCP), Multi Client Chat Server. You need to sit down and draw a diagram on how to write from the beginning.
-6402625 0 Failed to generate a user instance of SQL Server due to failure in retrieving the user's local application data path. The connection will be closedI am designing asp.net mvc3 project. I have used database that designed in SQL Server, and I have added by ado.net connection. When I run this project then it works correctly, but when I publish this website using IIS manager then it gives following error in data access:
System.Data.SqlClient.SqlException: Failed to generate a user instance of SQL Server due to failure in retrieving the user's local application data path. Please make sure the user has a local user profile on the computer. The connection will be closed.
Please help me what should I do.?
Update: this is my connection string:-
(pasted and formatted from comments - Andrew)
connectionString="metadata=res://*/Models.TestModel.csdl| res://*/Models.TestModel.ssdl| res://*/Models.TestModel.msl; provider=System.Data.SqlClient;provider connection string="Data Source=.\SQLEXPRESS; AttachDbFilename=|DataDirectory|\moGileOrder.mdf; Integrated Security=True; User Instance=True; MultipleActiveResultSets=True"" providerName="System.Data.EntityClient"
-1739705 0 What's wrong with this lex file? I have a Makefile so that when I type make the following commands run:
yacc -d parser.y gcc -c y.tab.c flex calclexer.l gcc -c lex.yy.c
But then after this I get the following error messages:
calclexer.l:10: error: parse error before '[' token calclexer.l:10: error: stray '\' in program calclexer.l:15: error: stray '\' in program calclexer.l:24: error: stray '\' in program make: *** [lex.yy.o] Error 1
This is what is inside calclexer. How can it be fixed?
%{ #include "y.tab.h" #include "parser.h" #include <math.h> %} %% %% ([0-9]+|([0-9]*\.[0-9]+)([eE][-+]?[0-9]+)?) { yylval.dval = atof(yytext); return NUMBER; } [ \t] ; /* ignore white space */ [A-Za-z][A-Za-z0-9]* { /* return symbol pointer */ yylval.symp = symlook(yytext); return NAME; } "$" { return 0; /* end of input */ } \n |. return yytext[0]; %%
-31438319 0 C# IEnumerable neededFiles I have this code:
var neededFiles = new[]{ "file1.exe", "file2.exe", "file3.exe", "file4.exe" }; IEnumerable<string> notFound = neededFiles.Where(f => !File.Exists(f)); if (notFound.Any()) { MessageBox.Show(string.Format(notFound.Count() > 1 ? "App cannot find these files - {0}" : "App cannot find this file - {0}", String.Join(", ", neededFiles)), "Test", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; }
It work's OK, but If I have for example file1.exe, file2.exe, file3.exe files code anyway prints "App cannot find these files - file1.exe, file2.exe, file3.exe, file4.exe". How to make it print only needed file which not exists? Example: if exists file1.exe, file3.exe, it must print: App cannot find these files - file2.exe, file4.exe Thanks in advance
FIXED: The best overloaded method match for 'string.Join(string, string[])' has some invalid arguments This helped me.
-32715389 0Deque is ADT and it could be implemented by linked list or Arrays as data structures. Your answer depends upon the type of data structure being used to store elements.and also I would suggest you to implement a peek operation and it would give you a reference of an element for edit propose .peek operation could be used by other high-level operations like delete/contains etc.
-19944679 0You don't need to add 'return' into the onClick content,just use the checkHost('test').That is OK
PS:make sure you have loaded your custom function like checkHost()
-8396006 0 Thickbox not opening with anchor tags generated at runtimeI am having an issue opening a thick-box with anchor tags appended to a div at runtime.The anchor tag contains the thick-box css and the href,that is required to open up a thickbox.However,its not opening up the required page in a thickbox. All it does is,open up the page in a new page. However,when i crate a hard coded anchor with the required thickbox stuff,it opens up fine.The only issue is ,it doesn't do the same when it is generated at runtime .
I am using Jquery to append the anchor tags.
Doesn't Jquery understand anchor tags with thickbox property append at runtime ?
-30425581 1 Displaying levels of wav fileI want to read wav file and display levels of it. I know how to read frames, using wave module in python, but do not know what to deal with it. Any ideas will help. Thanks
import wave import struct import matplotlib.pyplot as plt wrd = wave.open("albatros.wav") display = [] display2=[] x = [] (nchannels, sampwidth, framerate, nframes, comptype, compname) = wrd.getparams() for i in range(0,int(nframes)): x.append(i) samplestring = wrd.readframes(1) display.append(struct.unpack('h',samplestring[:2])[0]); if(nchannels == 2): display2.append(struct.unpack('h',samplestring[2:4])[0]) plt.figure(1) plt.plot(x,display, 'k') if (nchannels == 2): plt.figure(2) plt.plot(x,display2, 'k') plt.show() print (len(display)) wrd.close()
-32624814 0 Should I switch my web site to ASP.NET MVC? I have an web site built in ASP.NET. It is a business website that works with a lot of data.
I had a lot of problems, especially of speed and effectiveness, so I did what I can with ajax, and speed greatly improved.
I wonder if I should switch the web site to ASP.NET MVC?
I don't know ASP.NET MVC very deeply, so I want to know if I should invest in it, the main question is: Is ASP.NET MVC faster and more effective than regular ASP.NET?
-8177807 0You can't send through the email submitted on the form, since you aren't authorized to use that email. You either have to use an email you control or the user's email by connecting to their Google account. http://code.google.com/appengine/docs/python/mail/sendingmail.html This page says which email you can use to send emails from, just scroll down right after the first code block.
-39107397 0I found a workaround for not being able to use the preset_size attribute in xml. I am doing it through code now -
profilePictureView.setPresetSize(ProfilePictureView.LARGE);
As for running the samples,
I downloaded the github repository facebook-sdk-master and then imported it into my project. Then I changed the application name of the samples and set their app_id to my app_id. Now I am able to run them.
-9575854 0 MySQL insert NULL value after getting value with $_REQUESTI have input fields, but if the users leave it blank, i want to insert a null value to my database.
I request values like this:
$val1 = htmlspecialchars($_REQUEST["val"], ENT_QUOTES);
And then insert them to the DB:
INSERT INTO `table` ( `val1` , `val2` , `val3`) VALUES ('$val1', '$val2', '$val3');
I have tried removing the ' around val1, val2, val3 - but then nothing gets inserted into the DB if there is no value. I have also tried something like this:
if (!empty($val1)) { $val1 = "'".$val1."'"; } else { $val1 = NULL;}
And then without the ' around the values - still no insert to the DB
-9193569 0 Formatting Date::Manip's Delta to daysI have this routine,
I want to save that delta to count the days between all to and from days in the from-to pairs I have in the 2 dimensional array, I just need the workdays.
Say for
$date_from = 2012-02-09; $date_to = 2012-02-13; $delta_string = 4 sub calc_usage { use Date::Manip::Date; my $date_from; my $date_to; my $delta; my $i; for $i (0 .. $#DATE_HOLDER) { $date_from = new Date::Manip::Date; $date_to = new Date::Manip::Date; $date_from->parse($DATE_HOLDER[$i][0]); $date_to->parse($DATE_HOLDER[$i][1]); $delta = $date_from->calc($date_to, "business"); } }
-14173730 0 I have experienced this error many times and the solution for me was to increase the apache binary (apache.exe or httpd.exe) stack size. You will need the Visual studio to do that, but you can use the trial version, as I did. You don't even need to turn it on. The command is:
C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\amd64>editbin /STACK:8000000 "c:\Program Files (x86)\WAMP\apache\bin\apache.exe"
Change the paths above according to your environment of course.
In the Visual studio directory VC/binary/ there are several utilities by the name editbin.exe. Use the one suitable for you platform or try them one by one, until it works (as I did).
-15193786 0No, you are misunderstanding how that method works. componentsSeparatedByString:
doesn't use the individual characters in the passed string, it uses the entire string. Your separator is the three-character sequence [,]
. A string like @"pecan[,]pie"
uses this separator, but @"1[0,5]"
does not. The similar method componentsSeparatedByCharactersInSet:
will do what you are expecting:
[string componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"[,]"]];
If you want to pull digits out of strings and get their numerical values, you may want to look at NSScanner
.
Concatenate them like this:
Response.Redirect("Default2.aspx?adi=" + adi + "&soyadi=" + soyadi);
When passing query string parameters, use the ?
symbol just after the name of the page and if you want to add more than one parameter, use the &
symbol to separate them
In the consuming page:
protected void Page_Load(object sender, EventArgs e) { var adi = this.Request.QueryString["adi"]; var soyadi = this.Request.QueryString["soyadi"]; }
-27545362 0 in ALL browsers, the browser will make padding and margin between all the things. to remove that and control the page yourself add this add the first line of your css:
* {margin:0 auto; padding:0}
auto
makes all the things (except text and images) at the center of your page.
and for your table if you want texts to be on top of your td, add this:
.tlt{vartical-align:top; text-align:left;}
Sounds like you're still using the distribution code signing identity.
Assuming you're using Xcode 4.2, you can refer to the bellow image for how to change this:
[edit: better image]
You also need to change your application identifier to match your code signing identity:
So, look at the string next to the selection you choose in the step 4 of the first screenshot (probably something in the format of com.yourcompany.appname) and make sure to use that same identifier in step 4 of the second screenshot.
-39845394 0This is no doubt a million dollar question, and I think the right solution depends always on the case.
Here goes my thoughts. Hope could help:
One simple trick (which, in fact, I read that it is surprisingly more efficient than joining strings with "+") is to use arrays of strings for each row and join them.
It continues being a mess but, at least for me, a bit clearer (specially when using, as I do, "\n" as separator instead of spaces, to make resulting strings more readable when printed out for debugging).
Example:
var sql = [ "select foo.bar", "from baz", "join foo on (", " foo.bazId = baz.id", ")", // I always leave the last comma to avoid errors on possible query grow. ].join("\n"); // or .join(" ") if you prefer.
As a hint, I use that syntax in my own SQL "building" library. It may not work in too complex queries but, if you have cases in which provided parameters could vary, it is very helpful to avoid (also subotptimal) "coalesce" messes by fully removing unneeded query parts. It is also on GitHub, (and it isn't too complex code), so you can extend it if you feel it useful.
If you prefer separate files:
About having single or multiple files, having multiple files is less efficient from the point of view of reading efficiency (more file open/close overhead and harder OS level caching). But, if you load all of them single time at startup, it is not in fact a hardly noticeable difference.
So, the only drawback (for me) is that it is too hard to have a "global glance" of your query collection. Even, if you have very huge amount of queries, I think it is better to mix both approaches. That is: group related queries in the same file so you have single file per each module, submodel or whatever criteria you chosen.
Of course: Single file would result in relatively "huge" file, also difficult to handle "at first". But I (hardly) use vim's marker based folding (foldmethod=marker) which is very helpfull to handle that files.
Of course: if you don't (yet) use vim (truly??), you wouldn't have that option, but sure there is another alternative in your editor. If not, you always can use syntax folding and something like "function (my_tag) {" as markers.
For example:
---(Query 1)---------------------/*{{{*/ select foo from bar; ---------------------------------/*}}}*/ ---(Query 2)---------------------/*{{{*/ select foo.baz from foo join bar using (foobar) ---------------------------------/*}}}*/
...when folded, I see it as:
+-- 3 línies: ---(Query 1)------------------------------------------------ +-- 5 línies: ---(Query 2)------------------------------------------------
Which, using properly selected labels, is much more handy to manage and, from the parsing point of view, is not difficult to parse the whole file splitting queries by that separation rows and using labels as keys to index the queries.
Dirty example:
#!/usr/bin/env node "use strict"; var Fs = require("fs"); var src = Fs.readFileSync("./test.sql"); var queries = {}; var label = false; String(src).split("\n").map(function(row){ var m = row.match(/^-+\((.*?)\)-+[/*{]*$/); if (m) return queries[label = m[1].replace(" ", "_").toLowerCase()] = ""; if(row.match(/^-+[/*}]*$/)) return label = false; if (label) queries[label] += row+"\n"; }); console.log(queries); // { query_1: 'select foo from bar;\n', // query_2: 'select foo.baz \nfrom foo\njoin bar using (foobar)\n' } console.log(queries["query_1"]); // select foo from bar; console.log(queries["query_2"]); // select foo.baz // from foo // join bar using (foobar)
-24006346 0 Scheduling Oracle sql files using Unix based SAS enviornmentFinally (idea), if you do as much effort, wouldn't be a bad idea to add some boolean mark together with each query label telling if that query is intended to be used frequently or only occasionally. Then you can use that information to prepare those statements at application startup or only when they are going to be used more than single time.
I have bunch of SQL queries that run against an Oracle database. Is there a way to schedule these .sql
files using UNIX Based SAS, so they can execute one after another at certain time of day?
Try this :
mklink /D .\ venv\lib\python2.7\site-packages\httplib2
Note : mklink [OPTION] LINK TARGET (link and target are flipped compared to linux's ln -s
)
Mklink Command Syntax :
MKLINK has 3 options /D, /H and /J. You also need to specify the path to the new symbolic link and the path to the original file or directory.
/D – used to create symbolic links for directories (d for directory)
/H – used to create hard links (h for hard link)
/J – used to create directory junction (j for junction)
By the way, always prefer mklink /D over mklink /J. Windows explorer will delete the entire contents of a junction (the latter) whereas when deleting a directory link (the former) it will just remove the link.
The dot .
is the current directory (from where you are running the command). In the example above, I changed it to .\
to make it explicit.
For files : Helpful link.
If you can't get privilege with /D
, use a hard link (option /H
) :
mklink /H .\six.py venv\lib\python2.7\site-packages\six.py
-26355457 0 Not a complete answer but I guess I am pointing in the right direction. You can get all the information about the user's browser and platform in javascript using the code below
alert(navigator.userAgent);
You will have to create a list of known browsers and platforms, and you will have to compare the userAgent string with them to identify the respective browser/platform.
-40669321 0map[i][j]
needs to be set to a new object, like map[i][j] = new Node('a')
(well, if you had a constructor in Node
which worked like that: it would be written Node(char a) { this.content = a; }
).
You cannot do map[i][j].setContent('a')
because it is not a preexisting Node
object.
If speaking about x86 architecture when an operating system has nothing to do it can use HLT instruction. HLT instruction stops the CPU till next interrupt. See http://en.m.wikipedia.org/wiki/HLT for details.
Other architectures have similar instruction to give CPU a rest.
-31208970 0I believe typically that means that the character is not recognized by the font.
-30910666 0 How can I querying a key value without retriving all data in Firebase?I'm learning angularjs, firebase, angularfire by building a sample app. It's a dictionary app that any one can add a word, add several explanation to the word, add several common usage to the word, add example centences to the word. People can freely add new word via this web app. OR people can freely realtime search a word and display the content of that word. When I build the app.
I found everytime when I search a word, I have to load all the data and then check if the query string exist in the data and then display the content if exist. So, it's quite heavy if the library become very big.
How can I query a string if it exist from the server side and if exist, just download that piece of data?
-17610531 0Assuming you created this form with Webform...
If you just want to display the form at the end of the page, go to the form advance settings and click on "available as block"
Then on the block sections, add it to the "main content section" and configute the block.
Under Show block on specific pages, write the pages you want it to appear.
To print a block programatically
$block = module_invoke('webform', 'block_view', 'client-block-1'); //add your block id print render($block['content']);
-39775880 0 I'm running into the same issue on Xamarin.android. Here's what the documentation says.
-8232448 0 Glassfish/Hibernate save without calling save explicitelyThis can only be called before the fragment has been attached to its activity
I am using Glassfish 2 and container managed persistence with Hibernate 3.2 as persistence provider. I have some finder method in my business logic, which manipulates some persistent entities, which have been fetched via the EntityManager
. The manipulation is just changing a String
property (deleting an element from a collection leads to the same effect).
I do not call anything like save or persist on my EntityManager
. I just want to return some changed entities to my client.
It seems when the container commits the transaction the changes to my entity are saved automatically. Is there some magic Hibernate or Glassfish behaviour I missed completely so far?
-39275562 0Julia has its own interface to matplotlib called PyPlot
. (you didn't really expect you'd simply type @pyimport
and then just write python code into julia and magically have it all work, did you? :D )
See here for examples on how to use PyPlot
; The hist
plot in particular needs some special syntax to differentiate it from the julia native hist
function (check the code for its example).
Here is your code translated to PyPlot to the best of my ability (works in Julia v0.6.0)
import PyPlot a = vec( rand( 1:1000, 400, 300 )) b = vec( rand( 200:700, 400, 300 )) c = vec( rand( 300:1200, 400, 300 )) common_params = Dict( :bins => 20, :range => (-100, 1300), :normed => true ) PyPlot.subplots_adjust( hspace=.4 ) PyPlot.subplot( 311 ) PyPlot.title( "Default" ) PyPlot.plt[:hist]( a; common_params... ) PyPlot.plt[:hist]( b; common_params... ) PyPlot.plt[:hist]( c; common_params... ) PyPlot.subplot( 312 ) PyPlot.title( "Skinny shift - 3 at a time" ) PyPlot.plt[:hist]( (a, b, c); common_params... ) PyPlot.subplot( 313 ) common_params[:histtype] = "step" PyPlot.title( "With steps" ) PyPlot.plt[:hist]( a; common_params... ) PyPlot.plt[:hist]( b; common_params... ) PyPlot.plt[:hist]( c; common_params... ) PyPlot.savefig( "3hist.png" ) PyPlot.show() # PS, this is unnecessary in PyPlot. All commands show instantly
I'm not sure why you chose a range of (-5,5); this was causing a problem on the third subplot. I've changed it to something more reasonable here just to show you this works.
Here's the result below:
-26715764 0You can do the following:
library(dplyr) library(stringr) library(lazyeval) df %>% mutate(new = str_sub(V1, V2, V3)) # V1 V2 V3 new #1 ABBEDHH 4 5 ED #2 DEFGH 2 2 E #3 EFGF 1 2 EF #4 EEFD 1 1 E
Note that dplyr
is made for working with data.frame
s, so input and output should be data.frames, not atomic vectors.
You have to write your dates in YYYYmmdd
format so that alphabetical order matches chronological order.
But you want your dates to be displayed in a better-looking format (legit).
The solution is to have 2 columns: one with the good-looking date, one with the YYYYmmdd
date. This one will be hidden, but will be used by dataTable
sorting function.
<table id="sorting"> <thead> <tr> <th>CPA</th> <th>Shipping</th> <th>Shipping (sorting format)</th> </tr> </thead> <tbody> <tr> <td>123</td> <td>Aug 28</td> <td>20150828</td> </tr> <tr> <td>327</td> <td>July 30</td> <td>20150730</td> </tr> <tr> <td>789</td> <td>Process</td> <td>0</td> </tr> </tbody> </table>
Then, the Javascript :
$('#sorting').dataTable( { "aoColumns": [ {"bSortable": true}, // First column: normal {"iDataSort": 2}, // Second column's sorting depends on third column (dataTable starts counting from 0, that's why third column is number 2) {"bVisible": false}, // Third column: hide it ] });
You'll find more tips and examples in DataTables' documentation.
-13980410 0I'm no perl wizard, but the following seems to work:
p4 changelists -m 1 -t //depot/...| perl -p -e "s/^/\042/;s/$/\042/"
Check out Strawberry Perl, which provides a Windows version of Perl.
I'm always looking at my Unix tools when solving problems like this, even under Windows. sed and gawk will also get you there, check out msysgit for a nice bundle of Unix tools that will run on Windows.
-36790317 0 How to run tomcat before starting testafter two days of search, I still cannot run tomcat before test, can anyone tell what i am not doing right ? here is my pom
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-failsafe-plugin</artifactId> <version>2.16</version> <executions> <execution> <id>integration-test</id> <goals> <goal>integration-test</goal> </goals> </execution> <execution> <id>verify</id> <goals> <goal>verify</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <server>tomcat-development-server</server> <port>8081</port> <path>/test</path> </configuration> <executions> <execution> <id>start-tomcat</id> <phase>pre-integration-test</phase> <goals> <goal>run</goal> </goals> </execution> <execution> <id>stop-tomcat</id> <phase>post-integration-test</phase> <goals> <goal>shutdown</goal> </goals> </execution> </executions>
when I use mvn verify my tests start, but the server not, I don't know what i'm missing !
-34272479 0 Android EditTextPreference show value in summaryI would like to show the preference value in the summary field. This accepted answer shows how to do it for a ListPreference
.
Is there a similar way to do it for an EditTextPrefernce
in the layout instead of extending the class?
i have a problem. I have made a PHP proxy to get json data from an external server using this code :
<?php $url = $_GET['url']; $ch = curl_init(); curl_setopt($ch,CURLOPT_URL,$url); $data = curl_exec($ch); curl_close($ch); echo("<h1>".$url."</h1>"); echo (substr($data,0,-1)); ?>
But i have to pass this link "http://isohunt.com/js/json.php?ihq=ubuntu&sort=age" and since i have an & in there my php script can't properly evaluate the link. How i solve the issue?
-36475742 0To consider page 1 only…
var main = function(){ var doc = app.properties.activeDocument, finds,n; app.findTextPreferences = app.changeTextPreferences = null; app.findTextPreferences.findWhat = "#"; if ( !doc ) return; finds = doc.findText(); n = finds.length; while (n-- ) { finds[n].parentTextFrames.length && finds[n].parentTextFrames[0].isValid && finds[n].parentTextFrames[0].parentPage.id==doc.pages[0].id && finds[n].contents = "no: " + String(n+1); } }; main();
-36173916 0 htaccess redirecting one url to load from another I am trying to redirect one of my URLs in my website, but I get error 404 not found I am trying to redirect this url: http://www.stoikovstroi.com/bg/противопожарни-врати
to be loaded from this one: http://www.stoikovstroi.com/vina/index.php/protivpojarni-vrati
RewriteEngine On RewriteCond %{HTTP_HOST} ^stoikovstroi\.com\bg\противопожарни-врати$ [OR] RewriteCond %{HTTP_HOST} ^www\.stoikovstroi\.com\bg\противопожарни-врати$ RewriteCond %{REQUEST_URI} !^/vina/index.php/protivpojarni-vrati RewriteRule (.*) /vina/$1/index.php/protivpojarni-vrati
-6999553 0 Try removing the Data Source and Initial Catalog, and replace them with something like this:
Server=.\SQLEXPRESS;Database=BlueLadder;
I don't know if you're using SQLEXPRESS, so just modify accordingly if you're not.
-14091715 0I'm using InAppSettingsKit with localized text with no problems. Two things I can think of that you could check: are your Root.strings files located in the correct subdirectories of Settings.bundle (en.lproj and fr.lproj for English and French?
Is there a "Strings Filename" entry in your Root.plist? It should simply contain a string with value "Root"
-8869320 0If you don't use any transaction annotations the default will be transactions being required. Thus your DAO will run in a transaction and the persistence context will no later be flushed than when the transaction is committed.
From the JavaDoc on TransactionAttribute
:
If the TransactionAttribute annotation is not specified, and the bean uses container managed transaction demarcation, the semantics of the REQUIRED transaction attribute are assumed.
From the JavaDoc on FlushModeType
:
When queries are executed within a transaction, if FlushModeType.AUTO is set on the Query or TypedQuery object, or if the flush mode setting for the persistence context is AUTO (the default) and a flush mode setting has not been specified for the Query or TypedQuery object, the persistence provider is responsible for ensuring that all updates to the state of all entities in the persistence context which could potentially affect the result of the query are visible to the processing of the query.
This means that the persistence context might be flushed earlier, if you use a query whose result might be influenced by that flush.
-35197802 0A bit more late, but I've found another option using ngnix as a proxy:
This guide has been finished by following partially this guideline: https://support.rstudio.com/hc/en-us/articles/213733868-Running-Shiny-Server-with-a-Proxy
On an Ubuntu 14.04:
This:
events { worker_connections 768; multi_accept on; } http { map $http_upgrade $connection_upgrade { default upgrade; '' close; } server { listen XX; location / { proxy_pass http://localhost:YY; proxy_redirect http://localhost:YY/ $scheme://$host/; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; proxy_read_timeout 20d; auth_basic "Restricted Content"; auth_basic_user_file /etc/nginx/.htpasswd; } } }
XX: Port that the nginx will listen to
YY: Port that the shiny server uses
Using this tutorial, I added password authentication to the nginx server: https://www.digitalocean.com/community/tutorials/how-to-set-up-password-authentication-with-nginx-on-ubuntu-14-04
Set up the shiny process or the shiny server to only listen to localhost (127.0.0.1)
I have a problem every time I try to simulate in PSpice. When I click Run it appears the following window:
ERROR(15053):Unable to initialize PSpice UI
Can someone please help me with this? I need to use PSpice for a subject in my university. I would really appreciate any information that anyone could give me.
Thank you very much!
-10360987 0Do not Use InnerHtml. Its Wrong. Use Inbuild HtmlPage
Class
Use Like this for Example
Page.Controls.Add( new LiteralControl(@"<html>\r\n<body>\r\n <h1>Welcome to my Homepage!</h1>\r\n")); HtmlForm Form1 = new HtmlForm(); Form1.ID = "Form1"; Form1.Method = "post"; Form1.Controls.Add( new LiteralControl("\r\nWhat is your name?\r\n")); TextBox TextBox1 = new TextBox(); TextBox1.ID = "txtName"; Form1.Controls.Add(TextBox1); Form1.Controls.Add( new LiteralControl("\r\n<br />What is your gender?\r\n")); DropDownList DropDownList1 = new DropDownList(); DropDownList1.ID = "ddlGender"; ListItem ListItem1 = new ListItem(); ListItem1.Selected = true; ListItem1.Value = "M"; ListItem1.Text = "Male"; DropDownList1.Items.Add(ListItem1); ListItem ListItem2 = new ListItem(); ListItem2.Value = "F"; ListItem2.Text = "Female"; DropDownList1.Items.Add(ListItem2); ListItem ListItem3 = new ListItem(); ListItem3.Value = "U"; ListItem3.Text = "Undecided"; DropDownList1.Items.Add(ListItem3); Form1.Controls.Add( new LiteralControl("\r\n<br /> \r\n")); Button Button1 = new Button(); Button1.Text = "Submit!"; Form1.Controls.Add(Button1); Form1.Controls.Add( new LiteralControl("\r\n</body>\r\n</html>")); Controls.Add(Form1);
-7612396 0 Reverse String in Java without using any Temporary String,Char or String Builder Is it possible to reverse String
in Java without using any of the temporary variables like String
, Char[]
or StringBuilder
?
Only can use int
, or int[]
.
Your problem is that your data context is different when you are within the #each
block. Within #each
, your context is the current element in the iteration, { a: "A" }
, { b: "B" }
, etc. To access an object of the parent context you use Handlebars Paths:
{{#each a}} {{this.a}} {{#each ../b}} {{this.b}} {{/each}} {{/each}}
-9434178 0 This is a bit hardcoded and pcalcao's answer is probably more flexible:
private static boolean isLessThan8HoursFrom2AM(DateTime date) { return (date.getHourOfDay() >= 18 || date.getHourOfDay() < 10); }
-24138600 0 Checking if enter key pressed in the text box I am using following code to check if enter key was pressed in textbox but I am getting type error TypeError: e is undefined
<html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>demo</title> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script> function memSort(e){ if(e.keyCode === 13){ alert("Enter was pressed "); } } </script> </head> <body> <div class="searchBox"> <div class="keyname">Keyword : </div> <input name="usersearch" id="usersearch" type="text" value="" onKeydown="memSort();"/> <div id="listOrders"></div> </div> </body> </html>
-30322329 0 mobile vs dektop authentication with client certificate HTTPS Is there a different between mobile-authentication and desktop-authentication via certificate and https? And when, how to solve mobile authentiction with certificate?
We try to accomplish a connection to a site eg. https: example.com and authenticate the user via certificate. Before setup a CA and generate necessary certificates.
C# code from login site:
var x509 = new X509Certificate2(this.Request.ClientCertificate.Certificate); var chain = new X509Chain(true); chain.ChainPolicy.RevocationMode = X509RevocationMode.Offline; chain.Build(x509);
that works great with IE desktop browser, and we can log every certificate information.
edit: It´s not working with firefox and there is no question about to choose a local certificate - same behavior as mobile.
Try the same url via mobile eg: iPhone or Windowsphone - nothing can read from the certificate.
Solution: as @Sean Baker said, install your CA cert as well on mobile. Thats the reason for me to upvote his answer as the right answer for this question.
Have a look at the webservers certificate. in my case, i have created the certificates on microsoft server and used a copy from "webserver" template, so that it was possible for me to export the certificate with a private key, cause that made it easier to deploy.
here is a url that point me in the right direction: https://support.microsoft.com/en-us/kb/931351
The login with firefox is working as well - you have to install your personal certificate within the fF administration. After that, you will be prompted to choose that certificate when opening the url via https.
-12275856 0 Blackberry-not getting soap response xmlI am trying to consume SOAP response xml by passing request xml in a string, using BlackBerry Java plugin for Eclipse. I have been struck on this for the past two days looking for a way to solve it.
I have attached the sample code below.
public String CheckXml() { final String requestXml="<SOAP:Envelope xmlns:SOAP=\"http://schemas.xmlsoap.org/soap/envelope/\"><header xmlns=\"http://schemas.cordys.com/General/1.0/\"></header><SOAP:Body><authenticateAgainstOID xmlns=\"http://schemas.cordys.com/OIDAuthentication\"><stringParam>HEMANTS_MUM013</stringParam><stringParam1>TATA2012</stringParam1></authenticateAgainstOID></SOAP:Body></SOAP:Envelope>"; final String HOST_ADDRESS = "http://xyz.com/cordys/com.eibus.web.soap.Gateway.wcp?organization=o=B2C,cn=cordys,cn=cbop,o=tatamotors.com&SAMLart=MDFn+8e5dRDaRMRIwMY7nI84eEccbx+lIiV0VhsOQ7u+SKG6n5+WNB58"; String result=""; try { HttpConnection url=(HttpConnection)Connector.open(HOST_ADDRESS); url.setRequestProperty("Content-Type", "text/xml"); url.setRequestMethod(HttpConnection.GET); OutputStreamWriter writer=new OutputStreamWriter(url.openOutputStream()); writer.write(requestXml); writer.flush(); writer.close(); StringBuffer buffer1=new StringBuffer(); InputStreamReader reader=new InputStreamReader(url.openInputStream()); StringBuffer buffer=new StringBuffer(); char[] cbuf=new char[2048]; int num; while (-1 != (num = reader.read(cbuf))) { buffer.append(cbuf, 0, num); } String result1 = buffer.toString(); } catch (Exception e) { System.out.println(e); } return result; }
-38539066 0 Simply because b variable is initialized inside the function print.. and c variable is initialised on the global scope. so at this line:
document.write("b is : " + b + "<br />");
you trying to get the value of b variable but ur not calling the function print..
look at this :
var a = 45; var b; var c; function print(){ b = 10; document.write(a); } if(a == 45) { var c = 10; } document.write("a is : " + a + "<br />"); document.write("b is : " + b + "<br />"); document.write("c is : " + c + "<br />"); //-->
it will print the following:
a is : 45 b is : undefined c is : 10
because b didn`t change as the function has not yet been called .. but c has changed by the if statement which lies on the global scope.
var a = 45; var c; function print() { b = 10; document.write(a); } print() if (a == 45) { var c = 10; } document.write("a is : " + a + "<br />"); document.write("b is : " + b + "<br />"); document.write("c is : " + c + "<br />"); //-->
-1615832 0 That would only work if operator||(string,string)
returned.. a sort of collection of strings and you had an Equals
overload that took a string and that collection of strings and verified that the string is in the collection. Seems like a lot of work done behind the scenes for a very rarely used construct.
Especially since you already can do something like:
if(new string[]{"firstName","lastName"}.Contains(stringName)) // code
-7544486 0 I solved it! This is the query:
select case when (select min(time(myColumn)) from myTable where time(current_timestamp, 'localtime') < time(myColumn)) is null then (select min(time(myColumn)) from myTable where time(current_timestamp, 'localtime') > time(myColumn)) else (select min(time(myColumn)) from myTable where time(current_timestamp, 'localtime') < time(myColumn)) end
Thx Tim & Dave who showed me the way.
-4737686 0 How to generate SQL CLR stored procedure installation script w/o Visual StudioI am working on CLR stored procedure using VS2010. I need to generate standalone deployment script to install this procedure at customer servers. Now I am using Visual Studio which generate such script when I press F5 and try to debug SP on DB server. This script is placed at bin\Debug\MyStoredProcedure.sql
file. It looks like this:
USE [$(DatabaseName)] GO IF EXISTS (SELECT * FROM tempdb..sysobjects WHERE id=OBJECT_ID('tempdb..#tmpErrors')) DROP TABLE #tmpErrors GO CREATE TABLE #tmpErrors (Error int) GO SET XACT_ABORT ON GO SET TRANSACTION ISOLATION LEVEL READ COMMITTED GO BEGIN TRANSACTION GO PRINT N'Dropping [dbo].[spMyStoredProcedure]...'; GO DROP PROCEDURE [dbo].[spMyStoredProcedure]; GO IF @@ERROR <> 0 AND @@TRANCOUNT > 0 BEGIN ROLLBACK; END IF @@TRANCOUNT = 0 BEGIN INSERT INTO #tmpErrors (Error) VALUES (1); BEGIN TRANSACTION; END GO PRINT N'Dropping [MyStoredProcedure]...'; GO DROP ASSEMBLY [MyStoredProcedure]; GO IF @@ERROR <> 0 AND @@TRANCOUNT > 0 BEGIN ROLLBACK; END IF @@TRANCOUNT = 0 BEGIN INSERT INTO #tmpErrors (Error) VALUES (1); BEGIN TRANSACTION; END GO PRINT N'Creating [MyStoredProcedure]...'; GO CREATE ASSEMBLY [MyStoredProcedure] AUTHORIZATION [dbo] -- here should be long hex string with assembly binary FROM 0x4D5A90000300000004000000FFFCD21546869732070726F6772616D...000000000000000000 WITH PERMISSION_SET = SAFE; GO IF @@ERROR <> 0 AND @@TRANCOUNT > 0 BEGIN ROLLBACK; END IF @@TRANCOUNT = 0 BEGIN INSERT INTO #tmpErrors (Error) VALUES (1); BEGIN TRANSACTION; END GO PRINT N'Creating [dbo].[spMyStoredProcedure]...'; GO CREATE PROCEDURE [dbo].[spMyStoredProcedure] @reference UNIQUEIDENTIFIER, @results INT OUTPUT, @errormessage NVARCHAR (4000) OUTPUT AS EXTERNAL NAME [MyStoredProcedure].[MyCompany.MyProduct.MyStoredProcedureClass].[MyStoredProcedureMethod] GO IF @@ERROR <> 0 AND @@TRANCOUNT > 0 BEGIN ROLLBACK; END IF @@TRANCOUNT = 0 BEGIN INSERT INTO #tmpErrors (Error) VALUES (1); BEGIN TRANSACTION; END GO IF EXISTS (SELECT * FROM #tmpErrors) ROLLBACK TRANSACTION GO IF @@TRANCOUNT>0 BEGIN PRINT N'The transacted portion of the database update succeeded.' COMMIT TRANSACTION END ELSE PRINT N'The transacted portion of the database update failed.' GO DROP TABLE #tmpErrors GO
I am wondering, is it possible to generate such script without Visual Studio? For example, what if I build solution with MSBuild and then generate this script with some tool? I believe, that if I read assembly as byte array and then serialize it to hex string and insert into script template - it could work, but maybe there is some easier standard solution?
Thanks.
-35815395 0 Child category is set current-cat on parent pageI have parent categories which have childs. I'm listing child categories on parent category page.
I'm using archive.php template.
Now I'm facing issue with current-cat
class on parent category page. Seems that my first child category is getting current-cat
class when on parent category page. This current-cat
class should be on only when on current category page.
For example my parent category is Fruits. And when I'm on Fruits (category/fruits) page I can see child categories Apple, Orange, Banana. Problem is that Apple is getting current-cat
class on Fruits page.
It should get that class only when on Apple page (category/fruits/apple).
Here is my current code:
global $wp_query; $ID = $wp_query->posts[0]->ID; $postcat = get_the_category($ID); $cat = $postcat[0]->cat_ID; $thiscat = get_category ($cat); $parent = $thiscat->category_parent; if ($parent == 0) { } else { $subcategories = get_categories('child_of='.$parent); $items=''; foreach($subcategories as $subcat) { if($thiscat->term_id == $subcat->term_id) $current = ' current-cat'; else $current = ''; $items .= ' <li class="cat-item cat-item-'.$subcat->term_id.$current.'"> <a href="'.get_category_link( $subcat->term_id ).'" title="'.$subcat->description.'">'.$subcat->name.' </a> </li>'; } echo "<ul>$items</ul>"; } ?>
How to fix my code?
-19982100 0As you are plotting points and their aesthetics is color and accordingly you should use color=
instead of fill=
p+guides(color=guide_legend("Legend title"))
or
p + labs(color="Legend title")
-10803845 0 Try:
if ((string) $xml->action === 'register') { // code }
And you don't need the </xml>
in your xml file.
Problem temporarily solved by commenting a check in atlcore.h :
//#error This file requires _WIN32_WINNT to be #defined at least to 0x0403. Value 0x0501 or higher is recommended.
I know it isnt the right way to do [ editing a file shipped by the IDE ] but did since it may be due to Improper installation.
If anyone come across a permanent fix let me know .
-30868377 0Have you looked at the :not
selector?
You can try something like this:
.tab:not(.tab2):hover { background-color: #A9E59E; }
-19302837 0 I like to reference controls with the dot notation instead of the bang notation. Does it help to change it to the example below?
[Forms]![form1].[foo]
or if there are no spaces in the name of the form or the control.
Forms!form1.foo
-21092538 0 set TEXT_T="myfile.txt" set /a c=1 FOR /F "tokens=1 usebackq" %%i in (%TEXT_T%) do ( set /a c+=1 set OUTPUT_FILE_NAME=output_%c%.txt echo Output file is %OUTPUT_FILE_NAME% echo %%i, %c% )
-1762431 0 dynamic_cast is known to break across module boundaries with many compilers (including MSVC and gcc). I don't know exactly why that is, but googling for it yields many hits. I'd recommend trying to get rid of the dynamic_cast in the first place instead of trying to find out why it returns null in your second scenario.
-10675121 0I'm not sure to what limitations the author of the python tutorial was referring, but I would guess it has in part to do with the way that method / attribute lookup is implemented in python (the "method resolution order" or MRO). Python uses the C3 superclass linearization mechanism; this is to deal with what is termed to be "The Diamond Problem".
Once you've introduced multiple inheritance into your class hierarchy, any given class doesn't have a single potential class that it inherits from, it only has "the next class in the MRO", even for classes that expect that they inherit from some class in particular.
For example, if class A(object)
, class B(A)
, class C(A)
, and class D(B, C)
, then the MRO for class D
is D->B->C->A
. Class B might have been written, probably was, thinking that it descends from A, and when it calls super()
on itself, it will get a method on A. But this is no longer true; when B calls super()
, it will get a method on C instead, if it exists.
If you change method signatures in overridden methods this can be a problem. Class B, expecting the signature of a method from class A when it calls super, instead gets a method from C, which might not have that signature (and might or might not not implement the desired behavior, from class B's point of view).
class A(object): def __init__(self, foo): print "A!" class B(A): def __init__(self, foo, bar): print "B!" super(B, self).__init__(foo) class C(A): def __init__(self, foo, baaz): print "C!" super(C, self).__init__(foo) class D(B, C): def __init__(self, foo, bar): print "D!" super(D, self).__init__(foo, bar) print D.mro() D("foo", "bar")
In this code sample, classes B and C have reasonably extended A, and changed their __init__
signatures, but call their expected superclass signature correctly. But when you make D like that, the effective "superclass" of B becomes C instead of A. When it calls super, things blow up:
[<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <type 'object'>] D! B! Traceback (most recent call last): File "/tmp/multi_inherit.py", line 22, in <module> D("foo", "bar") File "/tmp/multi_inherit.py", line 19, in __init__ super(D, self).__init__(foo, bar) File "/tmp/multi_inherit.py", line 9, in __init__ super(B, self).__init__(foo) TypeError: __init__() takes exactly 3 arguments (2 given)
This same sort of thing could happen for other methods as well (if they call super()
), and the "diamond" doesn't have to only appear at the root of the class hierarchy.
The >
means that the option:selected
must be a child, or direct descendant of #OrganiastionSettingsAll
. The example without the >
means that option:selected
can be a descendant at any level of #OrganiastionSettingsAll
.
The child combinator (E > F) can be thought of as a more specific form of the descendant combinator (E F) in that it selects only first-level descendants.
Ref: http://api.jquery.com/child-selector/
-20791187 0 http file validation for html5What methods are used by the browser to ensure that all parts on a web page have been downloaded to the client successfully. This includes all html, css and javascript.
I have seen the etag in the http headers.
Does the browser have the ability to re-download content if a connection fails?
-128968 0I'm not quite sure I understand the question, but I think you're asking how to restrict sudo to the one specific command and not have to grant unlimited capacity for mischief to all of your Ruby developers.
/etc/sudoers can be set up to restrict the commands which users are allowed to invoke as root. It is commonly set to ALL, but you can provide just a list of the allowed commands.
-15330187 0have you tried like this ... it just a suggestion ....
$('input[type=password]').live('keyup',function() { $('#pswd_info').show("blind", { direction: "vertical" }, 1000); }).blur(function() { $('#pswd_info').hide("blind", { direction: "vertical" }, 1000); });
-5073898 0 Why is my program skipping a prompt in a loop? My code is supposed to continuously loop until "stop" is entered as employee name. A problem I am having is that once it does the calculation for the first employee's hours and rate, it will skip over the prompt for employee name again. Why? (The code is in 2 separate classes, btw) Please help. Here is my code:
package payroll_program_3; import java.util.Scanner; public class payroll_program_3 { public static void main(String[] args) { Scanner input = new Scanner( System.in ); employee_info theEmployee = new employee_info(); String eName = ""; double Hours = 0.0; double Rate = 0.0; while(true) { System.out.print("\nEnter Employee's Name: "); eName = input.nextLine(); theEmployee.setName(eName); if (eName.equalsIgnoreCase("stop")) { return; } System.out.print("\nEnter Employee's Hours Worked: "); Hours = input.nextDouble(); theEmployee.setHours(Hours); while (Hours <0) //By using this statement, the program will not { //allow negative numbers. System.out.printf("Hours cannot be negative\n"); System.out.printf("Please enter hours worked\n"); Hours = input.nextDouble(); theEmployee.setHours(Hours); } System.out.print("\nEnter Employee's Rate of Pay: "); Rate = input.nextDouble(); theEmployee.setRate(Rate); while (Rate <0) //By using this statement, the program will not { //allow negative numbers. System.out.printf("Pay rate cannot be negative\n"); System.out.printf("Please enter hourly rate\n"); Rate = input.nextDouble(); theEmployee.setRate(Rate); } System.out.print("\n Employee Name: " + theEmployee.getName()); System.out.print("\n Employee Hours Worked: " + theEmployee.getHours()); System.out.print("\n Employee Rate of Pay: " + theEmployee.getRate() + "\n\n"); System.out.printf("\n %s's Gross Pay: $%.2f\n\n\n", theEmployee.getName(), theEmployee.calculatePay()); } } }
AND
package payroll_program_3; public class employee_info { String employeeName; double employeeRate; double employeeHours; public employee_info() { employeeName = ""; employeeRate = 0; employeeHours = 0; } public void setName(String name) { employeeName = name; } public void setRate(double rate) { employeeRate = rate; } public void setHours(double hours) { employeeHours = hours; } public String getName() { return employeeName; } public double getRate() { return employeeRate; } public double getHours() { return employeeHours; } public double calculatePay() { return (employeeRate * employeeHours); } }
-2718574 0 I have a .NET Application that runs on a server with 16 COM ports, about 11 of which are currently connected to various devices, some RS485, many RS-232. (Diagram here: http://blog.abodit.com/2010/03/home-automation-block-diagram/). Most of these devices are running just 9600 baud, and most don't have very tight timing requirements. I have a thread per device handling receiving and while it runs at normal thread priority, all other non-communication threads run at a lower priority (as you should do for most background tasks anyway). I have had no issues with this setup. And, BTW it also plays music on three sound cards at the same time using high-priority threads from managed code and 1second DSound buffers, all without glitching.
So how tight are your latency requirements, what baud rate and how many serial ports are you trying to serve? The buffer on your UART at most normal baud rates is more than sufficient for garbage collection and much more to delay taking the next byte off it.
GC is not as evil as it is made out to be. On a properly prioritized threaded system with good management of object sizes and lifetimes and sufficient buffering (UARTS/Sound buffers etc.) it can perform very well. Microsoft is also continuously improving it and the .NET Framework 4 now provides background garbage collection. This feature replaces concurrent garbage collection in previous versions and provides better performance. See MSDN.
-13624426 0Because you just want to generate a php file I would suggest using string/regex replace in your ide/editor
going from
<option value="a">A</option>
to
<option value="a" <?= isset($array["a"]) ? "selected" : "" ?>>A</option>
In vim (but other editors should support this too) you can do this with
:%s/value=\(".*"\)/value=\1 <?= isset($array[\1]) ? "selected" : "" ?>/g
where the part you search for is
value=\(".*"\)
and this is the part you replace
value=\1 <?= isset($array[\1]) ? "selected" : "" ?>
using
\([someregex]\)
you can 'store' some variable and with \1 you can output it in the replace part 1
-22873817 0 Node.js https.request not returning data as expectedI'm trying to proxy API requests to a sever using node's https.request() function. When I run the same request to the same endpoints with the same headers through Postman I get the data back as expected. When I run the request though the node proxy I get http 500 error codes back. Is there anything obviously wrong with the way I'm sending the requests:
#!/usr/bin/env node process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; var https = require('https'), connect = require('connect'), staticDir = 'target/ui'; var app = connect(); app.use(connect.logger('dev')) .use(connect.bodyParser()) .use(function(req, res, next){ if( /^\/api\//.test(req.url) ){ var options = { hostname: 'host.name', port: 9090, path: req.url, method: req.method, headers: { authorization: 'Basic XYZ123', 'content-type': 'application/json', accept: 'application/json, text/javascript, */*; q=0.01', } }; var proxyRequest = https.request(options).on('response', function(res){ var data = ""; res.on('data', function(chunk){ data += chunk; }) res.on('end', function(){ sendData(data); }); res.on('error', function(e){ console.log('ERROR: ', e); sendError(e, code); }) }) proxyRequest.end(); function sendData(data){ console.log('SENDING RESPONSE DATA', data) res.write(data); res.end(); } function sendError(msg, code){ res.end(msg, code) } } else { next(); } }) .use(connect.static(staticDir));; app.listen(9090);
-6618914 0 Try removing the "line=data_file.readline()" altogether? I suspect the "for line in data_file:" is also a readline operation.
-4354143 0Try giving your form an id and then use document.getElementById('yourformid').submit();
Try this...
StringYourVar text := Totext({YourNumberField} , 6 , "YourText");
or this.
-12476828 0 Sony Smartwatch widget refreshI have a Problem with my Sony SmartWatch App. I've developed a widget with control, but after the App is installed by users on the device the scheduled refresh task of the widget starts automatically. This means the refresh task is running all the time, even if the user did not turn on SmartWatch Display or start the widget. This drains the battery. If I go to the widget screen and then turn the display from off, the scheduled Task stops like expected. But if I don't do this the task is running and running and running.... How can I detect if the Display is on and the widget is running?
Thank you very much!
P.S.: It makes no difference if the "Activate Widget" preference is checked or not....
EDIT: I've found out that the widget sourcecode does not fire if I uncheck the "Display as Widget" Checkbox in preferences. This means if the refresh schedule is running and I uncheck this box, the onDestroy is never called and so the cancel schedule also not....
-6562248 0 How to optimize full text searches?I know there are a lot of question already on this subject, but I needed more specific information. So here goes:
LIKE %$str%
and full-text search?LIKE %$str%
and full-text search implemented and use the optimal one dynamically?First your code is few issues, Any way try this,
JsFiddle Example
$(function() { var counter =2; $("#addButton2").click(function () { var newTextBoxDiv2 = $(document.createElement('div')).attr("id", 'TextBoxDiv2' + counter); newTextBoxDiv2.after().html("<table width='1200' border='0' cellspacing='0' cellpadding='0'><tr><td>Date</td><td><li class='demo'><div class='box'><input class='multi' type='text' id='from-input_"+counter+"' maxlength='10'></div><div class='code-box' style='display:none;'>$('#from-input').multiDatesPicker();<pre class='code prettyprint'></pre></div></li></td></tr></table>"); newTextBoxDiv2.appendTo("#TextBoxesGroup2"); $("#from-input_"+counter).multiDatesPicker(); counter++; }); });
-8155196 0 Trying to integrate unit tests into Xcode for iOS 5.0 project, but cannot get files to link correctly I am trying to add unit tests into my Xcode project for an iOS app that I am working on. I have SenTest working with basic examples, but the second I try to test any of the project code, I get linker errors like so:
"_OBJC_CLASS_$_Account", referenced from: objc-class-ref in Tests.o ld: symbol(s) not found for architecture i386
Obviously, I could solve this by duplicating my app target configuration into my test configuration, making all of the compile sources the same and such, but this will make two different targets that I will have to maintain, which is very unappealing. Also, I could refactor the project to use a static library and share between the app and the test targets, but that also is undesirable.
Is there any way that I can use the built objects from the app target in the test target? This sure seems like a lot of work to get unit testing in my project...
Thanks for any and all help!
-8425152 0I think your lucky with the '[c-a]' thing, My tr says tr: [c-a]: invalid destination string
, which is what I would expect.
Character ranges, i.e. [a-z], in all the languages I've dealt with, need to ascend in value. Be happy that you've already figured out your solution.
Or write a function that you can use like tr "[a-z]" "[$( revCharRange a-z )]"
(which would be more expensive due to the sub-shells required to create the reverse character range.
I hope this helps.
-16595298 0Here's a general approach:
data.frame(sapply(unique(names(tempList)), function(name) do.call(c, tempList[names(tempList) == name]), simplify=FALSE) )
-28543784 0 Create new page (http page) for your require functionality to show under new window. and point the newly created page url in click window code.
Or you can use native javascript to write you content in window. For example:
HTML
<button onclick="myFunction()">Try it</button>
Javascript
<script> function myFunction() { var myWindow = window.open("", "MsgWindow", "width=200, height=100"); myWindow.document.write("<p>This is 'MsgWindow'. I am 200px wide and 100px tall!</p>"); } </script>
You can notice from myfunction
function doing couple of task, first it will generate new window object secondly we writing something under newly created window object and then fire it successfully.
By this method we do not need to worry about url to hit.
-15982294 0 var value = $('input:radio[name="radiogroupname"]:checked').val();
-24307834 0 My fast approach to solving the problem is to create a function in an autoloaded helper file in the project i'm working on. This helper just redirects to the custom 404 page. So i just call show_my_404()
instead of show_404()
function show_my_404(){ //Using 'location' not work well on some windows systems redirect('controller/page404', 'location'); }
-29377626 0 (defclass locatable () ((zone :accessor zone :initform nil) (locator :initarg :locator :initform (error "Must supply a locator parameter for this class.") :allocation :class :accessor locator)))
The slot locator
is shared in the class. It will be allocated somehow in the class object. The DEFCLASS
form creates this class object. Thus the slot locator
usually will be initialized when the class object is created and initialized. Way before the first instance of that class is created.
LispWorks Backtrace
CL-USER 50 : 1 > :b Call to CLOS::CLASS-REDEFINITION-LOCK-DEBUGGER-WRAPPER Call to INVOKE-DEBUGGER Call to ERROR Call to (METHOD CLOS::COMPUTE-CLASS-SLOT-CONSES (STANDARD-CLASS)) Call to (METHOD SHARED-INITIALIZE :AFTER (STANDARD-CLASS T)) ; <-- Call to CLOS::ENSURE-CLASS-USING-CLASS-INTERNAL Call to (METHOD CLOS:ENSURE-CLASS-USING-CLASS (CLASS T)) Call to CLOS::ENSURE-CLASS-WITHOUT-LOD Call to LET Call to LET Call to EVAL Call to CAPI::CAPI-TOP-LEVEL-FUNCTION Call to CAPI::INTERACTIVE-PANE-TOP-LOOP Call to MP::PROCESS-SG-FUNCTION
As you see SHARED-INITIALIZE
is called on the class object, which then initializes the shared slots.
I also don't think calling error
like this should be done in user code. You might find a better way to check for missing initargs.
I have just implemented a solution like the one asked about here and it seems to work. I have an MVC
application and have this code in my _Layout.chtml page but it could work in an asp.net
app by placing it in the master page I would think. I am using local session storage via the amplify.js
plugin. I use local session storage because as Mr Grieves says there could be a situation where a user is accessing the application in a way that does not cause a page refresh or redirect but still resets the session timeout on the server.
$(document).ready(function () { var sessionTimeout = '@(Session.Timeout)'; //from server at startup amplify.store.sessionStorage("sessionTimeout", sessionTimeout); amplify.store.sessionStorage("timeLeft", sessionTimeout); setInterval(checkSession, 60000); // run checkSession this every 1 minute function checkSession() { var timeLeft = amplify.store.sessionStorage("timeLeft"); timeLeft--; // decrement by 1 minute amplify.store.sessionStorage("timeLeft", timeLeft); if (timeLeft <= 10) { alert("You have " + timeLeft + " minutes before session timeout. "); } } });
Then in a page where users never cause a page refresh but still hit the server thereby causing a reset of their session I put this on a button click event:
$('#MyButton').click(function (e) { //Some Code that causes session reset but not page refresh here amplify.store.sessionStorage("sessionTimeout", 60); //default session timeout amplify.store.sessionStorage("timeLeft", 60); });
Using local session storage allows my _Layout.chtml code to see that the session has been reset here even though a page never got refreshed or redirected.
-14180758 0Fromt the docs:
When an 'r' or 'R' prefix is present, a character following a backslash is included in the string without change, and all backslashes are left in the string. For example, the string literal r"\n" consists of two characters: a backslash and a lowercase 'n'. String quotes can be escaped with a backslash, but the backslash remains in the string; for example, r"\"" is a valid string literal consisting of two characters: a backslash and a double quote; r"\" is not a valid string literal (even a raw string cannot end in an odd number of backslashes). Specifically, a raw string cannot end in a single backslash (since the backslash would escape the following quote character). Note also that a single backslash followed by a newline is interpreted as those two characters as part of the string, not as a line continuation.
Specifically, a raw string cannot end in a single backslash (since the backslash would escape the following quote character)
-24491781 0<script type="text/javascript"> $(document).ready(function() { $("#date, #date2,#date3,#date4").datepicker(); $("#date,#date2,#date3,#date4 ").datepicker("option", "dateFormat", "yy/mm/dd"); var d = new Date(); var todaysM = d.getDate() + "/" + (d.getMonth() + 1) + "/" + d.getFullYear(); var todaysM = d.getFullYear()+ "/" + (d.getMonth() + 1) + "/" + d.getDate(); if ($("#date,#date2,#date3").val() == "") { $("#date,#date2,#date3").val(todaysM); } }); </script>
-23587890 0 When you say "same method", there is really only one way to do that which is accessing the system clock. There is more than one method to do this, but they ultimately rely on the same thing. Also, the paper you referred us to relies on using Windows and Visual C and so this would not be applicable to Mac OS or Linux. As such, I'm going to try and give you platform independent methods for both MATLAB and C++. In either platform, this will give you the execution time as best as it can.
You can use the tic
and toc
commands. You start with the tic
command, then do your processing, then you finish with t = toc
. t
will thus contain how much time has elapsed in between tic
and toc
.
Here is a quick example:
tic; for i = 1 : 100000 M = rand(100,100); %// Generate a 100 x 100 uniformly random matrix t = toc; fprintf('The amount of time that has elapsed is %f seconds\n', t);
If you want to compute FPS, simply measure how long it takes to execute the algorithm for one image/frame, then take the reciprocal. This time would be seconds/frame and so to compute FPS, take the reciprocal.
You can use the ctime
library, and use the time(NULL)
call. This will return the time in seconds since Epoch (January 1, 1970). Like the MATLAB example, here is a C++ example:
#include <ctime> void func() { using namespace std; // Begin int start = time(NULL); // Put in processing code here // End - time in seconds int finish = time(NULL); // Measure time elapsed int time_elapsed = finish - start; }
To compute FPS, just follow what I did for the MATLAB example.
If you want microsecond precision to measure time in C++, you can use the clock()
function. You can do something like this:
#include <ctime> void func() { using namespace std; // Begin clock_t start = clock(); // Put in processing code here // End - time in microseconds clock_t finish = clock(); // Measure time elapsed double time_elapsed = double(finish - start) / CLOCKS_PER_SEC; }
However, the clock()
function will measure CPU time and not the actual time elapsed, so you will need to be careful here if you decide to do this. Check this posting out for more details: Easily measure elapsed time
I normally use the GWT ClientBundle for managing my images within my application like this
@Source("icons/info.png") ImageResource info();
No I want to switch to .svg graphics but I didn't find a way to use svg in a ClientBundle like SVGResource or something. I know that svg is supported in GWT and there are possibilities to insert those graphics inside GWT, but I would like to use the advantages of the ClientBundle + the advantages of svg. Has anybody already solved this problem?
-23101029 0I found problem, in my app i made a custom side view controller implementation and I didn't queue animation actions for reveal a right and a left side view. That why i think spring board got crash (too many the same animations). I switched to similar open source controller with animation queue and now everything works.
-20743863 0my bad, I was doing it wrong!!
<?php $risk_numbers = array( '2' => '20', '3' => '23', '10' => '22', '11' => '24', '12' => '25', '13' => '27', '21' => '26', ); foreach($risk_numbers as $description => $other) { if($values[$description]['value'] == 'No'){echo $values[$description]['description'].'<br/>';} if($values[$other]['label'] == 'Other' && $values[$other]['value'] != ''){echo $values[$other]['value']; echo '<br/>';} } ?>
-35244459 0 Well, question is not fresh, but this situation may still become a piece of pain. You may use toJSON
or toObject
method to get normal, iterable object. Just like this:
media = media.toJSON() Object.keys(media.audio).forEach(...)
See this post for details about toJSON
an toObject
I'm putting together a site that I want to be responsive to browser re-sizing. The site pulls one set of CSS styles for a page under 768px, another for any window larger than 768px.
I have a javascript slider (jcarousel) beneath my feature video at. If I open a window larger than 768px (using Chrome), then the javascript slider works fine. If I reduce the size of the window, the slider is hidden (with a display:none style) and other content is shown. And if I resize the window larger, the slider appears and works fine.
However, and here's my problem ... If I open a browser smaller than 768px, the CSS hides my javascript slider at the start, and shows my other content. But when I resize the window and make it larger (over 768px), the slider doesn't work right. I'm assuming the javascript and its associated styles need to be "activated" initially. Is there a way to get this working when a smaller window is opened first?
-28537242 0 Error deploying plugin to jiraI'm trying to deploy my custom plugin to jira and then the error occurs:
java.lang.ClassCastException: org.apache.xerces.jaxp.datatype.DatatypeFactoryImpl cannot be cast to javax.xml.datatype.DatatypeFactory
The project is build with Maven and if I remove and exclude every
<exclusion> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> </exclusion> <exclusion> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-impl</artifactId> </exclusion> <exclusion> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-impl</artifactId> </exclusion> <exclusion> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-api</artifactId> </exclusion> <exclusion> <groupId>xerces</groupId> <artifactId>xercesImpl</artifactId> </exclusion>
dependency
// I just paniced :)
logs inform about ClassNotFoundException
I have no idea what to do, so can anybody help?
The URL you're passing in the example above is:
'DCC?command=' + encodeURIComponent(command)
The DCC
part is actually part of the path to the webpage. It's short because it's a relative path. The fully qualified path would look something like www.sitename.com/DCC
The part after that (after the ?
character) is called the query string. That's the part of the URL that contains data that you're passing to the server (in a GET transaction), and it follows this pattern:
a=somevalue&b=anothervalue&c=yetanother
So add "&varnameA=valueA" to that string to pass both command
and varnameA
:
xhr.open('GET', 'DCC?command=' + encodeURIComponent(command)+"&varnameA=valueA",true);
You can keep tacking on &varname=value strings until your query is around 2000 characters, because that's where browsers commonly start crapping out because the URL is too long.
Remember to encode any special characters in the values (that's what encodeURIComponent()
is being used for) or you'll get some weird behavior. That means that you're appending something like +"&varnameA="+encodeURIComponent("valueA")
for each additional variable/value pair you want to pass to the server.
"Why is the compiler not allowed to see"
I don't have an answer for safe bool, but I can do this bit. It's because a conversion sequence can include at most 1 user-defined conversion (13.3.3.1.2).
As for why that is - I think someone decided that it would be too hard to figure out implicit conversions if they could have arbitrarily many user-defined conversions. The difficulty it introduces is that you can't write a class with a conversion, that "behaves like built-in types". If you write a class which, used idiomatically, "spends" the one user-defined conversion, then users of that class don't have it to "spend".
Not that you could exactly match the conversion behaviour of built-in types anyway, since in general there's no way to specify the rank of your conversion to match the rank of the conversion of the type you're imitating.
Edit: A slight modification of your first version:
#define someCondition true struct safe_bool_thing { int b; }; typedef int safe_bool_thing::* bool_type; bool_type safe_bool( const bool b ) { return b ? &safe_bool_thing::b : 0; } class MyTestableClass { public: operator bool_type () const { return safe_bool( someCondition ); } private: bool operator==(const MyTestableClass &rhs); bool operator!=(const MyTestableClass &rhs); }; int main() { MyTestableClass a; MyTestableClass b; a == b; }
a == b
will not compile, because function overload resolution ignores accessibility. Accessibility is only tested once the correct function is chosen. In this case the correct function is MyTestableClass::operator==(const MyTestableClass &)
, which is private.
Inside the class, a == b
should compile but not link.
I'm not sure if ==
and !=
are all the operators you need to overload, though, is there anything else you can do with a pointer to data member? This could get bloated. It's no better really than Bart's answer, I just mention it because your first attempt was close to working.
This is my solution:
foreach ($arr1[0] as $key => $entry) { $arr1[0][$key][$arr1[0][$key]["Str1"]] = $arr2[0][$entry["Str1"]]; }
This produces the following output:
[ [ { "Str1":"ABC", "Str2":"Some Value", "Str3":"Something", "ABC":"Hello" }, { "Str1":"DEF", "Str2":"Another Value", "Str3":"Test", "DEF":"Test" }, { "Str1":"GHI", "Str2":"NULL", "Str3":"Blah", "GHI":"Something" } ] ]
-14882787 0 How can I write a regex in Java that will perform a .replaceFirst on a group that is not in a comment? So I need to return modified String where it replaces the first instance of a token with another token while skipping comments. Here's an example of what I'm talking about:
This whole quote is one big String -- I don't want to replace this @@ But I want to replace this @@!
Being a former .NET developer, I thought this was easy. I'd just do a negative lookbehind like this:
(?<!--.*)@@
But then I learned Java can't do this. So upon learning that the curly braces are okay, I tried this:
(?<!--.{0,9001})@@
That didn't throw an exception, but it did match the @@ in the comment.
When I test this regex with a Java regex tester, it works as expected. About the only thing I can think of is that I'm using Java 1.5. Is it possible that Java 1.5 has a bug in its regex engine? Assuming it does, how do I get Java 1.5 to do what I want it to do without breaking up my string and reassembling it?
EDIT I changed the # to the -- operator since it looks like the regex will be more complex with two chars instead of one. I originally did not reveal that I was modifying a query in order to avoid off topic discussion on "Well you shouldn't modify queries that way!" I have a very good reason for doing this. Please don't discuss query modification good practices. Thanks
-8286477 0 Infix for All (leaves)Infix[]
works only at first level:
Infix[(c a^b)^d] (* -> (a^b c) ~Power~ d *)
As I want to (don't ask why) get the full expression switched to infix notation, I tried something like:
SetAttributes[toInfx, HoldAll]; toInfx[expr_] := Module[{prfx, infx}, prfx = Level[expr, {0, Infinity}]; infx = Infix /@ prfx /. {Infix[a_Symbol] -> a, Infix[a_?NumericQ] -> a}; Fold[ReplaceAll[#1, #2] &, expr, Reverse@Thread[Rule[prfx, infx]]] ] k = toInfx[(c a^b)^d] (* -> (c ~Times~ (a ~Power~ b)) ~Power~ d *)
But this has two evident problems, because
(c a^b)^d == a~Power~b~Times~c~Power~d
k = toInfx[a/b + ArcTan[a/b]]
Is there an easy way to get Infix[]
working for All (leaves)?
I just wrote this function :
function Array_in_String($Haystack1, $Values1) { foreach ($Values1 as $token1) { if (strpos($Haystack1, $token1) !== false) return true; } }
that basically searches a string $Haystack1
for multiple values in an array $Values1
and returns true if hits a match.
Before that, I searched a lot in PHP for a similar string function. I'm still wondering if PHP has a similar function?
-5487950 0Presuming your website uses a "local" mail server, such as Postfix/Sendmail/Exim, you'd check the mail log. Generally (on Unix-ish systems), that's /var/log/maillog. It'll contain the full transcript of the email's passage through the mail server, from the moment it was handed off from PHP to when it goes out the door to the recipient.
However, some accepting servers will LIE to you about the mail - they'll accept it with the usual "200 OK" success code, then just dump it in the trash because it triggered a spam filter or your IP/IP-block has been blacklisted somewhere.
You could embed a web bug in the mail so that (hopefully) the client's email program will ping your server whenever they read the mail, but most mail clients now block remote images by default, so this is very unreliable as well.
Basically, email is a best-effort-not-guaranteed-to-succeed business, and the entire system is set up to lie to you about everything.
-14248572 0 AutoFilter method failingThis sub routine has suddenly stopped working; new sheets have been added, but no change to this code. Any idea why I'm getting the message "Auto filter method of range class failed" Run time error 1004?
Sub Hide_Row() Application.ScreenUpdating = False ActiveSheet.Unprotect Range("a6:HO499").AutoFilter Field:=2, Criteria1:="<>" End Sub
-35988627 0 How to open a new word document from outlook add-ins? I created an office outlook add-ins application. In my add-ins I have a button 'open word document' to open new Microsoft word document with word add-ins in locally and want to save it in Microsoft oneDrive
After searching some document I found a code that I tried but not working ..
after click on 'open word document' called a function openWordAddin()
function openWordAddin() { var url = 'ms-word:ofe|u|' + 'document.docx'; window.open(url, 'myDoc', '', false); }
it open a new tab in browser but not word document. can anyone help me pls..
-40578845 0So in my case there has to bee a condition for errno and it has to return true.
set_error_handler( function( $errno, $errstr, $errfile, $errline, array $errcontext ) { // Cause Php does not catch stream_socket_client warnings message. if ( $errno == E_WARNING ) throw new \Exception( $errstr, $errno ); // Is necessary to handle other errors by default handler. return true; });
-20624761 0 Chrome "unable to load" an image as CSS 'background' - then it blames jquery Hurr durr durrr disable adblock when working on sites that have ads. Bah.
I have an image set through straight CSS as a background image on a div element. For some reason, the image (which is actually web accessible) isn't loading. Chrome dev tools show an error, but the error seems to blame jquery.
Failed 'GET' request
Chrome blaming jquery
Basic CSS
Image is accessible by chrome
No CSS is overriding the image
Chrome tools don't give me much - other images loaded in the exact same way, from the exact same place seem to load fine.
So I'm at a loss here. No idea why it's not showing up (ignore the '.dev' domain for the moment - it's just pointing to my local apache, and this same problem is showing up on the production site, too).
Although I don't think it's affecting it, I'm using Laravel 4 as a background PHP framework.
-5012134 0You should use the Feedburner Awareness API. For instance you can retrieve the URL feedburner.google.com/api/awareness/1.0/GetFeedData?uri=http://feeds.feedburner.com/phpclassesblog-xml and then parse the returned XML to extract the relevant statistics.
-25888817 0 Android Bluetooth status 133 in onCharacteristicwriteI'm new to Android and now doing a simple app that requires writing some data into a peripheral device.
Actually nothing goes wrong in a Samsung GT-S7272C device. But when I switch to Sony LT29i, there will always be a status 133 when I'm trying to write into a certain characteristic. I will give out some brief code.
BluetoothGattService syncService = gatt.getService(SYNC_DATA_SERVICE); BluetoothGattCharacteristic tChar = syncService.getCharacteristic(SYNC_TIME_INPUT_CHAR); if (tChar == null) throw new AssertionError("characteristic null when sync time!"); int diff = /*a int*/; tChar.setValue(diff, BluetoothGattCharacteristic.FORMAT_SINT32, 0); gatt.writeCharacteristic(tChar);
and the onCharacteristicWrite function:
@Override public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { Log.d(TAG, String.format("Sync: onCharWrite, status = %d", status)); try { if (status != BluetoothGatt.GATT_SUCCESS) throw new AssertionError("Error on char write"); super.onCharacteristicWrite(gatt, characteristic, status); if (characteristic.getUuid().equals(SYNC_TIME_INPUT_CHAR)) { BluetoothGattService syncService = gatt.getService(SYNC_DATA_SERVICE); BluetoothGattCharacteristic tChar = syncService.getCharacteristic(SYNC_HEIGHT_INPUT_CHAR); if (tChar == null) throw new AssertionError("characteristic null when sync time!"); tChar.setValue(/*another int*/, BluetoothGattCharacteristic.FORMAT_SINT32, 0); gatt.writeCharacteristic(tChar); } else if { ... } } catch (AssertionError e) { ... }
Writing into first characteristic has nothing wrong and control will reach the onCharacteristicWrite and enter the first if
statement with status 0
, which means success. Problem is the second writing action in the if
statement, which will also trigger onCharacteristicWrite function but yield a status 133
, which cannot be found in the official site. Then the device disconnect automatically.
I've confirmed that the data type and the offset are all correct. And because in another device it works really nice, I think there might be some tiny differences of the bluetooth stack implementation between different device that I should do something more tricky to solve this problem.
I've search for result for a long time. Some results lead me to the C source code(Sorry, I will post the link below because I don't have enough reputation to post more than 2 links), but I can only find that 133
means GATT_ERROR there, which is not more helpful than just a 133
. I've also found a issue in google group, discussing some familiar questions, but I failed to find a solution here.
I'm a little bit sad because, if it is something wrong with the C code, even if I can locate what's wrong, I still have no way to make it right in my own code, right?
I hope that someone has the familiar experience before and may give me some suggestions. Thanks a lot!
links:
C source code: https://android.googlesource.com/platform/external/bluetooth/bluedroid/+/android-4.4.2_r1/stack/include/gatt_api.h
Issue: https://code.google.com/p/android/issues/detail?id=58381
vizier answered quite nicely but I am under the impression that his analysis has a mistake. I think he is not aware that Opencv has a version for android called OpenCV4Android. It is Java wrappers for the c++ functionality, meaning you can avoid using Android NDK and program everything in Java. This would make JavaCV "non-official" library redundant except for the fact that this one, besides wrapping opencv, also wraps a lot of other nice CV libraries.
Edit:
This doesn't change vizier conclusions about recommending OpenCV, it actually adds more points towards choosing it.
-22942076 0Both lines are showing a single input that connects to the inputs of two separate gates. For example, this line:
self.A.connect([self.A1.A, self.I2.A])
Is showing that the overall input A
is wired to two inputs: input A
on the AND gate A1 and input A
on the NOT gate I2
. That's indicated in the wiring diagram by the red circle/square:
The line self.B.connect([self.I1.A, self.A2.A])
does the same thing with the B
input to the XOR gate, wiring it to I1
and A2
(the blue circle above).
The error you saw with print
is because it is a function in Python 3. For Python 2.x, you just do print "Stuff I want printed"
.
I'm using a camel route to dispatch message to topic.
<route> <from uri="activemq:queue:TEST"/> <to uri="activemq:topic:TEST"/> </route>
How to set timeToLive propertie to the message send by camel?
-6864050 0 SQLite: Joining two select statements that include a count expressionI have a table containing a list of folders, each folder has an ID and Description
SELECT * FROM folders _id | description --------------------------- 1 | default 2 | test
I have an images table that contains a list of images, each image has a folderid
select folderid, count(*) as imagecount from images GROUP BY folderid; folderid| imagecount --------------------------- 1 | 4 2 | 5
I want to be able to write a query that returns a list of all folders, with its description, and how many images is inside it
????? _id | description | imagecount ------------------------------------------------------ 1 | default | 4 2 | test | 5
I tried the following query:
SELECT _id, description from folders, (select folderid, count(*) as imagecount from images GROUP BY folder) WHERE _id = folderid;
However it doesn't work, because it doesn't return the imagecount column. Any ideas?
-36637021 0 Width - fifty per cent for table cell display breaks into seperate lineI am trying to display a panel that displays information in a tabular fashion as,
My pluker code is here. Now, i use display:table-row
to put NAME
label and value My Venue
in one place. When i give 50% width to the table-cell
display, it breaks into next line as,
I am able to fix it by making the width as 49% for table-cell
display.
I am curious why does 50%
width break it into a different line, since table
display doesn't have any margin.
I think you should put it this way though
<?php $connection = mysql_connect('localhost', 'users', 'password'); //The Blank string is the password mysql_select_db('users'); let all the connection be outside the "ul" tag. $query = ("SELECT * FROM oneusers"); //You don't need a ; like you do in SQL $result = mysql_query($query); $query = ("SELECT * FROM oneusers"); //You don't need a ; like you do in SQL $result = mysql_query($query); $row=mysql_fetch_array($result); ?> <ul class="names"> <table> <tr> <th>Navn</th> <th>Email</th> <th>Score</th> </tr> <?php while($row){ //Creates a loop to loop through results echo "<tr><td>" . $row['iUserName'] . "</td><td>" . $row['iUserEmail'] . "</td><td>" . $row['iUserCash'] . " DKK</td></tr>"; //$row['index'] the index here is a field name } mysql_close(); //Make sure to close out the database connection ?> </table> </ul>
-40079029 0 how to prompt a pop up message right after user input in jtextfield I am new in Java and now trying to develop a simple program to support my research findings. In this program, I'll be displaying randomized images and users were to enter single integer in jtextfield provided. The users are required to count and answer the number of animals displayed. Since I want to develop the program as simple as possible, I imagine my tool will be straight forward.
Question 1: There will be a JTextField provided for user to input their answer. Is there any coding that could restrict user input right after a single integer(between 1-6) has been keyed in the box? As I need my program to be straight forward and easy to understand, I do not want user to click on any button so as to lead them to next image. May I know is there any way to restrict user input and lead the program to next image right after user enter a number without clicking any button? Question 1
Question 2: Right after the user key in the single integer answer, I would like to prompt a simple popup that includes a praise to user such as "Well done". Since the JOptionPane I'll be using will contain two buttons: "OK" and "cancel", may I know how to make sure the program leads to next randomized image after user click on "OK" button. Question 2
Question 3: Is there any ways to keep the input cursor for typing just in the JTextField provided? This is because I want the program as simple as possible that user do not need to waste their time moving their mouse and click at the jtextfield to start entering their answer. I want my program to work like: everytime user enter a single integer, a pop up message appear, user click "OK" and lead to next randomized image. At the next image, user just have to enter the answer without moving the cursor to click at the jtextfield(Example:By referring to image question 2, after user click "OK", how to make the program leads to next randomized image as image question 1). May I know is there any way to develop the program in such way?
This is my code.
package Project; import java.awt.*; import java.awt.event.*; import java.sql.*; public class Task implements KeyListener, ActionListener { static JFrame frame = new JFrame("FYP"); JPanel content = new JPanel(); JPanel content2 = new JPanel(); JLabel lbl2 = new JLabel(); JLabel labelUsername = new JLabel(""); JTextField textField = new JTextField(); long StartA=System.currentTimeMillis(); //connectionMSAccess Connection c; Statement s; ResultSet r; int sum=0; int Error=0; int total_test=0; static String inputID; static int index = 0; String[] imgFileHP = {"1.jpg","2.jpg","3.jpg","4.jpg","5.jpg","6.jpg","7.jpg","8.jpg","9.jpg","10.jpg", "11.jpg","12.jpg","13.jpg","14.jpg","15.jpg","16.jpg","17.jpg","18.jpg","19.jpg","20.jpg"}; String[] imgNo = {"5","5","4","6","4","6","3","4","5","3","5","4","3","5","4","5","6","4","4","6"}; List <String> pictureFileArray = Arrays.asList(imgFileHP); int randomNo; public Task(String inputID){ frame.setSize(2200,2500);; frame.setLocationRelativeTo(null);; frame.setVisible(true);; frame.getContentPane().setLayout(new BorderLayout(0,0)); Collections.shuffle(pictureFileArray); Task(inputID); } public void Task(String inputID){ JPanel panel = new JPanel(); JLabel labelUsername = new JLabel(""); frame.getContentPane().add(panel, BorderLayout.CENTER); panel.setBackground(Color.WHITE); Image im = new ImageIcon(Task.class.getResource("/images/" + imgFileHP[index])).getImage(); ImageIcon iconLogo = new ImageIcon(im); labelUsername.setIcon(iconLogo); panel.add(labelUsername); textField.setText(""); textField.setColumns(10); textField.setVisible(true); textField.addKeyListener(this); panel.add(labelUsername); panel.add(textField); frame.setVisible(true); int keyb = JOptionPane.showOptionDialog(null, "Well done!", "Message", JOptionPane.OK_CANCEL_OPTION,JOptionPane.PLAIN_MESSAGE,null,null,null); if(keyb == JOptionPane.OK_OPTION) { frame.dispose(); } } public void actionPerformaed(ActionEvent ae){ if(!textField.getText().equals("")){ total_test += 1; if(booleanisNumeric(textField.getText())){ if(Integer.valueOf(imgNo[randomNo])==Integer.valueOf(textField.getText())){ System.out.println("Correct"); sum+=1; }else{ System.out.println("Invalid input"); Error+=1; } refreshFrame(); }else{ System.out.println("Null Input"); } } } public void refreshFrame(){ if(total_test>=20){ System.out.println("Correct:" +sum+" Incorrect: "+Error); frame.dispose(); }else{ frame.getContentPane().removeAll(); //getContentPane().removeAll(); Task(inputID); } } public static void main(String args[]){ Task a = new Task(inputID); } @Override public void keyPressed(KeyEvent e){ } @Override public void keyTyped(KeyEvent e){ } public static boolean booleanisNumeric(String str){ try{ Integer.valueOf(str); } catch(NumberFormatException nfe){ return false; } return true; } @Override public void actionPerformed(ActionEvent arg0) { // TODO Auto-generated method stub } @Override public void keyReleased(KeyEvent arg0) { // TODO Auto-generated method stub } }
-4360188 0 C# - Send UI reference to Task.Factory.StartNew();? How would you send/pass instance references to a new task?
Let's say I've got this:
public BlockingCollection<string> blockingCollection = new BlockingCollection<string>(); textBox_txt.Text = "Result: "; public Task t = Task.Factory.StartNew(() => { foreach (string value in *???1*.blockingCollection.GetConsumingEnumerable()) { *???1*.blockingCollection.Take() [...bla...] *???2*.Invoke(new updateTextBox_txtCallback(*???2*.updatetextBox_txt) , new object[] { "THE RESULT!\r\n" }); } });
I'm guessing that somewhere in here StartNew(() =>
I have to pass the references to the blockingContent and to the textBox. I've looked around but couldn't figure out the syntax. (it's quite hairy)
Help, please.
[Edit] So, if I call a static object from withing the Task, it obviously works; but I need the task to work with instances; namely the blockingCollection and the updateTextBox_txtCallback Invoke.
-35274165 0 How to speed up TortoiseSVN to VisualSVN server through SSH tunnel?This is our current setup: Windows Server 2008 with Visual SVN Server. On the client side we use tortoise svn.
Inside the company (internal network), the access speed(checkout,update,commit) is good.
When we access from outside the company via our SSH tunnel, it becomes really slow.
I read that there could be a few possibilities:
Any other suggestions ? Thank you
-27148541 0 SQLite and JDBC: returns UnsatisfiedLinkErrorI am running Xubuntu in VirtualBox. I installed sqlite3 which for some reason does not come bundled any more. I added sqlite-jdbc-3.8.7.jar to my build path and run this simple code to test it.
import java.sql.*; public class JDBC_test { public static void main(String[] args) throws ClassNotFoundException, SQLException { Class.forName("org.sqlite.JDBC"); Connection connection = DriverManager.getConnection("jdbc:sqlite:test.db"); connection.close(); } }
I get this error:
Exception in thread "main" java.lang.UnsatisfiedLinkError: org.sqlite.core.NativeDB._open(Ljava/lang/String;I)V at org.sqlite.core.NativeDB._open(Native Method) at org.sqlite.core.DB.open(DB.java:161) at org.sqlite.core.CoreConnection.open(CoreConnection.java:145) at org.sqlite.core.CoreConnection.<init>(CoreConnection.java:66) at org.sqlite.jdbc3.JDBC3Connection.<init>(JDBC3Connection.java:21) at org.sqlite.jdbc4.JDBC4Connection.<init>(JDBC4Connection.java:23) at org.sqlite.SQLiteConnection.<init>(SQLiteConnection.java:45) at org.sqlite.JDBC.createConnection(JDBC.java:114) at org.sqlite.JDBC.connect(JDBC.java:88) at java.sql.DriverManager.getConnection(DriverManager.java:571) at java.sql.DriverManager.getConnection(DriverManager.java:233) at JDBC_test.main(JDBC_test.java:7)
I get the same error when I try to connect to an existing DB by substituting "test.db" with the full path to the file. Any ideas why?
-3485916 0The function readfile
should be faster.
If you are using PHP as an Apache module, you can also look into virtual
.
The approach of this article is really something that can be become a pain, because you already have a generic repository and a generic IUnitOfWork in EF and creating the specific repository for each type just removes the benefit of the generic!
I am posting here a sample of how i have a generic Repository and my IUnitOfWork, with this you can have a very nice repository!
public interface IUnitOfWork : IDisposable { void Save(); void Save(SaveOptions saveOptions); } public interface IRepository<TEntity> : IDisposable where TEntity : class { IUnitOfWork Session { get; } IList<TEntity> GetAll(); IList<TEntity> GetAll(Expression<Func<TEntity, bool>> predicate); bool Add(TEntity entity); bool Delete(TEntity entity); bool Update(TEntity entity); bool IsValid(TEntity entity); }
And the implementation something like:
public class Repository : Component, IRepository { protected DbContext session; public virtual IUnitOfWork Session { get { if (session == null) throw new InvalidOperationException("A session IUnitOfWork do repositório não está instanciada."); return (session as IUnitOfWork); } } public virtual DbContext Context { get { return session; } } public Repository(IUnitOfWork instance) { SetSession(instance); } public IList<TEntity> GetAll<TEntity>() where TEntity : class { return session.Set<TEntity>().ToList(); } public IList<TEntity> GetAll<TEntity>(Expression<Func<TEntity, bool>> predicate) where TEntity : class { return session.Set<TEntity>().Where(predicate).ToList(); } public bool Add<TEntity>(TEntity entity) where TEntity : class { if (!IsValid(entity)) return false; try { session.Set(typeof(TEntity)).Add(entity); return session.Entry(entity).GetValidationResult().IsValid; } catch (Exception ex) { if (ex.InnerException != null) throw new Exception(ex.InnerException.Message, ex); throw new Exception(ex.Message, ex); } } public bool Delete<TEntity>(TEntity entity) where TEntity : class { if (!IsValid(entity)) return false; try { session.Set(typeof(TEntity)).Remove(entity); return session.Entry(entity).GetValidationResult().IsValid; } catch (Exception ex) { if (ex.InnerException != null) throw new Exception(ex.InnerException.Message, ex); throw new Exception(ex.Message, ex); } } public bool Update<TEntity>(TEntity entity) where TEntity : class { if (!IsValid(entity)) return false; try { session.Set(typeof(TEntity)).Attach(entity); session.Entry(entity).State = EntityState.Modified; return session.Entry(entity).GetValidationResult().IsValid; } catch (Exception ex) { if (ex.InnerException != null) throw new Exception(ex.InnerException.Message, ex); throw new Exception(ex.Message, ex); } } public virtual bool IsValid<TEntity>(TEntity value) where TEntity : class { if (value == null) throw new ArgumentNullException("A entidade não pode ser nula."); return true; } public void SetSession(IUnitOfWork session) { SetUnitOfWork(session); } protected internal void SetUnitOfWork(IUnitOfWork session) { if (!(session is DbContext)) throw new ArgumentException("A instância IUnitOfWork deve um DbContext."); SetDbContext(session as DbContext); } protected internal void SetDbContext(DbContext session) { if (session == null) throw new ArgumentNullException("DbContext: instance"); if (!(session is IUnitOfWork)) throw new ArgumentException("A instância DbContext deve implementar a interface IUnitOfWork."); this.session = session; } }
-21745505 0 Recently (only a few months ago) the folks behind Phusion Passenger add support to Heroku. Definitely this is an alternative you should try and see if fits your needs.
Is blazing fast even with 1 dyno and the drop in response time is palpable. A simple Passenger Ruby Heroku Demo is hosted on github.
The main benefits that Passengers on Heroku claims are:
Static asset acceleration through Nginx - Don't let your Ruby app serve static assets, let Nginx do it for you and offload your app for the really important tasks. Nginx will do a much better job.
Multiple worker processes - Instead of running only one worker on a dyno, Phusion Passenger runs multiple worker on a single dyno, thus utilizing its resources to its fullest and giving you more bang for the buck. This approach is similar to Unicorn's. But unlike Unicorn, Phusion Passenger dynamically scales the number of worker processes based on current traffic, thus freeing up resources when they're not necessary.
Memory optimizations - Phusion Passenger uses less memory than Thin and Unicorn. It also supports copy-on-write virtual memory in combination with code preloading, thus making your app use even less memory when run on Ruby 2.0.
Request/response buffering - The included Nginx buffers requests and responses, thus protecting your app against slow clients (e.g. mobile devices on mobile networks) and improving performance.
Out-of-band garbage collection - Ruby's garbage collector is slow, but why bother your visitors with long response times? Fix this by running garbage collection outside of the normal request-response cycle! This concept, first introduced by Unicorn, has been improved upon: Phusion Passenger ensures that only one request at the same time is running out-of-band garbage collection, thus eliminating all the problems Unicorn's out-of-band garbage collection has.
JRuby support - Unicorn's a better choice than Thin, but it doesn't support JRuby. Phusion Passenger does.
Hope this helps.
-32208998 0I would say that the best alternative is to use Controllers since they, as you said, work well with FXML injection.
I don't see how letting one parent controller class control the widget is a bad thing since a class can implement interfaces of your choosing and even extend another class, inheriting its methods/attributes.
Plus, you can even use Scene Builder to easily manipulate the widget if you do import your fxml into scene builder.
-18203319 0 Possible to add partial view into a pre-rendered partial view in MVC3/4 within browser request?I am currently facing an issue about adding dynamic partial view into a partial view which is pre-rendered.
Situation: I have a view which contains a partial view (contains nothing initially, lets call it "A"). I want to add a dynamic partial view called "B" into the partial view "A" and keep stacking over time, and each of the partial view "B" would have their own GUID.
Possible to achieve this scenario?
-37254522 0If you need all words which are occurring repeatedly ..
List<string> list = new List<string>(); list.Add("A"); list.Add("A"); list.Add("B"); var most = (from i in list group i by i into grp orderby grp.Count() descending select new { grp.Key, Cnt = grp.Count() }).Where (r=>r.Cnt>1);
-11437854 0 As far as I can see mContext is null; and it may be causing this exception when instantiating the Intent.
-36081509 0Your code will return same values for fooIndex1
and fooIndex2
only if DateTime.Now.Millisecond
is the same for different runs. It's specified in Random class specification. I've have run your code twice. First run gives fooIndex1 = 0, fooIndex2 = 2
and the second fooIndex1 = 1, fooIndex2 = 3
.
Strange that you use r.Next(4)
. May be it's better to use r.Next(foosList.Count)
to be able to access all items in your foosList
.
You can generate a string to be used as a query:
var query = []; for(var i=1;i<=10;i++) query.push('a[rel=example_' + i + ']'); $(query.join(',')).fancybox({});
-29780959 0 You can achieve this by updaing your controller function as :
vs.selectTag = function(term,k) { if(vs.toggleTags.item.indexOf(k) == -1){ vs.toggleTags.item.push(k) } else { vs.toggleTags.item.splice(vs.toggleTags.item.indexOf(k),1); } alert(term +' in tag #'+ vs.toggleTags.item); };
And update html to:
<li ng-repeat="(k, m) in tags" ng-class="{'selected':toggleTags.item.indexOf(k) > -1}" ng-click="selectTag(m.name,k)"> <div class="tag">{{m.name}}</div> </li>
-4007303 0 GMP provides a convenient c++ binding for arbitrary precision integers
-19283051 0The thread handling the request to the Index
action with id=101
of your controller should be blocked. Threads handling other requests of other sessions will not be blocked. Even other requests for the same session may not be blocked depending on ReadOnly
session attribute of corresponding controllers [SessionState(System.Web.SessionState.SessionStateBehavior.ReadOnly)]
.
i came across a MIT lecture on recursion where they checked palindrome using recursion,and there they checked it using logic where they compare first and last alphabet and so on.. what i thought is something as follows
just a pseudo code:
String original="abba"; String reverse = ""; for(int i=original.length()-1;i>=0;i--) { reverse+=new String(original.substring(i,i+1)); } if(original.equals(reverse)) System.out.println("palindrome"); else System.out.println("not palindrome");
i have two doubts
compareTo()
method checks if strings are equal? DOes it compare bytecode or something?Yes, absolutely, that's possible and pretty easy to do: all you need is to create an extension with a content script that will be injected into that particular page and remove the element for you.
To do what you want you'll need to:
manifest.json
file.Specify the "content_scripts"
field in the manifest.json
, and declare the script you want to inject. Something like this:
"content_scripts": [ { "matches": "http://somesite.com/somepage.html", "js": "/content_script.js" } ]
Take a look here to find out how content scripts work.
Create a content_script.js
, which will delete the element for you. This script will basically contain the following two lines:
var element = document.querySelector('div.feedmain'); element.parentElement.removeChild(element);
You need this: http://www.iis.net/download/WebDeploy
-24757768 0In TreeView.SelectedItemChanged event, we get e.NewValue which is type of TreeViewItem, so I think you can use following code to select an item when it's group is selected.
var item = (e.NewValue as TreeViewItem); if (item.Items.Count > 0) { (item.Items[0] as TreeViewItem).IsSelected = true; }
-39091964 0 Remove menubar from Electron app How do I remove this menu-bar from my electron apps:
Also it says "Hello World"(is this because I downloaded electron pre-built, and will go away once I package the application?). I didn't code these into the html, so I don't know how to get it out!-
-1607632 0Are you in a situation where your data could be normalized? What you're trying to do seems like a dead giveaway that this is the actual problem.
-18541944 0 When making a POST call using a WebClient, how do I send duplicate values in the NameValueCollection?I am unfortunately at the mercy of an API that forces the reuse of parameter names in a POST call.
The end result POST params look like this:
ArgNameA: xyz ArgNameB: abc ArgNameC: 123 ArgNameD: LMN ArgNameC: 789 ArgNameD: JKL ArgNameC: ... ArgNameD: ...
You get the idea.
I'm currently using a NamedValueCollection and sending that to a WebClient to do the POST call. That works fine but when I try to reuse ArgNameC and ArgNameD over and over, it appears to recognize the names as already existing in the collection and therefor won't add them (or maybe it updates them, I'm not sure).
How do I make a POST using a WebClient which allows me to reuse POST argument names?
-39007139 0 How can I getText() from EditText in Fragment and pass in Volley Parameters?I am using Volley in Fragments for the first time.
Can anyone help me with this. I am trying this following code for the fragment which I am calling from a navigation drawer:
public class ChangePassword extends android.app.Fragment implements View.OnClickListener { EditText etOldSignUpPassword; EditText etNewSignUpPassword; EditText etNewSignUpConfirmPassword; ImageButton imageChangePasswordButton; ProgressBar pbWeb; String old,npass,ncpass; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_change_password, container, false); etOldSignUpPassword = (EditText)v.findViewById(R.id.etOldPassword); etNewSignUpPassword = (EditText)v.findViewById(R.id.etNewSignUpPassword); etNewSignUpConfirmPassword = (EditText)v.findViewById(R.id.etNewSignUpConfirmPassword); imageChangePasswordButton = (ImageButton)v.findViewById(R.id.imageChangePasswordButton); pbWeb = (ProgressBar)v.findViewById(R.id.pbWebC); pbWeb.setVisibility(View.GONE); imageChangePasswordButton.setOnClickListener(this); return v; } @Override public void onClick(View view) { if(view.getId() == R.id.imageChangePasswordButton) { old = etOldSignUpPassword.getText().toString(); npass = etNewSignUpPassword.getText().toString(); ncpass = etNewSignUpConfirmPassword.getText().toString(); if (!isNetworkAvailable()) { Toast.makeText(getActivity(), "Your Wifi/Data is disabled. Please switch on and try again", Toast.LENGTH_SHORT).show(); } else { pbWeb.setVisibility(View.VISIBLE); String server_url = "url_working_fine_for_activity_so_no_issue_here"; StringRequest strReq = new StringRequest(Request.Method.POST, server_url, new Response.Listener<String>() { @Override public void onResponse(String response) { if (response.equals("SUCCESS")) { Toast.makeText(getActivity(), "Password Changed Successfully", Toast.LENGTH_SHORT).show(); Intent loginIntent = new Intent(getActivity(), LoginActivity.class); startActivity(loginIntent); pbWeb.setVisibility(View.GONE); getActivity().finish(); } else { pbWeb.setVisibility(View.GONE); Toast.makeText(getActivity(), "Couldn't Change Password. Old Password Exists", Toast.LENGTH_SHORT).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { pbWeb.setVisibility(View.GONE); Toast.makeText(getActivity(), error.toString(), Toast.LENGTH_SHORT).show(); } }) { @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> map = new HashMap<String, String>(); map.put("old", old);//etOldPassword.getText().toString() throws NullPointerException map.put("new", npass);//"MY_DEFAULT_VALUE" as value is working fine but that is not the use case map.put("newCon", ncpass); return map; } }; //VolleySingleton is fine as working in Activity as well as when I give default values in getParams so no issue in this class VolleySingleton.getInstance(getActivity().getApplicationContext()).addToReqQueue(strReq); } } }
PREV: Currently this code leads to a crash.
NOTE: I have tried using onClickListener() directly on imageChangePasswordButton inside onActivityCreated() method without implemeting onClickListener on the class but found on a thread that there is a bug.
EDIT: Current Code as seen is working fine.
Here is the xml as requested:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".mypackage.ChangePassword"> <!--The class ChangePassword is inside mypackage--> <ProgressBar android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/pbWebC" style="@android:style/Widget.ProgressBar.Small" android:layout_centerInParent="true" /> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_alignParentTop="true"> <ImageView android:layout_width="150dp" android:layout_height="150dp" android:src="@drawable/image1" android:id="@+id/logo" android:layout_gravity="center_horizontal" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPassword" android:hint="@string/prompt_old_email" android:ems="10" android:layout_marginTop="10dp" android:id="@+id/etOldPassword" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPassword" android:hint="@string/prompt_new_password" android:ems="10" android:layout_marginTop="10dp" android:id="@+id/etNewSignUpPassword" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPassword" android:hint="@string/prompt_new_confirm_password" android:ems="10" android:layout_marginTop="10dp" android:id="@+id/etNewSignUpConfirmPassword" /> <ImageButton android:layout_width="150dp" android:layout_height="50dp" android:layout_gravity="center" android:id="@+id/imageChangePasswordButton" android:layout_marginTop="20dp" android:src="@drawable/reset" /> </LinearLayout> </RelativeLayout>
EDIT: Code working fine. Thanks for the help. @LongRanger @i-Droid
-6794890 0But the iframe call a foreign page. I don't have this page in my solution. I tried some javascript like
function resizeFrame(f) { f.style.height = f.contentWindow.document.body.scrollHeight + "px"; }
No, not at the present time. C++0x will change the meaning of auto
, and add a new keyword decltype
that lets you do things like this. If you're using gcc/g++, you might also look into using its typeof
operator, which is quite similar (has a subtle difference when dealing with references).
Generate array of values of data-x
and data-y
values using map()
and get()
. Then use Math.min
and Math.max
with apply()
to get maximum and minimum value from array.
// generate array of `data-x` attribute var arr1 = $('[data-x]').map(function() { return $(this).data('x'); }).get(); // generate array of `data-y` attribute var arr2 = $('[data-y]').map(function() { return $(this).data('y'); }).get(); console.log( Math.min.apply(Math, arr1), Math.min.apply(Math, arr2), Math.max.apply(Math, arr1), Math.max.apply(Math, arr2) )
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="container"> <div class="right" data-x="1" data-y="1"></div> <div class="right" data-x="2" data-y="1"></div> <div class="right" data-x="3" data-y="1"></div> <div class="right" data-x="4" data-y="1"></div> </div>
I want to add SDL and SDL_image to my Visual Studio project. But can I do it locally only for this project? I don't want to put the dlls in System32 folder.
-36362252 0cptr = malloc(256 * sizeof(char));
Above line is wrong. Even if you compute number of bytes allocated above, it is 256 bytes. If size of pointer is 4 bytes on your machine, it would be enough for 64 pointers. Instead you need 256 pointers. Use
cptr = malloc(256 * sizeof(char *));
-32584865 0 How to bind AJAX loaded elements to JQuery plugins with on() function I am using a JQuery plugin datepicker that allows me to set options e.g. default date, format, minimum date etc.
Here is the code
$(".standardDatePicker").datepicker({ defaultDate: "+1w", dateFormat: 'dd/mm/yy', changeMonth: true, numberOfMonths: 1, minDate: new Date(_currentTime.getFullYear(), _currentTime.getMonth(), _currentTime.getDate(), 1) });
I am loading content via Ajax into a modal, but am then trying to bind those elements that have been inserted into the DOM with a call to the datepicker plugin.
The following code has worked fine on other code but i cant find a way to use it with plugins, is this even possible without modifying the plugin?
What I have tried
$("document.standardDatePicker").on(datepicker({ defaultDate: "+1w", dateFormat: 'dd/mm/yy', changeMonth: true, numberOfMonths: 1, minDate: new Date(_currentTime.getFullYear(), _currentTime.getMonth(), _currentTime.getDate(), 1) }));
-33248900 0 The within_polygon
function is only available on the newest API endpoint for each dataset, so make sure you're using the correct endpoint. You should be using this one instead:
https://dev.socrata.com/foundry/#/data.seattle.gov/3c4b-gdxv
Using that endpoint, and correcting the location fieldname to location
, I was able to create this query that works:
https://data.seattle.gov/resource/3c4b-gdxv.json?$where=within_polygon(location,%20%27MULTIPOLYGON(((-122.345239999941%2047.7339842230969,-122.344670705637%2047.7051200031236,%20-122.35540073991%2047.7051536806063,-122.355548433321%2047.7340195160745,%20-122.345239999941%2047.7339842230969)))%27)
-39811346 0 Simple C++ demo for caffe? I want to implement a simple C++ demo. Its purpose is in loading an image and predicting its class using caffe network. There is examples/classification/classification.cpp. This example takes exactly 5 arguments:
deploy.prototxt network.caffemodel mean.binaryproto labels.txt img.jpg
But after training lenet as example, I have only
lenet.prototxt and lenet_iter_10000.caffemodel
Where should I get mean.binaryproto labels.txt?
-13818541 0 Deleting a range from a table with merged cellsBasically, what I'm trying to accomplish is this: Delete all rows from a table starting from where the cursor is in the table to the end of the table.
The problem is that this table contains vertically merged cells, so when I try to do something like this:
For i = Selection.Tables(1).Rows.Count To Selection.Cells(1).RowIndex Step -1 Selection.Tables(1).Rows(i).Delete Next
It complains that individual rows cannot be accessed because the table contains vertically merged cells.
I've also tried selecting the range first, and then deleting the selection. But I couldn't get the range definition right; it always complained that there was an improperly defined parameter.
-32888565 0the api (or by url) does not support converting a csv into an existing spreadsheet.
you could instead convert into a new sheet and then use the spreadsheet api to copy the sheet data into your spreadsheet. you can also skip the csv upload step and directly parse and write to the existing sheet using that api.
-36519894 0This is probably slower than a Perl program (1 minute for 10.000 files) but it should work with any POSIX compliant shell.
#! /bin/sh nd=0 nf=0 /bin/ls | \ while read file; do case $(expr $nf % 10) in 0) nd=$(/usr/bin/expr $nd + 1) dir=$(printf "dir_%04d" $nd) mkdir $dir ;; esac mv "$file" "$dir/$file" nf=$(/usr/bin/expr $nf + 1)
done
With bash, you can use arithmetic expansion $((...)).
And of course this idea can be improved by using xargs - should not take longer than ~ 45 sec for 2.5 million files.
nd=0 ls | xargs -L 1000 echo | \ while read cmd; do nd=$((nd+1)) dir=$(printf "dir_%04d" $nd) mkdir $dir mv $cmd $dir done
-28623813 0 For a repeater field of act you have to use the field_key not the name. This was the answer to my question.
$startlocation = array(); $startlocation[] = array( 'lat' => $route['startingSpot']['location']['lat'], 'lng' => $route['startingSpot']['location']['lng'], 'description' => $route['startingSpot']['nl'], 'direction' => $route['startingSpot']['direction'] ); update_field('field_dhjawhdwkwkhd', $startlocation, $post_id );
-8611642 0 It's probably related to this bug: https://github.com/wayneeseguin/rvm/issues/560
What I've done (today) is get latest version of RVN to get it fixed:
rvm get latest rvm reload
-7530532 0 Sort product listings in Spree based on created_at I'm using spree and I want to sort product listing based on created_at
of the product.
I tried to find the way to override the spree default scope under lib/scopes/product.rb but couldn't find it.
I want to list recently created products on public panel. How can I do it with spree?
-24014184 0 How to check for text node of an element in xmltype oracleUsing the following query,
SELECT * FROM sampletable WHERE XMLExists('/books/book[@max="30"]' passing XMLCOLUMN);
But I want to know , how to check for the plain text content of an element, like
SELECT * FROM sampletable WHERE XMLExists('/books/book="Content"' passing XMLCOLUMN);
-21780036 0 I also got an exception saying "The invoked member is not supported in a dynamic assembly." and it caused me some headache to find its cause in my case.
The reason mentioned in @StuffHappens' answer held also for me: I also had checked the "Thrown"-box for "Common Language Runtime Exceptions" in the Debug->Exceptions dialog. But, I also had unchecked Tools->Options->Debugging->"Enable Just My Code (Managed Only)". In fact, I didn't expect such exceptions to show up during degugging when I did so.
In addition to the exception above, I also saw
I checked "Enable Just My Code (Managed Only)" box again and all the mysterious exceptions vanished!
I hope this may help someone to crawl out of this pitfall.
-17942164 0Suppose your dataObj
contains a unique ID field, then any set data structure would be fine for your job. The immutable data structures are primarily used for functional style code or persistency. If you don't need these two, you can use HashSet<T>
or SortedSet<T>
in the .Net collection library.
Some stream specific optimization may be useful, e.g., keeping a fixed-size Queue<T>
for the most recent data objects in the stream and store older objects in the more heavy weight set. I would suggest a benchmarking before switching to such hybrid data structure solutions.
Edit:
After reading your requirements more carefully, I found that what you want is a queue with user-accessible indexing or backward enumerator. Under this data structure, your feature extraction operations (e.g. average/sum, etc) cost O(n). If you want to do some of the operations in O(log n), you can use more advanced data structures, e.g. interval trees or skip lists. However, you will have to implement these data structures yourself as you need to store meta information in the tree nodes which are behind collection API.
-7963831 0With SizeAndTimeBasedFNATP and MaxHistory set to 10, the logs older than 10 days will be removed (assuming daily rollover schedule). Size is not factored in the into removal logic.
-3568806 0 File Locking vs. SemaphoresJust out of curiosity, what is the preferred way to achieve interprocess synchronization on Linux? The sem*(2)
family of system calls seem to have a very clunky and dated interface, while there are three ways to lock files - fcntl()
, flock()
and lockf()
.
What are the internal differences (if any) and how would you justify the usage of each?
-24713173 0"== false" is not very readable. Use ! instead.
If the "object value" is already of desired type (e.g. DateTime), it would be slower to convert it to string and then back again.
I would write instead
if (value is DateTime) return (DateTime)value;
I would not use var result = -999; as a return value.
If the conversion fails, you can either return Int32.MinValue (better than -999) or rather null.
Maybe also you would like to check for DBNull.Value? So first I would check for null and DBNull.Value, then "value is DateTime" check and the last thing would be DateTime.TryParse.
-27266391 0Try
else { if (convertView == null || getViewType(position) == 2)
-33645856 0 Instead of doing {{html_entity_decode($post->content)}}
, try this instead:
{!! $post->content !!}
More info here https://laravel-news.com/2014/09/laravel-5-0-blade-changes/
-29324924 0 Slider run in offline/localhost but not run in online/serverI write a JavaScript code for slider. This code run in localhost or offline. But it is not run in online or my server. I use this code. please help me. I try but not solve it. where is my wrong?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script type="text/javascript"> var imagecount=1; var total=5; function slide(x){ var Image = document.getElementById('img'); imagecount = imagecount + x; if(imagecount > total) { imagecount=1; } if (imagecount < 1) { imagecount = total; } Image.src = "img/image" + imagecount + ".jpg"; } window.setInterval(function slideA(){ var Image = document.getElementById('img'); imagecount = imagecount + 1; if(imagecount > total) { imagecount=1; } if (imagecount < 1) { imagecount = total; } Image.src = "img/image" + imagecount + ".jpg"; },5000); </script>
-38548316 0 how do i add a side bar and center page with out them merging with the nav bar I have tried adding a center page and side bars to my site but the only problem is the div tags merge and the backround color of the nav bar takes over the side bars even if the style code is separated heres an example
<!DOCTYPE html> <style> body {margin:0;} ul { list-style-type: none; margin: 0; padding: 0; overflow: hidden; border: solid; background-color: #000000; width: 100%; display:inline-block; } li { float: left; } .dropbtn { background-color: #0E8E0A; color: white; padding: 19px; font-size: 16px; border: none; overflow:hidden; cursor: pointer; } .dropbtnR { background-color: #15428A; color: white; padding: 19px; font-size: 16px; border: none; overflow:hidden; cursor: pointer; } .dropdown { display: inline-block; } .dropdown-content { display: none; position: absolute; background-color: #f9f9f9; min-width: 100px; box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); } .dropdown-content a { color: black; padding: 12px 16px; text-decoration: none; display: block; } .dropdown-content a:hover {background-color: #f1f1f1} .dropdown:hover .dropdown-content { display: block; } span { } </style> <!-- saved from url=(0039)http://www.theamannetwork.net/beta.html --> <html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <style> .float-left-area { width: 70%; float: left; } .float-right-area { width: 30%; float: left; } .inner-left { padding: 5px 5px 5px 5px; margin-right: 10px; border: #999999 1px solid; min-height: 60px; } .inner-right { font-size: 11px; padding: 5px 5px 5px 5px; border: #999999 1px solid; min-height: 60px; } .clear-floated { clear: both; height: 1px; font-size: 1px; line-height: 1px; padding: 0; margin: 0; } </style> < </head> <body> <ul> <br> <div class="dropdown" style="float:left;"> <button class="dropbtn">≡</button> <div class="dropdown-content" style="left:0;"> <a href="http://www.theamannetwork.net/beta.html#">the </a> <a href="http://www.theamannetwork.net/beta.html#">cake </a> <a href="http://www.theamannetwork.net/beta.html#">is a lie</a> </div> </div> </br> <div class="dropdown-content"> <a href="http://www.theamannetwork.net/beta.html#"><img src="./beta_files/Twitter.png"> </a> <a href="http://www.theamannetwork.net/beta.html#">random link </a> <a href="http://www.theamannetwork.net/beta.html#">SOMTHING IDK </a> </div> </div> <center><a class="navbar-brand" href="http://www.theamannetwork.net/beta.html#"><img src="./beta_files/banner.png" alt=""></a></center> <div class="float-left-area"> <div class="inner-left"> some random content </div> </div> <div class="float-right-area"> <div class="inner-right"> some random content </div> </div> <div class="clear-floated"></div> </ul></body></html>
how do I go about adding a center page and side bars with out merging
-11810972 0 Always get "Error validating verification code." when requesting access_tokenWell, I have done all my best to try to solve this problem, but, still, it's too annoying.
I decided to use OAuth with server-side authentication. So, I have followed Facebook documentation, and I have done the following step.
https://www.facebook.com/dialog/oauth?client_id={APP_ID}&redirect_uri=http://abc.com/nextStep.php
https://graph.facebook.com/oauth/access_token?code={CODE GENERATED BY FACEBOOK}&client_id={APP_ID}&redirect_uri=http://abc.com/thirdStep.php&client_secret={APP_SECRET}
The problem exists when proceeding to step 2. The page shows that:
{ "error": { "message": "Error validating verification code.", "type": "OAuthException", "code": 100 } }
I have googled for lots of time. Some people suggests to add a trailing slash in the redirect_uri, but it doesn't work. What should I do? And how can I get the user information after getting the access_token? Thanks for your help.
-20283130 0Use BackgroundWorker class to output progressBar and statusLabel changes:
BackgroundWorker bgw; private void btnScrape_Click(object sender, EventArgs e) { bgw = new BackgroundWorker(); bgw.WorkerReportsProgress = true; bgw.DoWork += new DoWorkEventHandler(bgw_DoWork); bgw.ProgressChanged += new ProgressChangedEventHandler(bgw_ProgressChanged); bgw.RunWorkerAsync(); } void bgw_DoWork(object sender, DoWorkEventArgs e) { for (int i = 1; i <= 100; i++) { Thread.Sleep(100); bgw.ReportProgress(i); } } private void bgw_ProgressChanged(object sender, ProgressChangedEventArgs e) { progressBar1.Value = e.ProgressPercentage; }
This is only an example how to update controls in an asynchron way.
-34086188 0 How to work with Decision Table with WSO2?I have to work on decision table using wso2 and my requirement is like that i should be able to modify the data dynamically in the decision table. is it possible to achieve this requirement using wso2 ?Please suggest me.
-28051711 0 How do I horizontally center this in Android (RelativeLayout)?I have the following code:
<TextView android:id="@+id/exercise_name_label" android:layout_width="match_parent" android:layout_height="32dp" android:text="Curls" android:gravity="bottom" android:layout_centerHorizontal="true" />
And I want the text to be aligned at the bottom of the 32dp and center horizontally..currently it's not centering horizontally:
I have a page, that lists a collection, that can be filtered. As there are some fancy effects (hover dimming) on these items, they have to be applied once the page has loaded.
This works fine, but when I select a criteria that hides an item, and then make it reappear by deleting that filter, these effects are no longer applied to these items.
I have tried to create a template.rendered
function, but that only works on the first page load.
I also thought that adding a 'hover #mydiv: function () {...}'
inside the template.events
section could help, but that still doesn't work.
I have even tried to listen to the changes made in the drop-down ('change #myselect': function () {...}
) where the filters can be applied, but that's not working either.
I also tried to tie it to a dependency, that is submitted when the criteria is selected, that has also failed.
Any suggestions what else should I try?
Thanks, Alex
Edit 1:
This is how I treat the filters:
in Template.search.events
:
'change #search-skills-select': function () { Session.set('searchFilter', $('#search-skills-select').val()); }
This then goes to:
/* This is of course properly handled for nulls, undefineds, etc. */ var searchFilterString = Session.get('searchFilter'); Profiles.find({profileAttributes: { $all: searchFilterString } });
-23426792 0 Add JS Script to this HTML I want to add this "TimeCircles JavaScript but, I can't do it correctly, I will add the files of it in the following location: /js/count-down/timecircles.css and /js/count-down/timecircles.js
The HTML file: https://www.dropbox.com/s/diho8tcumte5pqr/coming-soon.html
The JS link: http://git.wimbarelds.nl/TimeCircles/
-27054474 0The issue was resolved when the project was migrated onto another machine. Apparently the error had nothing to with incorrectness related to RMI. Although, the cause of the error and why it didn't resolve even after re-building the project is still unknown.
-4373454 0For this very reason it is recommend that you change your shebang line to be more path agnostic:
#!/usr/bin/env python
See this mailing list message for more information:
-3630828 0 Magento Module Upload Image in AdminConsider the possiblities that in a different machine, python may be installed at
/usr/bin/python
or/bin/python
in those cases,#!/usr/local/bin/python
will fail. For those cases, we get to call theenv
executable with argument which will determine the arguments path by searching in the$PATH
and use it correctly.(
env
is almost always located in/usr/bin/
so one need not worry thatenv
is not present at/usr/bin
.)
I'm developing a module with both a frontend and a backend. Until now everything has been ok, but now I want to upload images in the backend. I don't know how to start, and everything I've tried has just given me a headache.
Thanks
-9351599 0According to http://ruby.about.com/od/rubyfeatures/a/envvar.htm, you can just write:
ENV['SOME_VAR'] = 'some_value'
-28013340 0 Size UILabel in UIPickerView to fit I want to make the text size in the pickerView
to become smaller if the text does not fit in the label. For example, whenever the text shows like this "This is a test for somebo..." I want it to automatically size itself to a smaller size so it should fit. Here is the code I'm using:
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view { UILabel *lView = (UILabel *)view; if (!tView) { tView = [[UILabel alloc] init]; [tView setFont:[UIFont systemFontOfSize:15]]; tView.numberOfLines = [categorie count]; } tView.text = [categorie objectAtIndex:row]; return tView; }
I tried to set the number of lines to 0 but that didn't solve my issue. I then tried to make the label sizeToFit
, and that didn't work either.
I also tried making the label's frame height, taller, so it would be multiple lines, with didn't help either.
What did I get wrong?
-3658447 0 crawl a website for data at frequent intervalsI need to crawl a website and retrieve certain data that keeps getting updated every few minutes. How do i do this?
-34465507 0This is what I came up with. If you see any performance concerns, please let me know.
public class FilterByIntegerSetQuery extends Query { protected String numericDocValueFieldName; protected Set<Integer> allowedValues; public FilterByIntegerSetQuery(String numericDocValueFieldName, Set<Integer> allowedValues) { this.numericDocValueFieldName = numericDocValueFieldName; this.allowedValues = allowedValues; } @Override public Weight createWeight(IndexSearcher searcher, boolean needsScores) { return new RandomAccessWeight(this) { @Override protected Bits getMatchingDocs(LeafReaderContext context) throws IOException { final int len = context.reader().maxDoc(); final NumericDocValues values = context.reader().getNumericDocValues(numericDocValueFieldName); return new Bits() { @Override public boolean get(int index) { return allowedValues.contains((int) values.get(index)); } @Override public int length() { return len; } }; } }; } @Override public String toString(String field) { return "(filter "+numericDocValueFieldName+" by set)"; } }
-31465860 0 I think teamnorge is on the right track His code won't work as posted, though, since the array isn't mutable.
Make your property a mutable array. Have the base class create it it init's init method:
In your base class header:
@property (nonatomic, retain) NSMutableArray *ignoreProperties;
Then in the init for your base class:
-(instanceType) init; { self = [super init]; if (!self) return nil; self.ignoreProperties = [@[@"property1"] mutableCopy]; }
And in the init for your subclass:
-(instanceType) init; { self = [super init]; if (!self) return nil; [self.ignoreProperties addObject: @"property2"]; //or to add multiple objects... NSArray *newProperties = @[@"property2", @"property3"]; [self.ignoreProperties addObjectsFromArray: newProperties]; }
For efficiency's sake, it might be better to make the array immutable and have the subclass's init method replace it with a an array created using arrayByAddingObject
or arrayByAddingObjectsFromArray
. (Immutable objects are less costly for the system than their mutable forms. In this case the array of properties will only be created once at initialization of your class, and then persist for it's lifetime.)
It seems that there are multiple reasons for "domain = LaunchServicesError code = 0" error. I also encountered it, while I try to reinstall app on iOS8 simulator. I cannot reinstall but have to delete the old app first.
The problem was solved by:
In Xcode, fill empty Version or Build field with appropriate value in your Target->General->Identity
In Simulator, reset Content and settings...
After that, everything works fine.
-35263062 0setInterval(function(){ object.style.backgroundColor=bgcolorlist[Math.floor(Math.random()*bgcolorlist.length)]; },5000);
-16455630 0 Migrating application from SSCE to SSEI have a large project based on SQLServer-CE 3.5. Now I need to convert it to SQLServer. My questions are:
1) If I just change the connection strings in aap.config, will it work?
2) What about the datasets which have been made with SQLServer-CE database. Shall I need to change them too or app.config change will help there as well?
Thanks
-4795586 0 Determine Which JTable Cell is ClickedWhen a user clicks a cell on a JTable
, how do I figure out the row and column of the clicked cell? How would I show this information in a JLabel
?
My first met of RadioButtons was too not easy. But basically, it's simple to use it.
private RadioGroup mRadioGroup; private View radioButton; int radioButtonID; int idx; //index of radio item in the list public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mRadioGroup= (RadioGroup) findViewById(R.id.mRadioGroup); .... }
Put this part of code to any click event method, idx always will return an index of checked radio button:
radioButtonID = mRadioGroup.getCheckedRadioButtonId(); radioButton = mRadioGroup.findViewById(radioButtonID); idx = mRadioGroup.indexOfChild(radioButton);
If you want to catch radio button click event, here the good solution How to set On click listener on the Radio Button in android
-13897153 0Where you have:
<Directory /home/bitnami/public_html/http/flasktest1> WSGIProcessGroup flaskapp WSGIApplicationGroup %{GLOBAL} Order deny,allow Allow from all </Directory>
it should be:
<Directory /home/bitnami/public_html/http> WSGIProcessGroup flaskapp WSGIApplicationGroup %{GLOBAL} Order deny,allow Allow from all </Directory>
as you are neither running your app in daemon mode or in the main interpreter because of the directives being in the wrong context.
That Directory directive then conflicts with one for same directory above so merge them.
If using mod_wsgi 3.0 or later count instead perhaps drop that second Directory block and use:
WSGIDaemonProcess flaskapp threads=5 WSGIScriptAlias /flasktest1 /home/bitnami/public_html/wsgi/flasktest1.wsgi process-group=flaskapp application-group=%{GLOBAL}
Note that processes=1 has been dropped as that is the default and setting it implies other things you likely don't want. You also don't need to set user/group as it will automatically run as the Apache user anyway.
-35873843 0 When setting terminal attributes via tcsetattr(fd.....), can fd be either stdout or stdin?I have been looking int the man 3 tcgetattr (as I want to change the terminal settings in a program) and found this.
int tcgetattr(int fd, struct termios *termios_p); int tcsetattr(int fd, int optional_actions, const struct termios *termios_p);
I would like to know what fd
should mean? (it seems to be stdin
, yet I do not understand why)?
My comprehension is that terminal is input and output together, as my understanding was that a /dev/tty
or /dev/pty
yields stdin
, stdout
and stderr
together.
First of all don't add the validator (or anything else for that matter) into vendor namespaces. Instead put it somewhere within your application code. Don't know how your app is structured, but lets say ./module/YourModule/src/YourModule/Validator/ZendValidatePesel
.
Then reference your validator class with a full, qualified name, so following my guess it'd be something like:
'validators' => array( array( 'name' => 'YourModule\Validator\ZendValidatePesel', 'options' => array( // ... ), ),
As far as I know that will directly instantiate the validator for you. Not-so-fun-fact: even if you'd register your validator there under the same name as the fqcn, it won't go through the ValidatorPluginManager
-- something that I hope will be, or already is fixed in the framework (if it is somebody let me know, because it'd love to have validators with dependencies at last).
Well, first of all, you can never return an array. You have two options, the more commonly used option is to create the array in main, and pass a pointer to it as one of your arguments (generally "output" arguments are the last one, but this obviously doesn't matter), or your other option, is to create the array in your function (it has to be static
otherwise it will go out of scope once the function returns), and return a pointer to the array. Considering that this 'static' method isn't recommended, your second option could instead be malloc()
ing space for the array in your function, and returning the pointer to that (don't forget to free()
in main!).
The video that @OleksandrKravchuk links to returns a pointer to a local variable, this is a bad idea (you can use the static
trickery, but this is not a perfect solution either. 99% of time having it in as an argument is the way to do this). To be clear, there is NO WAY to return an array (by value, anyways). Don't let his answer confuse you.
I need help understanding this piece of code. What is the point of handler.guid
? Why is there a need for a hash table?
What is the point of:
if ( element["on" + type]) { handlers[0] = element["on" + type]; }
What does the "this" refer to in handleEvent
, the element or the the addEvent function?
function addEvent(element, type, handler) { // assign each event handler a unique ID if (!handler.$$guid) handler.$$guid = addEvent.guid++; // create a hash table of event types for the element if (!element.events) element.events = {}; // create a hash table of event handlers for each element/event pair var handlers = element.events[type]; if (!handlers) { handlers = element.events[type] = {}; // store the existing event handler (if there is one) if (element["on" + type]) { handlers[0] = element["on" + type]; } } // store the event handler in the hash table handlers[handler.$$guid] = handler; // assign a global event handler to do all the work element["on" + type] = handleEvent; } // a counter used to create unique IDs addEvent.guid = 1; function removeEvent(element, type, handler) { // delete the event handler from the hash table if (element.events && element.events[type]) { delete element.events[type][handler.$$guid]; } } function handleEvent(event) { // grab the event object (IE uses a global event object) event = event || window.event; // get a reference to the hash table of event handlers var handlers = this.events[event.type]; // execute each event handler for (var i in handlers) { this.$$handleEvent = handlers[i]; this.$$handleEvent(event); } }
-37130139 0 A lot of misconception here.
blob
is not a Blob, but a string, the url of .file-preview-image
.onload
callback of the FileReader, you are just checking if the result is equal to an undefined variable dataURI
. That won't do anything. console.log
the call to readAsDataURL
which will be undefined
since this method is asynchronous (you have to call console.log
in the callback). But since I guess that what you have is an object url (blob://
), then your solution is either to get the real Blob object and pass it to a FileReader
, or to draw this image on a canvas, and then call its toDataURL
method to get a base64 encoded version.
If you can get the blob :
var dataURI; var reader = new FileReader(); reader.onload = function(){ // here you'll call what to do with the base64 string result dataURI = this.result; console.log(dataURI); }; reader.readAsDataURL(blob);
otherwise :
var dataURI; var img = document.querySelector(".file-preview-image"); var canvas = document.createElement('canvas'); canvas.width = img.width; canvas.height = img.height; canvas.getContext('2d').drawImage(img, 0,0); dataURI = canvas.toDataURL();
But note that for the later, you'll have to wait that your image actually has loaded before being able to draw it on the canvas.
Also, by default, it will convert your image to a png version. You can also pass image/jpeg
as the first parameter of toDataURL('image/jpeg')
if the original image is in JPEG format.
If the image is an svg, then there would be an other solution using the <object>
element, but except if you really need it, I'll leave it for an other answer.
The way ng-minlength and ng-maxlength work, if the input textbox has fewer or more characters than specified by the two directives, then user.name is not populated (I don't even think it is defined). To see what I mean, add {{user.name}}
after the <span>.
You need to increment your compteur
variable (I'm assuming that you have it for this purpose) and check it's value on every submission. Something like this:
var resultat = Math.floor(Math.random() * 100) + 1; var compteur = 1; $('div').html("( answer is : " + resultat + " )"); $('form').on('submit', function(e) { e.preventDefault(); if (compteur < 8) { var inputVal = $('#number').val(); var nbInput = Number(inputVal); compteur++; if (nbInput !== resultat) { if (nbInput < resultat) { $('h2').html(inputVal + ' is too small'); } else { $('h2').html(inputVal + ' is too big'); }; } else { $('h2').html('Yes! ' + inputVal + ' is the right number'); }; } else $('h2').html('You reached the limit of 7 guesses.'); });
I've updated your fiddle so you can see it.
-10604065 0 How do you replace multiple instances of '+' in a string in JavaScript?I have a URL that I need to manipulate. I cant seem to replace all the '+' within a query string with whitespace.
var url = window.location.replace(/+/g, ' ');
What am I doing wrong here?
Or is there a better method?
-36454005 0 Spring-boot app built jar results in: Could not generate DH keypairMaven Spring MVC app with spring-boot and built in jetty server has the following error when ran after built to jar:
java -jar app.jar
org.springframework.ws.client.WebServiceIOException: I/O error: java.lang.RuntimeException: Could not generate DH keypair
java version 1.8.0_77
Anybody any ideas?
You probably want to redirect your System.out to another place.
If you want to work with Swing then you can look here
Then it's the duty of the other place where you redirect it.
But right now it's only a thing of your IDE (Eclipse). It is independent from your Java logic.
If your think serious about it. You don't want to play your text adventure in your Eclipse IDE. So if you are using Windows the next question is if you want to use the Window command line. This may already be enough for you. But I still would recommend to make first thoughts about in which kind of window you want to have your text output
-36787686 0No, you can not calculate the furthest point for each point in O(n)
. The best you can obtain is O(n log n)
with a 2-d tree. You can do this with a technique, similar to finding a closest point.
Read a more detailed answer here where I show a couple of other approaches to solve a similar problem.
-36394230 0 Defining Foreign Key in Unary RelationshipI have the table assignment which should have two FK - ManagerID & ManagerProjID
CREATE TABLE Assignment ( RescID NUMBER (8) NOT NULL , RProjID NUMBER (4) NOT NULL , AssignRole VARCHAR2(100) , ManagerID NUMBER (8) , ManagerProjID NUMBER (4), CONSTRAINT Assignment_PK PRIMARY KEY ( RescID, RProjID) ) ;
When I try running the command
ALTER TABLE Assignment ADD CONSTRAINT Assignment_Manager_FK FOREIGN KEY ( MANAGERID ) REFERENCES Assignment ( MANAGERID ) ;
I am getting an error of no matching unique or primary key for this column-list.
-5058999 0 Single Window WPF ApplicationI've created a single window application and this application has 2 screens all shown in the main window. Logon screen and then the main application screen after successful logon. I've currently achieved this by using a navigation window and pages.
I'm not sure if this is the best approach as I do not need to use the functionality provided by the navigation window (Browse back and forward et cetera).
I'm hoping someone could let me know if the navigation window is the best approach for this design or if a similar look can be achieved by not using pages and navigationwindow.
Thanks for all your help.
Emlyn
-7995584 0 Can I 'match' values in 2 arrays and then use the subsequent 'matched' value?I'm trying to achieve the following though with my intermediate JavaScript skills I'm not sure if this is possible.
This is related in part to this question.
Now I have 2 arrays
a) Has the various language in (e.g. "en-GB", "fr", "de" etc)
b) Has a suffix of a URL based on the browser language above (e.g. "fr/","de/","uk/")
What I am trying to achieve is:
1) User hits a page, browser detects which browser it is using from the array (a)
2) Depending on what the browser is based on (a), it then searches through (b) and if they match, e.g. if the language is "fr" it will use the suffix "fr/" from the array in (b).
3) It will then add this suffix to a top level domain (which is always constant)
Is this even possible to achieve (I'm sure it is)? Can it be done purely via JavaScript (or JQuery)? How would I go about doing this?
Here's some of the code I have so far:
var IAB_Array = new Array("de-at","nl-be","fr-be","da","de","hu","en-ie","ga","es","fr","it","nl","no","pl","en","en-GB","en-US","en-gb","en-us"); //language array var IAB_suffix = new Array("at/","be-nl/","be-fr","den/","de/","hu/","ie/","es/","fr/","it/","nl/","nor/","pl/","uk/"); //URL suffix Array var IAB_lang = "en-GB"; //default language var IAB_link = "http://www.mysitegoeshere/"; if(navigator.browserLanguage) IAB_lang = navigator.browserLanguage; //change lang if detection supported if(window.navigator.language) IAB_lang = window.navigator.language; //change lang if detection supported function IAB_Lang_detect () { //execute search for (var i=0;i<IAB_Array.length;i++) { if(IAB_Array[i]==IAB_lang) { document.write(IAB_Array[i]); //output matched array value } } return false; } var IAB_URL = "<a href="+IAB_link+IAB_suffix[1]+">"+IAB_link+IAB_suffix[1]+"</a>"; //this is the resulting URL document.write(IAB_URL); IAB_Lang_detect ();
I hope someone can help as I'm a little confused! It's more so the matching the values from the 2 arrays and then subsequently selecting the correct suffix that I'm having trouble with.
Thanks
-34952446 0It seems you can't but they have java api to communicate through there aadhar uidai db.Please follow the link to more details https://developer.uidai.gov.in/site/book/export/html/18
-33067130 0Just change the line-height: 3px;
to line-height:22.5px;
See also the jsfiddle example.
-21059701 0Not sure how your $.each()
doesn't work, but this will work fine.
$.each(json, function(i,obj){ console.log(obj); });
Where obj will be:
{"name":"2323dffd","type":"jpg","caption":"ddd"}
And you can do
console.log(obj.name);
and so on.
Further, here's a jsFiddle illustrating your JSON iteration.
-8006068 0There are several reasons why returning references (or pointers) to the internals of a class are bad. Starting with (what I consider to be) the most important:
Encapsulation is breached: you leak an implementation detail, which means that you can no longer alter your class internals as you wish. If you decided not to store first_
for example, but to compute it on the fly, how would you return a reference to it ? You cannot, thus you're stuck.
Invariant are no longer sustainable (in case of non-const reference): anybody may access and modify the attribute referred to at will, thus you cannot "monitor" its changes. It means that you cannot maintain an invariant of which this attribute is part. Essentially, your class is turning into a blob.
Lifetime issues spring up: it's easy to keep a reference or pointer to the attribute after the original object they belong to ceased to exist. This is of course undefined behavior. Most compilers will attempt to warn about keeping references to objects on the stack, for example, but I know of no compiler that managed to produce such warnings for references returned by functions or methods: you're on your own.
As such, it is usually better not to give away references or pointers to attributes. Not even const ones!
For small values, it is generally sufficient to pass them by copy (both in
and out
), especially now with move semantics (on the way in).
For larger values, it really depends on the situation, sometimes a Proxy might alleviate your troubles.
Finally, note that for some classes, having public members is not so bad. What would be the point of encapsulating the members of a pair
? When you find yourself writing a class that is no more than a collection of attributes (no invariant whatsoever), then instead of getting all OO on us and writing a getter/setter pair for each of them, consider making them public instead.
Basically, your regular expression is recursive. Removing the final .+
solves the issue. Here is a good article on avoiding it in the future. Why does .NET hang? Probably because it will never abort the search. Perhaps the JavaScript parser you used aborts if it detects too many steps or goes too deep into recursive searches.
As mentioned by user2394787:
Select your view controller that has the scrollview then go to
Editor -> Resolve AutoLayout Issues -> Add Missing Contraints in [your view controller].
This will make it work.
I tried to vote up the above answer but do not have enough rep.
-33508017 0See the first input field for full width:
<form method="post" class="mobile-login-form _5spm" id="u_0_0" novalidate="1" data-autoid="autoid_1"><input name="lsd" value="AVpe_Wp1" autocomplete="off" type="hidden"><input name="charset_test" value="€,´,€,´,水,Д,Є" type="hidden"><input name="version" value="1" type="hidden"><input id="ajax" name="ajax" value="0" type="hidden"><input id="width" name="width" value="0" type="hidden"><input id="pxr" name="pxr" value="0" type="hidden"><input id="gps" name="gps" value="0" type="hidden"><input id="dimensions" name="dimensions" value="0" type="hidden"><input name="m_ts" value="1421117640" type="hidden"><input name="li" value="yIi0VOqdqMbfGzXVr-lypMC-" type="hidden"><div class="_56be _5sob"><div class="_55wo _55x2 _56bf"><input style="width: 100%;" autocorrect="off" autocapitalize="off" class="_56bg _55ws _5ruq" name="email" placeholder="Email Address" type="email"><p><input autocorrect="off" autocapitalize="off" class="_56bg _55ws _5ruq" placeholder="Password" name="pass" id="password" type="password"></p><div class="_55ws"><button type="submit" value="Submit" class="_56bs _56b_ _56bw _56bu" name="login" id="u_0_1" data-sigil="touchable"><span class="_55sr">Submit</span></button></div></div></div><noscript><input type="hidden" name="_fb_noscript" value="true" /></noscript></form>
It's this line:
<input style="width: 100%;" autocorrect="off" autocapitalize="off" class="_56bg _55ws _5ruq" name="email" placeholder="Email Address" type="email">
-19360349 0 you could try wrapping your message in a <pre>...</pre>
tag, so linebreaks get rendered by the browser :-)
That is very strange my opinion to you.
First go to Build(top on the android studio)-> Clean project -> Build APK -> Generate signed APK.
If this will not help you than go to. app\build\outputs\apk and delete your apk. and again build signed APK.
-9767753 0 Insert multiple rows into table from a variable in PHP for Mysql & Oracle tablesI am fetching data from some tables & storing it in a variable like below-:
$result = mysql_query("SELECT * FROM sample where column=mysql_insert_id()"); while($row=mysql_fetch_array($result)) { $str = "'". $row["name"] . "',". "'" . $row[quantity] . "'," . "'" . $row["id"]; }
So in my variable $str
, suppose I have following values-:
shirt,10,1,pant,50,2....i.e. it will store values in a comma separated format.
Now I want to insert these values in another table say test-:
$qry = "INSERT INTO test(name,quantity,id)values(".$str.");
Now I want to store values in test table in two rows like-:
shirt 10 1 pant 50 2
So how to do the same for Mysql & Oracle tables?
Plz help
See my below query-:
$query2 = "SELECT sfoi.name, sfoi.sku, sfoi.qty_ordered, sfoi.price, sfoi.row_total, sfo.base_subtotal, sfo.base_shipping_amount, sfo.base_grand_total, (select mso.order_primary from mysql_sales_order mso where mso.increment_id =sfo.increment_id) FROM sales_flat_order sfo JOIN sales_flat_order_item sfoi ON sfoi.order_id = sfo.entity_id WHERE sfo.increment_id = ". $order_id ; $result_query2 = mysql_query($query2);
So for one order id i.e. for one order may contain more than 1 products i.e. many name,sku,quantity ordered etc. So at the time of mysql_fetch_array(), I want all product data in a single variable...my code for fetching is like this-:
while($row = mysql_fetch_array($result_query2)) { $string = "'". $row["name"] . "',". "'" . $row["sku"] . "'," . "'" . $row["qty_ordered"] . "',". "'" . $row["price"] . "'," . "'" . $row["row_total"] . "'," . "'" . $row["base_subtotal"]. "'," . "'" . $row["base_shipping_amount"] . "'," . "'" . $row["base_grand_total"] ."'," . $row["prod_foreign"]; $query3 = "INSERT into mysql_sales_product(name, sku, qty_ordered, price, row_total, base_subtotal,base_shipping_amount,base_grand_total,prod_foreign) VALUES(".$string.")"; } $result_query_product_outbound = mysql_query($query3);
Here I want to store result of mysql_ fetch_array in variable in such a way that if there are multiple rows I can still able to pass those rows using variable$string. e.g-:
name sku qty_ordered price row_total subtotal shipping_amnt grand_total prod_foreign nokia nk 2 500 1000 1000 300 1300 11 sansung sam 3 400 1200 1200 500 1700 30 sony sny 4 200 800 800 200 1000 45
-10759259 0 story.fans
is an array of objectids. objectids do cannot have ratings. You need to add the rating to the Person schema instead of the story schema.
var PersonSchema = new Schema({ name : String , age : Number , rating: Number , stories : [{ type: Schema.ObjectId, ref: 'Story' }] });
-39398118 0 I'm trying to add input text into a list but doesn't work So I'm trying to put input text into a list but doesn't work. And empty list option doesn't work either. Here is my code:
Here is the task I was given: Create a " numeric keypad " by putting out 10 buttons with text 0,1,2,3 etc . Make as a text field where you can enter numbers as 3604 by pressing the buttons. Every time you press a button , should therefore number that is on the button is added to the text box.
Somehow it doesn't let me add the numbers to another list and it won't empty the list either.
-12926976 0 Display the title and year for all of the films that were produced in the same year as any of the SH and CH filmsDisplay the title and year for all of the films that were produced in the same year as any of the SH and CH films.
how would I bring up a result table showing the titles of the movies that were also made in same years as the movies from genre column?
table name (movies) year column (YR) genre column (genre) genre (SH) (CH) i really don't know how i would put this all together any help would be appreciated.
-32045365 0 Can't find the maven repository for xwiki xmlrpcI want to include this library:
import org.xwiki.xmlrpc.XWikiXmlRpcClient;
so I am using this maven snippet to include it:
<dependency> <groupId>org.xwiki.platform</groupId> <artifactId>xwiki-core-xmlrpc-client </artifactId> <version>2.1.1</version> </dependency>
I can't find the library anywhere though. We use Artifactory which queries the main maven repo for unresolved dependencies. I can find the jar online, but I need a maven repository to include it in the build process.
Do I need to add a special repo or something?
-37916357 0 Cannot find symbol clone() in interface CloneableI am trying to clone a list of Cloneables:
public static <T extends Cloneable> List<T> cloneList(List<T> list) { List<T> out = new ArrayList<T>(); for(int i=0;i<list.size();i++) { out.add((T)((T)list.get(i)).clone()); } return out; }
which throws the error:
Helpers.java:40: error: cannot find symbol out.add((T)((T)list.get(i)).clone()); ^ symbol: method clone() location: interface Cloneable
Why is that; isn't clone()
the single method the Cloneable
interface is all about?
var util = require("util"), http = require("http"); var options = { host: "www.google.com", port: 80, path: "/" }; var content = ""; var req = http.request(options, function(res) { res.setEncoding("utf8"); res.on("data", function (chunk) { content += chunk; }); res.on("end", function () { util.log(content); }); }); req.end();
-39478505 0 How to count multiple lines from git log in PowerShell? PROBLEM
git log --pretty=oneline $branch...$version
Allows me to determine how many commits are between the specified branch and tag. Each commit is printed to the console window on a different line, and starts with 40 characters of that commit's SHA and is followed by a brief description.
Using PowerShell, I would like to take the count of all these commits and assign it to a variable. I don't want to output this data to a file.
My assumption is that a large regex would be the best option, but I'm thinking that there must be an easier solution.
QUESTION
Is there an easier way to find the count of multiple lines outputted to the console?
Also, is there a way to get around the buffer size when handling the log data without adjusting the buffer-size of the console window? Or is this a factor I will need to worry about at all? (when handling a large amount of commits)
-22744791 0if you do not set a stroke-width
, defaut value is 1 for 1 pixel:
Try this :
<svg height="30px"><text x="0" y="20" stroke-width="0" stroke="#000000">bla - svg stroke width 0</text></svg> <svg height="30px"><text x="0" y="20" stroke="#000000">bla - svg stroke no width defined</text></svg> <svg height="30px"><text x="0" y="20" stroke-width="1" stroke="#000000">bla - svg stroke width 1</text></svg> <svg height="30px"><text x="0" y="20" stroke-width="2" stroke="#000000">bla - svg stroke width 2</text></svg>
text-stroke
is actually avalaible in webkit , using vendor prefix. So is text-fill
.
In near futur it could be avalaible in other browser too , check it out here : http://caniuse.com/text-stroke
To stroke text in CSS, you need to use multiple text-shadow to increase as much as needed the shadow to turn it into a full strike color .
http://codepen.io/anon/pen/xklIi/
(as bigger is the shadow used for stroke effect, as much it needs to be repeated, redrawn)
/* using CSS3 selector filters older browser, you can reset freely letter-spacing here */ [data-stroke="1"] {/* class can be used */ text-shadow: 0 0 1px red, 0 0 1px red, 0 0 1px red, 0 0 1px red, 0 0 1px red, 0 0 1px red, 0 0 1px red, 0 0 1px red, 0 0 1px red; } [data-stroke="2"] { letter-spacing:2px /* you might need to reset letter-spacing to keep text readable */ text-shadow:/* repeat until sharp enouggh */ 0 0 2px red, 0 0 2px red, 0 0 2px red, 0 0 2px red, 0 0 2px red, 0 0 2px red, 0 0 2px red, 0 0 2px red, 0 0 2px red, 0 0 2px red; }
HTML
<p data-stroke="1">bla - text stroke width 1</p> <p data-stroke="2">bla - text stroke width 2</p> <p data-stroke="2sharp">bla - text stroke sharp width 2</p>
-21598444 0 Unity. Function call after a certain period of time How can I make an object invisible (or just delete) after a certain period of time? Use NGUI.
My example (for changes):
public class scriptFlashingPressStart : MonoBehaviour { public GameObject off_Logo; public float dead_logo = 1.5f; void OffLogo() { off_Logo.SetActive(false); } //function onclick button //remove item after a certain time after pressing ??? void press_start() { InvokeRepeating("OffLogo", dead_logo , ...); } }
-4741881 0 OpenGL: how to use buffer_objects to draw In page 103 of OpenGL redbook, they give an example (example 2-17) about how to use buffer_object to draw something.
#define BUFFER_OFFSET(bytes) ((GLubyte*) NULL + (bytes)) GLuint buffers[NUM_BUFFERS]; GLfloat vertices[][3] = { { -1.0, -1.0, -1.0 }, { 1.0, -1.0, -1.0 }, { 1.0, 1.0, -1.0 }, { -1.0, 1.0, -1.0 }, { -1.0, -1.0, 1.0 }, { 1.0, -1.0, 1.0 }, { 1.0, 1.0, 1.0 }, { -1.0, 1.0, 1.0 } }; GLubyte indices[][4] = { { 0, 1, 2, 3 }, { 4, 7, 6, 5 }, { 0, 4, 5, 1 }, { 3, 2, 6, 7 }, { 0, 3, 7, 4 }, { 1, 5, 6, 2 } }; glGenBuffers(NUM_BUFFERS, buffers); //Generate NUM_BUFFERS of buffers and put them in buffers array. glBindBuffer(GL_ARRAY_BUFFER, buffers[VERTICES]); //bind buffers glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); //allocate space for buffers glVertexPointer(3, GL_FLOAT, 0, BUFFER_OFFSET(0));
Here, we suppose to have a point to a array to specify in which array we will find the data. Then is that should be a pointer to some memory address in server?
I just do not understand that BUFFER_OFFSET(0).
Does that mean that there is always only one Vertex_Array in server and the program will choose that address automatically? The BUFFER_OFFSET(0) just tell you where to start in this array?????????
glEnableClientState(GL_VERTEX_ARRAY); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffers[INDICES]); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); glDrawElements(GL_QUADS, 24, GL_UNSIGNED_BYTE, BUFFER_OFFSET(0));
Same thing here. We suppose to give a address at the last parameter. But I do not see that BUFFER_OFFSET(0) is a useful address.
-33406300 0Yes - you can do that using Geneos commands. For you reference I have added a sample screenshot of how your command will look like in Geneos Gateway Editor. Notice that it is set to run on Netprobe and the checkbox Enable password is checked. This means when you run this command from inside the Geneos Active Console it will ask for a password. Since this command is set to run on Netprobe, you need to define the password on probe. This is under the Advanced Section of Probe. See the below screenshot:
on the first how did you run your App? I noticed that when i run an App in Debugmode, the Debugger eats 50% of the performance of my mobile Device. So if you just run your App the onFinish works much faster.
A second point is to detect the timeout manually in the onTick Method an block the taps after some time with a boolean
private boolean tapBlock = false; private void beginTimer() { new CountDownTimer(10100, 1000) { public void onTick(long millisUntilFinished) { if (!tapBlock) { time.setText("Time: "+millisUntilFinished/1000); if (millisUntilFinished<100) { tapBlock = true; } } } public void onFinish() { time.setText("Timeout!!!"); finalTap++; tapBlock = false; } }.start(); }
This is a bit around but its maybe faster and you have to add the "tapBlock" to the update method
-36268856 0 multiple gridviews in a single Activity/fragmentI would like to have two or more gridviews on a single activity/fragment so for instance, i have a textview and a gridview, so when i click on a button in this activity the current gridview disappears and replaces it with new gridview, however i want the textview to stay there and not loose the text inside the textview.
-25882874 0It can happen, that the string has nothing inside, than it is "None" type, so what I can suppose is to check first if your string is not "None"
# Extracting the sites def CiteParser(content): soup = BeautifulSoup(content) #print soup print "---> site #: ",len(soup('cite')) result = [] for cite in soup.find_all('cite'): if cite.string is not None: result.append(cite.string.split('/')) print cite return result
-7432259 0 VBA Excel VerticalAlignment = xlCenter not working The below code selects the sheet but fails to align the cells to center.
wb.Sheets(1).Columns("A:L").Select With Selection .VerticalAlignment = xlCenter End With
Thanks!
wb.Sheets(1).Activate wb.Sheets(1).Columns("A:L").Select With Selection .VerticalAlignment = xlCenter End With
Selects the entire sheet but it's not changing the vertical alignment to center.
wb.Sheets(1).Columns("A:L").VerticalAlignment = xlCenter
Does nothing.
I don't want HorizontalAlignment :)
I found out the column has VerticalAlignment set to xlCenter but the Cells underneath the column do not have VerticalAlignment set to xlCenter.
-35905803 0 Gradle: interchangeably use AAR or project dependencyI have an AAR library that I want to distribute to partners along with a sample project that uses it. I want to also use the same sample project for manual testing while developing the AAR library. Thus, I would like to be able to use the library project as a dependency when developing, and the AAR file as a dependency when distributing.
I tried to define two flavors in the sample application:
productFlavors { aar {} project {} }
...and then define dependencies like this:
dependencies { //other dependencies projectCompile project(':myLibrary') aarCompile 'com.example.mylibrary:myLibrary-release@aar' }
The aar
flavor builds if I comment out the dependency for the project
flavor, but if I leave both uncommented, Gradle sync fails if the myLibrary directory is not present - despite the fact that the project
build flavor is not part of the current build variant.
What is the correct way to do this? Or do I have to choose between creating a whole separate project for distribution or always referencing the AAR even when debugging/testing?
-2459230 0the solution was in the -validateMenuItem code... I wasnt checking for a return value of null somewhere that method and it was logically returning false.
-31573333 0 IntelliJ 14 Unable to generate JavaFX exeI am trying to package an app to an exe file, (including java8, so it is self contained). The app needs to run on any machine even if java is not installed.
Here is a screenshot of my settings:
I get this as an error:
Error:Java FX Packager: BUILD FAILED /home/foo/.IntelliJIdea14/system/compile-server/_temp_/build0.xml:11: Total time: 0 seconds Error:Java FX Packager: Buildfile: /home/foo/.IntelliJIdea14/system/compile-server/_temp_/build0.xml build artifact: Error:Java FX Packager: fx:deploy task has failed.
Now what am I supposed to get from this error ?
How can I fix this and get my app executable?
-20216486 0 Using import java.util.Random; nextInt and user inputI am fairly new to java so this will probably seem like a basic question. I am trying to use the random java.util and nextInt to create a random number in a range specified by user input and then cast it as a character, to then be stored in an array;
gridCells[x][y] = (char)(r.nextInt(numberOfRegions) + 'a');
However, because I want nextInt to use user Input, and although im controlling the range of values, im guessing the error is caused because nextInt thinks numberOfRegions could be 0?
// Map Class import java.util.Random; public class map { // number of grid regions private int numberOfRegions; private boolean correctRegions = false // grid constants private int xCord = 13; // 13 so the -1 makes 12 for a 12x12 grid private int yCord = 13; // initiate grid private int[][] gridCells = new int[xCord][yCord]; Random r = new Random(); map() { } // ask for number of regions public void regions() { keyboard qwerty = new keyboard(); // keyboard class while(correctRegions = false) { System.out.print("Please enter the number of regions: "); numberOfRegions = qwerty.readInt(); if(numberOfRegions < 2) // nothing less then 2 accepted { correctRegions = false; } else if(numberOfRegions > 4) // nothing greater then 4 accepted { correctRegions = false; } else { correctRegions = true; } } } // fills the grid with regions public void populateGrid() { for(int x =0; x<gridCells[x].length-1; x++) // -1 to avoid outofboundsexception error { for(int y =0; y<gridCells[y].length-1; y++) { gridCells[x][y] = (char)(r.nextInt(numberOfRegions) + 'a'); } } } public void showGrid() { for(int x=0;x<gridCells[x].length-1; x++) { for(int y=0; y<gridCells[x].length-1; y++) { System.out.print(gridCells[x][y] + " "); } System.out.println(); } } }
-25896054 0 Well I Was really being Dumb!! I Just Fixed it up :P Thnx For The Help everyone :)
string='xyz' x='' for lel in string: x+=lel print x
-29864018 0 The bandwidth requirements are almost the same as the bandwidth requirement for opus and vp8. Real time audio typically has a bitrate of 40-200kbit/s. Video requires at least 200 kbit/s (500kbit/s if you want to see people's faces).
According to webrtc-experiment the minimum bandwidth for opus is 6kbit/s and for vp8 100kbits/s. So in total that makes 106kbit/s but when you account for the overhead of the webrtc protocol stack and constantly varying network conditions I would guess that 200kbit/s is the minimum if one wants stable video and audio.
Chrome and Firefox both use opus and vp8 so the bandwidth requirements should be the same. Although I don't have any hard data to prove it.
You can see the current traffic generated by webrtc by going to chrome://webrtc-internals and inspecting all the charts.
-12687953 0 Call java method from log4j.xml fileI have to populate level value dynamically in log4j.xml. Is it possible to set this value by calling a java method?
-984670 0 What is the difference between WCF and the RIA Services Domain Service Class?I'm just introducing myself to the basic differences between Silverlight 3 and it's predecessor. Looking at Domain Service Class within RIA services, the execution seems quite a bit simplified. Can someone explain the basic differences between this and Windows Communication Foundation?
Does the Domain Service Class employ WCF or some other services framework in the background, or is this new from the ground up?
-18601402 0I suppose you need an ANE - unless Adobe extends flash.notifications one day to support Android too.
-9769157 0 What happens after Form.Close?I have a code like
void onDgvRelations_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e) { if (e.ColumnIndex == 2 && ktlg == null) { this.Cursor = Cursors.WaitCursor; ktlg = new FormKatalog(); ktlg.Show(); this.Cursor = Cursors.Default; } }
The idea is to check if a form
FormKatalog ktlg
is closed. If it's closed I have to create a new form and show it to user. The problem is that after user close the form, variable ktlg will never be null.
How to check properly if a form was not instantiated OR was closed by user?
-30807138 0The answer is in apple SCNNode documentation. Try using flattenedClone()
method instead of clone()
. And one more thing, it's not needed any for statement. Here is a little example in Swift:
nodeB = nodeA.flattenedClone()
Now, nodeB contains all children nodes of nodeA
-20924156 0The behaviour of this operator is different across various versions of Ruby. You're probably using an older one, in which case this is to be expected.
Here's an excerpt from the docs for Ruby 1.8.7's String class
If passed a single Fixnum, returns the code of the character at that position.
This has been changed and the newer versions of Ruby (1.9.x and above, according to this site ) simply print the character as a String. See the docs for Ruby 2.1.0.
If passed a single index, returns a substring of one character at that index.
Ruby 1.9.3, which I happen to have installed on the machine I'm using displays exactly the same behavior:
"Mwada"[0] => "M" "Mwada"[0].class => String
-6407526 0 The problem is that the EditField will still try to use all of the width, which causes the VerticalFieldManager to also use the entire width available to it, effectively shoving off the password field.
The only way I know of to do something like this would be to create classes that explicitly set their width to 50% of the screen. There are two ways of doing this: either create subclasses of EditField and PasswordEditField, or create a subclass of HorizontalFieldManager. The former option will be easier and more reliable across the different platforms, but will require two classes instead of one.
To do this, you'll want to create a subclass of EditField and override its layout
method to look something like:
protected void layout(int maxWidth, int maxHeight) { super.layout(maxWidth, maxHeight); this.setExtent(Display.getWidth()/2, this.getHeight()); }
Similarly for the PasswordEditField.
Depending on how you want it to behave, you might have to override other methods as well. For instance, this code will (I'm pretty certain, haven't tested it specifically) cause any extra characters to be truncated if they dont fit in the desired area. If that's not what you want, you might have to override paint
or change the layout based on the current text. Also, you should test it when tilting the storm screen to ensure the size updates correctly - it should work in most cases, but there is a bug that causes it to not update layouts/sizes if you have certain configurations of managers on the screen.
If you decide to go the manager route (which, again, I don't especially recommend, as you'll probably run into many more issues), you'll want to extend either Manager or HorizontalFieldManager (might be easier to do the former, so you don't have to deal with some of the quirks of the HFM), and override its sublayout
method. In this method, you'll want to call layoutChild
and setPositionChild
(in that order) for every field in the manager (in your case, the user field and the password field). Then, at the end, you'll want to call setExtent
. I would refer you to the blackberry docs on this matter, but in all honesty you're better off searching for how to implement blackberry custom managers, or asking questions on SO.
All that said, you might also want to reconsider why you want to do this. I can guarantee you from experience that there will be some phones where the UI does not look right - we tried a similar approach once, and eventually scrapped it because we couldn't get it to work from a UI standpoint on all devices. There are lots of different resolutions - some very narrow, some very wide - and if you go with this UI then some devices will have very cramped logins. IMHO, it would be preferable to be consistent with the other BlackBerry applications, and have username and password on different lines.
-892409 0You can read a reasonable answer from this implementation found in some webpage
Point * intersection2(Point * _line1, Point * _line2) { Point p1,p2,p3,p4; p1=_line1[0]; p3=_line2[0]; p2=_line1[1]; p4=_line2[1]; // Store the values for fast access and easy // equations-to-code conversion double x1 = p1.x, x2 = p2.x, x3 = p3.x, x4 = p4.x; double y1 = p1.y, y2 = p2.y, y3 = p3.y, y4 = p4.y; double A1 = y2-y1; double B1 = x1-x2; double C1 = (A1*x1)+(B1*y1); double A2 = y4-y3; double B2 = x3-x4; double C2 = A2*x3+B2*y3; double det = A1*B2 - A2*B1; if (det==0){ return NULL; }else{ // Return the point of intersection Point * ret = new CvPoint2D64f (); ret->x = (B2*C1 - B1*C2)/det; ret->y = (A1*C2 - A2*C1)/det; return ret; }
}
Reference. C++ Example: Geometry Concepts Line Intersection and its Applications, 2D drawing By lbackstrom from site ucancode
-12782373 0 html select option SELECTEDI have in my php
$sel = " <option> one </option> <option> two </option> <option> thre </option> <option> four </option> ";
let say I have an inline URL = site.php?sel=one
if I didn't saved those options in a variable, I can do it this way to make one of the option be SELECTED where value is equal to $_GET[sel]
<option <?php if($_GET[sel] == 'one') echo"selected"; ?> > one </option> <option <?php if($_GET[sel] == 'two') echo"selected"; ?> > two </option> <option <?php if($_GET[sel] == 'three') echo"selected"; ?> > three </option> <option <?php if($_GET[sel] == 'four') echo"selected"; ?> > four </option>
but the problem is, I need to save those options in a variable because I have a lot of options and I need to call that variable many times.
Is there a way to make that option be selected where value = $_GET[sel]
?
I am trying to integrate FB connect into our user profile screen. Although, I'm having an issue with FB.ApiClient.revokeAuthorization.
The basic problem is that I revoke the auth at line 44 after the user clicks the disconnect button.
After that, all subsequent API calls don't have a valid session to even check user status. I've tried wrapping blocks in a FB.Connect.forceSessionRefresh block, but then the code will never be called at all.
I'm not sure what the proper workflow should be for this purpose. Right now it's basically...
Try this : WHERE IV00101.ITEMNMBR = IV00102.ITEMNMBR AND IV00102.ITEMNMBR = ItmPrice.ITEMNMBR group by IV00101.ITEMNMBR ORDER BY IV00101.ITEMNMBR
-38003846 1 Python Mongodb limiting by batch size times outI'm trying to scrape a huge (5gb) mongo database, so I'm limiting the batch size in order to be manageable. However, I'm still getting a time out error :/
My mongo knowledge is admittedly not the best, so if I'm doing something utterly stupid, please let me know! I already searched through the documentation and other questions and none of the answers have helped.
Here is what I'm trying to do:
from pymongo import MongoClient collection = MongoClient(host="mongodb://xxx@xxx") cursor = collection.all_companies.companies batch = cursor.find().batch_size(1).limit(1) # I tried w/ other numbers too for item in batch: print item
And here's what I'm getting:
-40615228 0 count rows taking into account qtypymongo.errors.ServerSelectionTimeoutError: xxx:xxx: timed out
I currently get a count by runningthe following command, and parsing it into a custom pdo
select function.
SELECT COUNT(*) FROM foo GROUP BY bar
Table Structure
col1 | col2 | bar | qty ------------------------ blahb blah abc 1 blahb blah abc 3 blahb blah abc 1 blahb blah aaa 3 blahb blah aaa 5 blahb blah aaa 1
This will return:
abc => 3 aaa => 3
Is there a way of modifying the query so that the qty
multiplies the bar
column?
Desired Result:
abc => 5 aaa => 9
Why are certain functions in PHP (such as eregi
) deprecated? I normally use eregi
for email validation.
Should I use it, or is there another function that can be used in its place?
-9757195 0Maybe this one close to your expression will fit your need :
just get rid of chars that your are not interested after your keyword or match the end of string
-5984205 0(?:[a-zA-Z'-]+[^a-zA-Z'-]+){0,5}keyword(?:[^a-zA-Z'-]+|$)(?:[a-zA-Z'-]+[^a-zA-Z'-]*){0,5}
already you can write like this: SampledbDataContext sdc = new SampledbDataContext(Server.MapPath("~/Sampledb.mdf")); or in design.cs file public SampledbDataContext() : base(global::"[write cnn string Here !]", mappingSource) { OnCreated(); }
-26918806 0I think this is a problem and I think if I set it to 1GB it will increase the performance and capability, is that right ?
It will mean the DB will need to stop less often to grow, certainly, and data inserts will occur more frequently. It will reduce the impact of data file growth. However, Microsoft says that autogrow is not intended to manage planned file growth. It's intended to handle unexpected growth. Autogrow is just not designed to work the way you're using it. The design intent is that you know how much data you will be storing and you have planned accordingly and already correctly sized your DB.
This might be somewhat unrealistic given your application, however. If your system is designed to hold all data ever collected indefinitely, your capacity planning is a bit difficult.
This is why it's common practice to differentiate operational data from warehoused data. Your operational data is stored in one database, which you can predict the growth for within a given time frame (usually 1 or more years). After a period of time, older data is archived to data warehouses, which may be very large or single year containers, but since data is inserted here rarely, you know what your capacity is going to be.
If I were you, I would pick a time frame to plan for. Say one month, quarter, or year. Every period of time, manually grow your database large enough so that the free space is what you expect to need to accommodate the coming period. Don't forget to include index space! Use the SSMS reports to help your estimates!
This means you can do your growth during off-hours or maintenance windows and your application is never waiting on the DB to finish growing. I would then set autogrowth to be about 5% of the free space you're planning for. If you underestimate, you'll get an idea by how much when you look at your shrink/grow logs. You can then increase for next month. Eventually, you'll learn what you need on a monthly basis. Just make sure to grow based on free space in the database and not absolute file size.
-36445189 0 libcurl use same user defined port to send periodic requestI am working on a project need to send periodic alive message to https server.
Because of security issue, we need to use minimal number of ports (blocking unused ports as many as we can).
I am using c++ libcurl easy interface to send https request in linux.
I have tried to use the same curl handler object (CURL object) and set CURLOPT_LOCALPORT to a port number. The first request is ok. But in the second, libcurl verbose mode said address already in use. However, when I comment out the port set through CURLOPT_LOCALPORT, it works on second connection also, and by setting VERBOSE to 1, I can see "Re-using existing connection" print out, which is missing in version setting up local port. And I check with linux netstat, find out that it is using the same port. I cannot figure out why setting up local port will make it failed.
And also, I have tried to close the connection using curl_easy_cleanup, but due to tcp time_wait state, we cannot reuse the port in a while, that's not what I want.
Could anyone provide a solution or suggestion to us? Thanks a lot.
Edit My reason using one port is not to keep opening and closing connection too much.
-4699246 0Your best bet is probably to use shell_exec to cat some of the data from the various /proc/* files that are commonly used on Linux/Unix systems, the key ones probably being:
For example:
echo shell_exec('cat /proc/cpuinfo/');
-14809573 0 If you want to share users informations database from a master to other(s) Joomla website(s), there's a better solution.
The only requirement is all databases must be located on the same server + Joomla 2.5.x!
Open PhpMyAdmin and apply this modifications :
xxxx1... are tables from master site
xxxx2... are tables from client site
DROP TABLE xxxx2_session DROP TABLE xxxx2_usergroups DROP TABLE xxxx2_users DROP TABLE xxxx2_user_notes DROP TABLE xxxx2_user_profiles DROP TABLE xxxx2_user_usergroup_map CREATE VIEW xxxx2_users AS SELECT * FROM xxxx1.jos_users CREATE VIEW xxxx2_session AS SELECT * FROM xxxx1.jos_session CREATE VIEW xxxx2_usergroups AS SELECT * FROM xxxx1.jos_usergroups CREATE VIEW xxxx2_user_notes AS SELECT * FROM xxxx1.jos_user_notes CREATE VIEW xxxx2_user_profiles AS SELECT * FROM xxxx1.jos_profiles CREATE VIEW xxxx2_user_usergroup_map AS SELECT * FROM xxxx1.jos_usergroup_map
-28705658 0 Align 3 elements in css I have 3 elements which I want to align in my html file. I have attached a sample image, the first image just has a left margin and is vertically centered. the middle element is vertically and horizontally centered and the third element has right margin and is vertically centered.
I can independently align elements horizontally and vertically with below code :
#element{ height : 40%; position : relative; left : 50%; top : 50%; transform : translate(-50%,-50%); }
but when it comes to align elements along each other they don't place correctly.
I'll appreciate if you can help me with this.
Thanks very much
I'm trying to understand why the following is not working as I would think it does. I'd like to check whether an object is a window. I was thinking that checking the constructors of the current window and another window would work.
So, first creating another window:
var popup = window.open('', '', '');
And then checking with:
popup.constructor === window.constructor;
But for some reason the results vary among browsers:
true
.constructor === undefined
false
""
)false
.constructor === DOMWindow
- but DOMWindow
is not accessible directly like thisfalse
.constructor === Object
false
.constructor === Window
Why isn't this reliable and working correctly? jQuery simply checks for "setInterval" in window
, but I'd like to create a more robust function for checking whether an object is a window.
When a servlet runs, the user from an operating system perspective is the user that the Servlet Container (Jetty, Tomcat, Glassfish, etc) is running as. It is the rights of that user that are being checked by the operating system. The owner of the JSP file is irrelevant. Well, to be precise the JSP file has to be readable by the user that the Servlet Container is running as otherwise it can't be executed but in terms of OS permissions for the actions defined by that JSP, the only thing that matters is the user the Servlet Container is running as.
-1346611 0If you are on SQL Server 2008, then you can try Change Data Capture which will allow you to pick up a Delta of changes every time.
http://msdn.microsoft.com/en-us/library/cc645937.aspx
-38112027 0As it seems this is a common issue I'll try to provide more information here:
First, make sure you check whatever code you are using on your Analytics. The first answer provided here pasted a code using Google GA.JS code, but many websites today uses the new Analytics.JS code (my case). So my suggestion is to copy your GA code from your website or from your GA panel.
Second, check if your GA code is being passed on your Instant Article RSS feed correctly (i'm assuming you are using Wordpress with some plugin to build a RSS). If you are using the new analytics.js method the code inside your RSS feed (per article) should be like this:
<!-- Adding tracking if defined --> <figure class="op-tracker"> <iframe> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); ga('create', 'YOUR_GA_ID', 'auto'); ga('send', 'pageview'); </script> </iframe> </figure>
Third, if your articles were already on Facebook Instant Article Production list BEFORE you added the Analytics code, they will NOT update / load the code. The best way to test is to edit any of your articles (a simples change of punctuation is enough) and republish it on your wordpress. Then go to your IA panel on Facebook, Configuration and click to reload / rebuild your RSS. Wait a little then check on the list of I.A that the post will update (you will see the date change), then open it on the edit option and check at the end of the code. Your GA code should be there.
So, if everything is good now, your last step (at least was for me) is to delete all the old Instant Articles on Facebook (I'm assuming you don't have them published yet) and reload the RSS feed on the Configuration area, so it will rebuild your articles with the GA code on them.
Hope this helps.
PS: I'm NOT using the plugin from Automattic to publish IA from WP as it's just garbage. There is one way simpler that work's w/o any trouble: https://wordpress.org/plugins/allfacebook-instant-articles/
-36117284 0By default phalcon's router is using auto routing in this convention : '/:module/:controller/:action/:params
in multimodule application and '/:controller/:action/:params
in single module application. If you want to get rid from it then you have to pass false to router constructor.
You should not rewrite static files. Where are your images/css files located?
A rewrite rule like this will prevent files existing on disk not to be rewritten:
RewriteCond %{REQUEST_FILENAME} !-f # Do not rewrite static files RewriteCond %{REQUEST_FILENAME} !-d # Do not rewrite static directories
As for your second question, please clarify, im not sure i understand what you mean.
-19014476 0You could switch your MVC action to ActionResult
instead of FileStreamResult
. Then just point to it with a regular link, no jquery post is needed:
<a href="/controller/GetFile"target="_blank">
-28882184 0 How to resolve Tabdrop bootstrap issue? I use bootstap Modal and Bootstrap tabs and i want to achieve the tabdrop, when the Modal window loads the tabs are not grouped even they overflow $('.nav-tabs').tabdrop({text: "More"});
but when i resize the browser window it works, what could be the problem in this case?
try wrapping it in onCreateOptionsMenu
win.activity.onCreateOptionsMenu = function(e) { actionBar = win.activity.actionBar; if (actionBar) { alert("ACTIVITY"); actionBar.backgroundImage = "/images/bg_top.png"; actionBar.title = "New Title"; actionBar.onHomeIconItemSelected = function() { Ti.API.info("Home icon clicked!"); }; } else { alert('missing action bar'); } });
-7502566 1 FieldError on ManyToMany after upgrading to Django 1.3 Just been updating to Django 1.3 and come across an odd error. I'm getting the following error from some code which works with version 1.2.7.
FieldError: Cannot resolve keyword 'email_config_set' into field. Choices are: id, name, site, type
The odd thing being email_config_set is a related name for a ManyToMany field. I'm not sure why django is trying to resolve it into a field.
The error occurs deep inside django:
Traceback (most recent call last): File "./core/driver.py", line 268, in run self.init_norm() File "./driver/emailevent/background.py", line 130, in init_norm self.load_config() File "./driver/emailevent/background.py", line 71, in load_config events = list(config.events.select_related()) File "/usr/local/lib/python2.6/site-packages/Django-1.3.1-py2.6.egg/django/db/models/manager.py", line 168, in select_related return self.get_query_set().select_related(*args, **kwargs) File "/usr/local/lib/python2.6/site-packages/Django-1.3.1-py2.6.egg/django/db/models/fields/related.py", line 497, in get_query_set return superclass.get_query_set(self).using(db)._next_is_sticky().filter(**(self.core_filters)) File "/usr/local/lib/python2.6/site-packages/Django-1.3.1-py2.6.egg/django/db/models/query.py", line 550, in filter return self._filter_or_exclude(False, *args, **kwargs) File "/usr/local/lib/python2.6/site-packages/Django-1.3.1-py2.6.egg/django/db/models/query.py", line 568, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "/usr/local/lib/python2.6/site-packages/Django-1.3.1-py2.6.egg/django/db/models/sql/query.py", line 1194, in add_q can_reuse=used_aliases, force_having=force_having) File "/usr/local/lib/python2.6/site-packages/Django-1.3.1-py2.6.egg/django/db/models/sql/query.py", line 1069, in add_filter negate=negate, process_extras=process_extras) File "/usr/local/lib/python2.6/site-packages/Django-1.3.1-py2.6.egg/django/db/models/sql/query.py", line 1260, in setup_joins "Choices are: %s" % (name, ", ".join(names))) FieldError: Cannot resolve keyword 'email_config_set' into field. Choices are: id, name, site, type
Any pointers or tips would be welcome.
-38071649 0To dynamically create an attribute based on certain conditions, re-jig your code to this...
<xsl:element name="{if (@role='rowhead' ) then 'th' else 'td'}"> <xsl:if test="fn:exists(@def)"> <xsl:attribute name="class" select="concat('def-', @def)"/> </xsl:if> <xsl:apply-templates /> </xsl:element>
If you use xsl:attribute
immediately after xsl:element
the attribute gets appended on to the element. Note that attributes must be created before any child elements.
The response contains no content in the geodata-lat element. It appears that client side code is getting that data so your response only is looking at the html that the server generated. I tried this out myself and this is the section of the response you are looking for. You can see it is empty:
If you try an element that has content (geodata-kml-button), it does pull in a value ("Download KML file"). Ignore the ByteArrayToString() call, that was just me testing:
If they don't have a real API then I don't think you can get your data this way.
-27304748 0 Significant performance differences in JTextPane when text contains linefeedI wrote a method that writes hello world!\n 10000 times in a JTextPane. I recognized a significant performance drop when using hello world! without linefeed.
Example:
import java.awt.BorderLayout; import javax.swing.*; import javax.swing.text.*; public class JTextPaneTest { JTextPane textPane = new JTextPane(); Document doc = new DefaultStyledDocument(); //constructor JTextPaneTest() { for(int i=0;i<10000;i++) { try { doc.insertString(doc.getLength(), i+" hello world!", null); } catch (BadLocationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } textPane.setDocument(doc); createWindow(); } public void createWindow() { JFrame frame = new JFrame(); frame = new JFrame("frame"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(400, 300); frame.setLocationRelativeTo(null); frame.getContentPane().add(new JScrollPane(textPane), BorderLayout.CENTER); frame.setVisible(true); } public static void main(String[] args) { System.out.println("start..."); float startTime = System.nanoTime(); new JTextPaneTest(); float stopTime = System.nanoTime() - startTime; System.out.println("elapsed time main: "+stopTime/1000000000+ "s"); } }
what could be the reason for that phenomena? Any ideas?
-34944194 0 Show user his productsThis is my first year with HTML, PHP, JAVASCRIPT and mysql!
And i am having a problem, im making a website that users can only see them products. For example: Admin created a product for MARTA, when MARTA log in she can see her product.
I have created the table USER_EQUIPMENT but i don't know how can i use it like i want.
I made something like this:
function getEquipment($name) { $query = "select * from equipments where name = '$name'"; $this->connect(); $res = $this->execute($query); $this->disconnect(); return $res; }
and then i called it like:
$name = $_SESSION['name']; include_once('DataAccess.php'); $da = new DataAccess(); $res = $da->getEquipment($name);
But i doesn't get the equipment by the name. Little help please?
Thanks.
-3804934 0bool equals = a.Intersect(b).Count() == a.Union(b).Count()
is about arrays but as far as IEnumerable<T>
methods are used, it can be used for Dictionary<K,V>
too.
Create jsfiddle
and check it in browserstack:
Check what you don't have javascript errors on page.
-35508498 0 mongodb native driver issues on filter queriesI'm having trouble getting to use the query mongodb.
I do not know if I could detail the method used is being sent an object, but is being rejected or sometimes the filter back empty.
it always returns me an error:
MongoError: query selector must be an object
The entry of the query is being thereby:
{ filter: 'f', limit: '5', page: '1', sort: '-posted' }
My server Route:
exports.findAll = function(req, res, next) { var locals = {}, section = req.params.section, query = req.query, filter = {}; if(query.filter) { filter = query.filter.replace(/"(\w+)"\s*:/g, '$1:'); filter = filter.replace(/["]/g, "'"); } console.log(filter); delete query.filter; async.series([ function(callback) { MongoClient.connect(url, function(err, db) { if (err) return callback(err); locals.collection = db.collection(section); callback(); }); }, function(callback) { locals.collection.count(filter, function (err, result){ if (err) return callback(err); locals.count = result; callback(); }); }, function(callback) { //var cursor = locals.collection.find(filter); var cursor = locals.collection.find(filter, req.query); // if(req.query.order) { // cursor = cursor.sort(); // } // // if(req.query.limit) { // cursor = cursor.limit(Math.abs(req.query.limit)); // if(req.query.page) { cursor = cursor.skip(Math.abs(req.query.limit) * --req.query.page); } // } cursor.toArray(function(err, docs) { if (err) return callback(err); locals.docs = docs; callback(); }); } ], function(err) { //This function gets called after the three tasks have called their "task callbacks" if (err) return next(err); // Here locals will be populated with 'count' and 'docs' res.json({ count: locals.count, data: locals.docs }); });
};
i change the function server, adn now my response is:
{ filter: {situation: 't'}, limit: '5', page: '1', sort: '-posted' }
And same error :( :(
-28354731 0SELECT * FROM table WHERE val = if(condition1, 'result1', if(condition2, 'result2', if(condition3, 'result3','result')))
-13871663 0 Did you changed the password you use in the machine where the SQL server is installed? I experienced this before, and what I did was to reflect my new password to the SQL Server configuration, then restart the service.
Please also make sure the the TCP/IP setting is enabled in the SQL configuration settings.
-14238164 0If one class is specifically designed for validation purposes and another class is designed to contain instance-specific information, then there are three different approaches you can take.
1) Statically reference the validator (recommended):
<?php class Validation { public static function validateEmail($email) { return filter_var($email, FILTER_VALIDATE_EMAIL); } } class AccountManagement { public $email; public function __construct($email) { $this->email = $email; // Validate the e-mail. If not valid, an exception is thrown. if(!Validation::validateEmail($this->email)) { throw new InvalidArgumentException('$email argument supplied must contain a valid e-mail address'); } } }
2) Extend your instance class to inherit from your validation class
<?php class Validation { public function validateEmail($email) { return filter_var($email, FILTER_VALIDATE_EMAIL); } } class AccountManagement extends Validation { public $email; public function __construct($email) { $this->email = $email; // Validate the e-mail. If not valid, an exception is thrown. if(!$this->validateEmail($this->email)) { throw new InvalidArgumentException('$email argument supplied must contain a valid e-mail address'); } } }
3) Instantiate your validation class from within your instance class (NOT RECOMMENDED):
<?php class Validation { public function validateEmail($email) { return filter_var($email, FILTER_VALIDATE_EMAIL); } } class AccountManagement extends Validation { public $email; public function __construct($email) { $this->email = $email; $validator = new Validation; // Validate the e-mail. If not valid, an exception is thrown. if(!$validator->validateEmail($this->email)) { throw new InvalidArgumentException('$email argument supplied must contain a valid e-mail address'); } } }
Testing your implementation
Once you've chosen the method which best fits your needs (regardless of which one you choose), you can test it with the following code:
// Valid, should not throw an exception and should print success. try { $account = New AccountManagement('me@myself.com'); print "AccountManagement object successfully instantiated.<br />\r\n"; } catch(Exception $e) { print 'Error: Encountered ' . $e; } // Invalid, should throw an InvalidArgumentException exception try { $account = New AccountManagement('myself.com'); print "AccountManagement object successfully instantiated.<br />\r\n"; } catch(Exception $e) { print 'Error: Encountered ' . $e; }
Bonus Example:
Sometimes, you may want to specifically catch Validation errors, and let something take care of any other exceptions which may be encountered. In this case, we can create a special exception just for our validator, and allow the validator to be the one to throw the exception:
<?php class ValidationException extends Exception { // Will use default Exception behavior. } class Validation { public static function validateEmail($email) { if(!filter_var($email, FILTER_VALIDATE_EMAIL)) { throw new ValidationException('E-mail address supplied is not valid'); } } } class AccountManagement { public $email; public function __construct($email) { $this->email = $email; // Validate the e-mail. Validation::validateEmail($this->email); } } // Valid, should not throw an exception and should print success. try { $account = New AccountManagement('me@myself.com'); print "AccountManagement object successfully instantiated.<br />\r\n"; } catch(Exception $e) { print 'Error: Encountered ' . $e; } // Invalid, should throw an ValidationException exception try { $account = New AccountManagement('myself.com'); print "AccountManagement object successfully instantiated.<br />\r\n"; } catch(ValidationException $e) { print 'Error: Encountered ' . $e; }
-14854935 0 Exception Due to referring struts.dtd file from internet/local From morning facing Exception while running struts2 apps....application was working yesterday
There's a problem in loading some struts2-jquery jar even though they exist in WEB-INF/lib
After browsing I got some solution to make change in struts.xml <!DOCTYPE ....>
like changing
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd">
to
<!DOCTYPE struts SYSTEM "../dtds/struts-2.0.dtd">
or
<!DOCTYPE struts SYSTEM "struts-2.0.dtd">
For local referencing struts.dtd but none of these working..
Exception on console :
Unable to load configuration. - action - file:/D:/.........plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/XXXXXXXX/WEB-INF/classes/struts.xml:25:88 at com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:58) at org.apache.struts2.dispatcher.Dispatcher.init_PreloadConfiguration(Dispatcher.java:360) at org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:403) at org.apache.struts2.dispatcher.ng.InitOperations.initDispatcher(InitOperations.java:69) at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.init(StrutsPrepareAndExecuteFilter.java:48) at org.apache.catalina.core.ApplicationFilterConfig.initFilter(ApplicationFilterConfig.java:273) at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:254) at org.apache.catalina.core.ApplicationFilterConfig.setFilterDef(ApplicationFilterConfig.java:372) at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:98) at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4584) at org.apache.catalina.core.StandardContext$2.call(StandardContext.java:5262) at org.apache.catalina.core.StandardContext$2.call(StandardContext.java:5257) at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source) at java.util.concurrent.FutureTask.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) Caused by: Error building results for action getGroups in namespace - action - file:/D:/T....plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/XXXXXXX/WEB-INF/classes/struts.xml:25:88
-11450737 0 Is Content Negotiation broken? I recently got interested in web crawlers but one thing isn't a very clear one to me. Imagine a simple crawler that would get the page, extract links from it and queue them for later processing the same way.
How crawlers handle the case when certain link wouldn't lead to another page but to some asset or maybe other kind of static file instead? How would it know? It probably doesn't want to download this kind of maybe large binary data, nor even xml or json files. How content negotiation fall into this?
How I see content negotiation should work is on the webserver side when I issue a request to example.com/foo.png
with Accept: text/html
it should send me back an html response or Bad Request status if it cannot satisfy my requirements, nothing else is acceptable, but that's not how it works in the real life. It send me back that binary data anyway with Content-Type: image/png
even when I'm telling it I only accept text/html
. Why webservers work like this and not coercing the right response I'm asking for?
Is implementation of content negotiation broken or it's application's responsibility to implement it correctly?
And how does real crawlers work? Sending HEAD request ahead to check whats on the other side of a link sees as an unpractical waste of resources.
-34002792 0You should login your user again and only after that attach the file.I had similar situation when i took a picture using camera. I did this. Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivity(intent); CameraActivity was started and connection was lost, so you need to reconnect if you want to upload the file.
-18872090 0There is a config.inc.php under setup/frames, this is the one you are showing us but it's not the one that contains the configuration. Look at the main directory containing all the db_* and tbl_* scripts. However, phpMyAdmin is able to run without a config.inc.php.
Do you see a login panel with phpMyAdmin logo?
-10784772 0 Drawing a line with a brush in iOSthere are so many posts here, were people ask how to draw lines with a brush in CGContext. The answer always is: Use a pattern. However, I tried this for some hours now and the main problem to me seems to be: It seems like CoreGraphics simply draws the pattern as a fill and then simply clips this pattern with the stroke of the path you specified. This leads to some bad looking tile-borders and it simply doesn't look as someone really draws something by hand. What I want is something were the brush is painted along the path, without any clipping. I basically want to move along the path and simply draw the brush image every x points, in distance, on the path, with the size of the brush. Is this somehow possible with CoreGraphics or is this just something you have to implement on your own?
//EDIT: Sorry, I thought it was clear what I tried by saying, I used a pattern. This is what I did so far:
struct CGPatternCallbacks patternCallback = {0, drawChalkPattern, NULL}; CGAffineTransform patternTransform = CGAffineTransformMakeScale(.25f, .25f); UIImage* brush = [UIImage imageNamed:@"ChalkBrush"]; CGPatternRef pattern = CGPatternCreate(NULL, (CGRect){CGPointZero, brush.size}, patternTransform, brush.size.width, brush.size.height, kCGPatternTilingConstantSpacingMinimalDistortion, true, &patternCallback); CGColorSpaceRef patternSpace = CGColorSpaceCreatePattern(NULL); CGContextSetStrokeColorSpace(context, patternSpace); CGFloat color[4] = {1.0f, 1.0f, 1.0f, 1.0f}; CGContextSetStrokePattern(context, pattern, color); CGContextDrawPath(context, kCGPathStroke);
and than this is the patternCallback function:
void drawChalkPattern(void * info, CGContextRef context) { UIImage* pattern = [UIImage imageNamed:@"ChalkBrush"]; CGContextDrawImage(context, (CGRect){CGPointZero, pattern.size}, [pattern CGImage]); }
Best regards, Michael
-32181194 0Rust has local type inference, so the type normally doesn’t need to be written; let x = 5;
will suffice. x = 5;
would be quite different, as it would not declare a variable x
, and Rust very deliberately separates declaration and assignment.
It’s also actually let PATTERN = EXPR;
, not just let IDENT = EXPR;
, so removing the let
keyword would cause grammatical ambiguity. A pattern could be mut x
(making the variable binding mutable), it could be (a, b)
signifying tuple unpacking, &c.
You only think i32 x = 5;
makes sense because you’re used to languages like C++. Seriously, who came up with that idea? It makes more sense on purely philosophical grounds to have the type after the name than before, and having just the type to declare variables is silly too. All sorts of grammatical ambiguity there. Type inference, allowing you to omit the type altogether, is a much nicer approach all round.
I have written a plugin which isn't finished yet I might add. All it does at the moment is to check if all inputs are empty. If any inputs are empty it puts a message under the input.
Now the plugin is suppose to return false if it fails.
The problem is chaining. The way it works at the moment it doesn't chain if I return false, because I am not returning base.
How do I make this plugin return false and still chain.
;(function($){ "use strict"; $.fn.valiDate = function(options){ var base=this; /*Adds the input on the page */ if(!$('#asi_validate').length) { $('.footer').before('<span style="border:1px solid black;background-color:#FFF;color:red;\ box-shadow: 5px 5px 5px #888888;padding:5px;position:absolute;width:auto;display:none;\ " id="asi_validate"></span>'); } var valid = true; var validatepos=$('#asi_validate'); base.check_key= function(){ $(this).keyup(function(){ validatepos.fadeOut(50); }); } base.check= function() { $('input').each(function() { if (this.value == '') { var cell=$(this); var position = cell.offset(),maxLength=cell.val().length; validatepos.css('left',position.left), validatepos.css('top',position.top+(cell.outerHeight()+2)), validatepos.fadeIn(100), validatepos.html('This field is required'); valid = false; return false; } }); } base.check_key(); base.check(); if (valid === false) { return false; } return base; }; })(jQuery);
-17945944 0 In XAML a string is so easily converted to a color that you hardly realize they are very different types. In C# you will have to convert it explicitly. Luckily there is a built-in class that can do that:
string colorName = (string) listColor.SelectedItem; Color colorValue = ColorConverter.ConvertFromString(colorName);
-38488612 0 Search all tables to display a row that contains a specific string/ id I am fairly new to PostgreSQL. I want to search all tables that contain a string/id and display the row that holds the string/id. This is what I have so far:
`CREATE OR REPLACE FUNCTION search_columns( needle text, haystack_tables name[] default '{}', haystack_schema name[] default '{public}' ) RETURNS table(schemaname text, tablename text, columnname text, rowctid text) AS $$ begin FOR schemaname,tablename,columnname IN SELECT c.table_schema,c.table_name,c.column_name FROM information_schema.columns c JOIN information_schema.tables t ON (t.table_name=c.table_name AND t.table_schema=c.table_schema) WHERE (c.table_name=ANY(haystack_tables) OR haystack_tables='{}') AND c.table_schema=ANY(haystack_schema) AND t.table_type='BASE TABLE' --AND c.column_name = "id" LOOP EXECUTE format('SELECT ctid FROM %I.%I WHERE cast(%I as text) like %L', schemaname, tablename, columnname, needle ) INTO rowctid; IF rowctid is not null THEN RETURN NEXT; END IF; END LOOP; END; $$ language plpgsql; select * from search_columns('%3172226%','{}');` I run the code above and the tables that contain 3172226 get displayed. Let's assume I found that tablenamexxx contains the id. Then I run the following command: `select * from public.tablenamexxx where ctid='(x,x)';`
The command above displays the row from tablenamexxx
I have two problem: 1) I want to alter my code so I don't have to type in the found tablenames (that contain 3172226). I want my code to find what tables contain the id and directly display the row that has the id.
2)There are two tables that have the id (3172226). I want to display both the tables together. My guess is using union all.
Any help would be appreciated! Thank you
-10465436 0It gives me a blank page.
Actually it should. You don't use output functions in code you shown. If you expected error messages, make sure you have display_errors
enabled and error_reporting
to E_ALL
Using any of the lines below throws a ClassNotFoundException when app is run on Android.
val list = listOf("a", "b") val arrayList = arrayListOf("a", "b") val map = mapOf("key" to "value")
The exception:
04-28 15:12:00.770 27326-27326/com.example.kotlin E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.kotlin, PID: 27326 java.lang.NoClassDefFoundError: Failed resolution of: Lkotlin/collections/CollectionsKt; at com.example.kotlin.MainActivity.onCreate(MainActivity.kt:17) at android.app.Activity.performCreate(Activity.java:6237) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) at android.app.ActivityThread.-wrap11(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) Caused by: java.lang.ClassNotFoundException: Didn't find class "kotlin.collections.CollectionsKt" on path: DexPathList[[zip file "/data/app/com.example.kotlin-1/base.apk"],nativeLibraryDirectories=[/data/app/com.example.kotlin-1/lib/x86, /vendor/lib, /system/lib]] at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56) at java.lang.ClassLoader.loadClass(ClassLoader.java:511) at java.lang.ClassLoader.loadClass(ClassLoader.java:469) at com.example.kotlin.MainActivity.onCreate(MainActivity.kt:17) at android.app.Activity.performCreate(Activity.java:6237) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) at android.app.ActivityThread.-wrap11(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) Suppressed: java.lang.ClassNotFoundException: kotlin.collections.CollectionsKt at java.lang.Class.classForName(Native Method) at java.lang.BootClassLoader.findClass(ClassLoader.java:781) at java.lang.BootClassLoader.loadClass(ClassLoader.java:841) at java.lang.ClassLoader.loadClass(ClassLoader.java:504) ... 14 more Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack trace available
The following is my app module gradle file:
apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' android { compileSdkVersion 23 buildToolsVersion "24.0.0 rc3" defaultConfig { applicationId "com.example.kotlin" minSdkVersion 16 targetSdkVersion 23 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } dataBinding { enabled = true } sourceSets { main.java.srcDirs += 'src/main/kotlin' } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.3.0' compile 'com.android.support:gridlayout-v7:23.3.0' compile 'com.android.support:cardview-v7:23.3.0' kapt 'com.android.databinding:compiler:2.1.0-beta3' } buildscript { ext.kotlin_version = '1.0.1-2' repositories { mavenCentral() } dependencies { classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } } repositories { mavenCentral() } kapt { generateStubs = true }
Is there any other dependency I need to add to gradle in order to use any of the Kotlin collection classes?
-9203949 0My understanding is that the user can extend localstorage but the website can't (by design). You simply need to catch the error in Javascript and show the user a dialog requesting they increase their storage limit - preferably providing some instructions for major browsers.
EDIT: Perhaps not so simple. It seems some browsers don't allow the user to increase the storage size. Google seems convinced the localStorage API doesn't scale well to large files and developers should consider IndexedDB instead.
-13289354 0see Oracle tutorial How to Write a List Selection Listener
there are
a) single selection mode
b) single interval selection mode
c) multiple interval selection mode
rest is described in tutorial How to Use Lists
probably you search for multiple interval selection mode
I could not place a comment, but try to look for the image view in your activity. It could be because your code is overriding it from there.
also limit the size of your imageview from the layout xml to make sure its loaded correctly.
And from experience with large photos, they normally not loaded easily on an emulator. so try smaller image as a last step.
-22853672 0I did it like
$where = new \Zend\Db\Sql\Where(); $where->equalTo('company_id',$company_id)->and ->equalTo('users.status','1')->nest() ->isNull('project_id')->or->equalTo('project_id',$project_id) ->unnest(); $resultSet = $this->tableGateway->getSql()->select() ->join(array('pu'=>'project_users'), 'users.id = pu.user_id', array('project_id'), 'left') ->join(array('r'=>'roles'),'pu.role_id=r.id', array('role'),'left') ->where($where);
-3492763 0 Active Directory User Group Membership I am trying to get a users group membership and limiting the results to those that match a string, ie I am only interested in the users group membership where the group begins with "test-".
The following is what I have been playing around with, even though the user is apart of several groups that match the search string, the If statement is not returning True on any of them.
Private Function GetGroups(ByVal userName As String) As Collection Dim Groups As New Collection Dim intCount As Integer Dim entry As DirectoryEntry = ADEntry() Dim mySearcher As DirectorySearcher = New DirectorySearcher(entry) Dim arrList As New ArrayList() ' Limit the search results to only users mySearcher.Filter = "(&(ObjectClass=User)(CN=" & userName & "))" ' Set the sort order mySearcher.PropertiesToLoad.Add("MemberOf") Dim searchResults As SearchResultCollection = mySearcher.FindAll() MessageBox.Show(searchResults.Count) If searchResults.Count > 0 Then Dim group As New DirectoryEntry(searchResults(0).Path) For Each member As Object In group.Properties("MemberOf") MessageBox.Show("Pre: "+ member) 'This message box returns all the groups the user is apart of. If group.Properties("memberOf").Contains("test-") = True Then MessageBox.Show(member) ' This message box never shows End If Next End If Return Groups End Function
Is there any way of applying a search or If statement agains an Object where the constraint is a wildcard?
The groups I am looking for could be one of about 60 (this amount does increase and decrease as staff leave).
I am using VB.NET 2.0.
Thanks,
Matt
-24352732 0 Can not preview the welcome page in laravel 4.2I have installed laravel 4.2 in http://localhost/laravel/varadha/
According to Quick start guide of laravel if i visit http://localhost/laravel/varadha/
, i should get a welcome message. but i am getting this message.
Index of /laravel/varadha Name Last modified Size Description
Parent Directory - CONTRIBUTING.md 22-Jun-2014 20:28 146 app/ 22-Jun-2014 20:28 - artisan 22-Jun-2014 20:28 2.4K bootstrap/ 22-Jun-2014 20:28 - composer.json 22-Jun-2014 20:28 697 composer.lock 22-Jun-2014 20:28 58K laravel-master/ 22-Jun-2014 20:30 - phpunit.xml 22-Jun-2014 20:28 567 public/ 22-Jun-2014 20:28 - server.php 22-Jun-2014 20:28 519 vendor/ 22-Jun-2014 20:29 -
I am using wamp server.
PHP 5.4.29.
MYSQl 5.5.8
Apache 2.2.17
-9991099 0 Does perforce SCC plugin support Visual Studio 2010 Express?I can’t seem to find information on that on perforce’s website, nor on the SCC plugin release notes. Launching Visual Studio 2010 after installing the plugin shows no difference.
-6244740 0 Chrome Extension Timed RedirectionWhat I'm trying to achieve is make a chrome extension run in the background, and every minute it'll redirect to google.com and then a minute later redirect to stackoverflow.com and so on continuously until the icon is clicked by the wrench icon where most of the extensions are.
However I only know on how to redirect a page using window.location.replace("http://google.com");
I'm still learning on how to develop chrome extensions, and just making some simple stuff for a learning process. I started learning from this tutorial, and tried a couple things out, and now I wanna figure out how to get something like this to work with it running in the background.
-20700295 0//由于调用 ProvideFault 时,客户端处于阻塞状态,不要在这里进行长时间的操作 public void ProvideFault(Exception error, MessageVersion version, ref Message msg) { //避免敏感信息泄漏,例如:数据库配置, error包含的错误信息应该记录到服务器的日志中,不能显示给客户端 // FaultException<int> e = new FaultException<int>(123, error.Message); DateTime now = DateTime.Now; time = now.ToString("yyyyMMddHHmmssfff", DateTimeFormatInfo.InvariantInfo);// "" + now.Year.ToString() + now.Month.ToString() + now.Day.ToString() + now.Hour.ToString() + now.Minute.ToString() + now.Second.ToString() + now.Millisecond.ToString(); string errorMsg = "服务内部错误_" + time; // FaultException fe = new FaultException(errorMsg); // MessageFault mf = fe.CreateMessageFault(); // msg = Message.CreateMessage(version, mf, fe.Action); //The fault to be returned msg = Message.CreateMessage(version, "", errorMsg, new DataContractJsonSerializer(typeof(string))); // tell WCF to use JSON encoding rather than default XML WebBodyFormatMessageProperty wbf = new WebBodyFormatMessageProperty(WebContentFormat.Json); // Add the formatter to the fault msg.Properties.Add(WebBodyFormatMessageProperty.Name, wbf); //Modify response HttpResponseMessageProperty rmp = new HttpResponseMessageProperty(); // return custom error code, 400. rmp.StatusCode = System.Net.HttpStatusCode.InternalServerError; rmp.StatusDescription = "Bad request"; //Mark the jsonerror and json content rmp.Headers[HttpResponseHeader.ContentType] = "application/json"; rmp.Headers["jsonerror"] = "true"; //Add to fault msg.Properties.Add(HttpResponseMessageProperty.Name, rmp); }
-21702893 0 Have you tried unicode notation \u2014
?
Reference: How to convert a string with Unicode encoding to a string of letters
-1580464 0 Accessing the viewstate of a child controlI want to extract information in the viewstate of a child control. This control belongs to a third party and i do not have access to the source code. Is this possible?
-37874837 0What you want to do is sort an array, whose elements are hash, based on the hash's "code" value.
entries.sort { |a, b| a["code"] <=> b["code"] }
And also, I would suggest you do this in your controller instead of view.
EDIT:
Or you could do sort the tag first, then mapping them into an Array
Ci::Canonical::Language::Tag.sort_by do |a, b| a.code <=> b.code end.map do |tag| { "code" => tag.code, "description" => tag.description, "ordinal" => tag.value, } end
-11526627 0 bounding box of n glyphs, given individual bboxes and advances For specific reasons, I'm implementing my own font rendering, and an algorithm to compute the bounding box of a text by using bounding boxes of single glyphs, together with the respective advance, is needed. For clarification see this illustration:
For every of these N glyphs is given the relative bbox relative to the origin (xmin, xmax, ymin, ymax), and the advance (pseudocode):
int xmin[N], xmax[N], ymin[N], ymax[N], adv[N];
I will give the answer myself if noone bites.
-3605118 0try this...
select p.*, c.category_id, c.category_name, pcm.quantity from products p inner join product_categories_map pcm on p.product_id = pcm.product_id inner join categories c on pcm.category_id = c.category_id where c.code = 'something' order by p.product_id, c.category_id;
-11559072 0 XamlParseException - Image Pixels Manipulation with WPF C# / Kinect I want to use this code to access the image pixels to be used with my Kinect code.. so i can replace the depth bits with the Image bits, so i created a WPF application and As soon as i run my code, i get this exception (it doesnt happen on a Console application) but i need this to run as a WPF application since . . i intend to use it with Kinect
XamlParseException
'The invocation of the constructor on type 'pixelManipulation.MainWindow' that matches the specified binding constraints threw an exception.' Line number '3' and line position '9'.
Here is the code:
public partial class MainWindow : Window { System.Drawing.Bitmap b = new System.Drawing.Bitmap(@"autumn_scene.jpg"); public MainWindow() { InitializeComponent(); doSomethingWithBitmapFast(b); } public static void doSomethingWithBitmapFast(System.Drawing.Bitmap bmp) { Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height); System.Drawing.Imaging.BitmapData bmpData = bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly, bmp.PixelFormat); IntPtr ptr = bmpData.Scan0; int bytes = bmpData.Stride * bmp.Height; byte[] rgbValues = new byte[bytes]; System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes); byte red = 0; byte green = 0; byte blue = 0; for (int x = 0; x < bmp.Width; x++) { for (int y = 0; y < bmp.Height; y++) { //See the link above for an explanation //of this calculation (assumes 24bppRgb format) int position = (y * bmpData.Stride) + (x * 3); blue = rgbValues[position]; green = rgbValues[position + 1]; red = rgbValues[position + 2]; Console.WriteLine("Fast: " + red + " " + green + " " + blue); } } bmp.UnlockBits(bmpData); } } }
-10217562 0 Theres no formal difference between 'Text classification' and 'Sentence classification'. After all, a sentence is a type of text. But generally, when people talk about text classification, IMHO they mean larger units of text such as an essay, review or speech. Classifying a politician's speech into democrat or republican is a lot easier than classifying a tweet. When you have a lot of text per instance, you don't need to squeeze each training instance for all the information it can give you and get pretty good performance out a bag-of-words naive-bayes model.
Basically you might not get the required performance numbers if you throw off-the-shelf weka classifiers at a corpora of sentences. You might have to augment the data in the sentence with POS tags, parse trees, word ordering, ngrams, etc. Also get any related metadata such as creation time, creation location, attributes of sentence author, etc. Obviously all of this depends on what exactly are you trying to classify.. the features that will work out for you need to be intuitively meaningful to the problem at hand.
-21053553 0In lcmm(*range(1,5))
you're unpacking the iterable range(1, 5)
with *
so you're actually calling lcmm(1, 2, 3, 4)
. In other words, there are five arguments that don't have names but they're in order and they're passed in those positions. In the function def lcmm(*args):
the *
captures the positional arguments into args
. This means args
gets the value (1, 2, 3, 4)
. That explains why you're getting the same as reduce(lcm, range(1,5))
because that's the same as reduce(lcm, args)
when args = (1, 2, 3, 4)
.
When you're calling lcmm(range(1,5))
it means you're passing [1, 2, 3, 4]
as your argument. This is the only positional argument so at def lcmm(*args):
the value of *args
still captures all positional arguments. But because there's only one positional arguments the value of args
becomes ([1, 2, 3, 4],)
. That's a tuple with one value in it, namely [1, 2, 3, 4]
. This gives you a different result when lcm
computes the return value.
If they are daily returns and you want a cumulative return, surely you must want a daily compounded number?
df['perc_ret'] = (1 + df.Daily_rets).cumprod() - 1 >>> df Poloniex_DOGE_BTC Poloniex_XMR_BTC Daily_rets perc_ret 172 0.006085 -0.000839 0.003309 0.003309 173 0.006229 0.002111 0.005135 0.008461 174 0.000000 -0.001651 0.004203 0.012700 175 0.000000 0.007743 0.005313 0.018080 176 0.000000 -0.001013 -0.003466 0.014551 177 0.000000 -0.000550 0.000772 0.015335 178 0.000000 -0.009864 0.001764 0.017126
-36120660 1 python 3.5 pass object from one class to another I am trying to figure out how to pass data from one class into another. My knowledge of python is very limited and the code I am using has been taken from examples on this site.
I am trying to pass the User name from "UserNamePage" class into "WelcomePage" class. Can someone please show me how to achieve this. I will be adding more pages and I will need to pass data between the different pages
Below is the full code - as mentioned above most of this code has come from other examples and I am using these examples to learn from.
import tkinter as tk from tkinter import * from tkinter import ttk from tkinter import messagebox import datetime import re def Chk_String(mystring): Allowed_Chars = re.compile('[a-zA-Z_-]+$') return Allowed_Chars.match(mystring) def FnChkLogin(Page): booAllFieldsCorrect = False; myFName = Page.FName.get() myFName = myFName.replace(" ", "") myLName = Page.LName.get() myLName = myLName.replace(" ", "") if myFName == "": messagebox.showinfo('Login Ifo is Missing', "Please type in your First Name") elif not Chk_String(myFName): messagebox.showinfo('First Name Error:', "Please only use Leter or - or _") elif myLName == "": messagebox.showinfo('Login Info is Missing', "Please type in your Last Name") elif not Chk_String(myLName): messagebox.showinfo('Last Name Error:', "Please only use Leter or - or _") else: booAllFieldsCorrect = True; if booAllFieldsCorrect == True: app.geometry("400x200") app.title("Welcome Screen") PageController.show_frame(app,"WelcomePage") def FnAddButton(Page,Name,Label,Width,X,Y,FnAction): Name = ttk.Button (Page, text=Label,width=int(Width),command=FnAction) Name.place(x=int(X),y=int(Y)) class PageController(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) container = tk.Frame(self) container.pack(side="top",fill="both",expand="True") container.grid_rowconfigure(0,weight=1) container.grid_columnconfigure(0,weight=1) self.frames={} for F in (UserNamePage,WelcomePage): page_name = F.__name__ frame = F(container,self) self.frames[page_name] = frame frame.grid(row=0,column=0,sticky="nsew") self.show_frame("UserNamePage") def show_frame(self,page_name): frame= self.frames[page_name] frame.tkraise() class UserNamePage(tk.Frame): def __init__(self,parent,controller): tk.Frame.__init__(self,parent) self.controller = controller lblFName = Label(self,text="First Name ",relief=GROOVE,width=12,anchor=E).place(x=50,y=50) lblLName = Label(self,text="Last Name ",relief=GROOVE,width=12,anchor=E).place(x=50,y=75) self.FName = StringVar() inputFName = Entry(self,textvariable=self.FName,width=25).place(x=142,y=50) self.LName = StringVar() inputLName = Entry(self,textvariable=self.LName,width=25).place(x=142,y=75) cmdContinue = ttk.Button (self, text='Continue',width=9,command=lambda:FnChkLogin(self)).place(x=320,y=70) class WelcomePage(tk.Frame): def __init__(self,parent,controller): tk.Frame.__init__(self,parent) self.controller = controller UserNamePageData = UserNamePage(parent,controller) UserFName = str(UserNamePageData.FName) UserLName = str(UserNamePageData.LName) strWelcome = "Welcome " + UserFName + " " + UserLName lblWelcome = Label(self,text=strWelcome,relief=FLAT,width=50,anchor=W).place(x=25,y=25) if __name__ == "__main__": app = PageController() app.geometry("400x200") app.title("User Page") app.eval('tk::PlaceWindow %s center' % app.winfo_pathname(app.winfo_id())) app.mainloop()
-738357 0 Two issues I can see here:
The empty() and remove() methods of jQuery actually do quite a bit of work. See John Resig's JavaScript Function Call Profiling for why.
The other thing is that for large amounts of tabular data you might consider a datagrid library such as the excellent DataTables to load your data on the fly from the server, increasing the number of network calls, but decreasing the size of those calls. I had a very complicated table with 1500 rows that got quite slow, changing to the new AJAX based table made this same data seem rather fast.
My solution to this was to add an event handler in the test method, so that when the event is raised, the test method will create a CancelEventAgrs and set its Cancel to True/False.
Public Sub TestingMethod() Dim txt As TextLoader = Nothing AddHandler TextLoader.LoadingDoneEvent, (Sub(e As ComponentModel.CancelEventArgs) e.Cancel = True End Sub) txt = New TextLoader() txt.FireThisEvent() End Sub
-1095873 0 boost::reference_wrapper
(which is what boost::ref
returns) does not overload operator()
. You can use it with boost::bind
, which has special treating for it (not using ref
would make bind
copy the provided function object).
But for_each
returns the function object it invokes the stuff on. So just do this
between_1_and_10 val; val.d = 4; val = for_each(lst.begin(), lst.end(), val); printf("rg");
It will call the stuff on the copied val
, and return the function object as it's after the last invocation.
Just to tell you where you might use boost::ref
, because you seem to misuse it. Imagine a template that takes its parameter by value, and calls another function:
void g(int &i) { i++; } template<typename T> void run_g(T t) { g(t); }
If you now want to call it with a variable, it will copy it. Often, that's a reasonable decision, for example if you want to pass data to a thread as start parameters, you could copy it out of your local function into the thread object. But sometimes, you could want not to copy it, but to actually pass a reference. This is where boost::reference_wrapper
helps. The following actually does what we expect, and outputs 1
:
int main() { int n = 0; run_g(boost::ref(n)); std::cout << n << std::endl; }
For binding arguments, a copy is a good default. It also easily makes arrays and functions decay to pointers (accepting by reference would make T
be possibly an array/function-type, and would cause some nasty problems).
I want to make an app, in which I want to take a picture and input x,y axis it will show me corresponding point pixel value from the captured picture .
I don't have any knowledge about image processing well . So, how can I do it ? help me .
-9255519 0Make sure the generated classes are put into the same package as those that declare the protected members. Specifying 'the classpath that it should end up in' shouldn't really come into it, unless it is caused by classloading issues.
-30840009 0 Java javac is not regonized as an internal or external commandI was just starting to learn basic java for I apparently need it to be able to code bukkit plugins for minecraft and I'm stuck on the following issue.
I have made the HelloWorldApp.java in the folder c/test but it wont do want its supposed to do. Any help would be good and please try to dumb down any coding, etc
This is how I invoked it:
C:\Users\Matthew\Desktop>cd C:\test C:\test>javac HelloWorldApp.java 'javac' is not recognized as an internal or external command, operable program or batch file. C:\test>
-9450859 0 I know you accept that but check this one also with less css:
.container { margin-left: 15px; width: 200px; background: #FFFFFF; border: 1px solid #CAD5E0; padding: 4px; position: relative; min-height: 200px; } .container:after { content: ''; display: block; position: absolute; top: 10px; right:-7px; width: 10px; height: 10px; background: #FFFFFF; border-right:1px solid #CAD5E0; border-bottom:1px solid #CAD5E0; -moz-transform:rotate(-45deg); -webkit-transform:rotate(-45deg); }
-18402555 0 Have a look at DBIx::Mint You will need to add a role to your Moo classes
with 'DBIx::Mint::Table';
And also write a schema file. This schema file should have all information on classes you're going to use (class-to-table mapping, relationship to other tables/classes). No need to write schema file for each Moo class.
-8523921 0Faux columns would work but if you're after a pure CSS method you can try equal height columns from www.ejeliot.com
http://jsfiddle.net/spacebeers/s8uLG/3/
You set your container up with overflow set to hidden, then on each div add negative margin-bottom and equal positive padding-bottom.
#container { overflow: hidden; } #container div { float: left; background: #ccc; width: 200px; margin-bottom: -2000px; padding-bottom: 2000px; } #container .col2 { background: #eee; } <div id="container"> <div> <p>Content 1</p> </div> <div class="col2"> <p>Content 2</p> <p>Content 2</p> <p>Content 2</p> <p>Content 2</p> </div> </div>
-29038271 0 As of right now, you cannot retrieve a permanent access token. You have 2 options that come close.
The first is to request a "refresh" token when using the standard OAuth flow. That's what you're doing by sending "duration" as "permanent" in your code. The refresh token can be used to automatically retrieve new 1 hour access tokens without user intervention; the only manual steps are on the initial retrieval of the refresh token.
The second alternative, which applies only when writing a script for personal use, is to use the password
grant type. The steps are described in more detail on reddit's "OAuth Quick Start" wiki page, but I'll summarize here:
https://www.reddit.com/api/v1/access_token
with POST parameters grant_type=password&username=<USERNAME>&password=<PASSWORD>
. Send your client ID and secret as HTTP basic authentication. <USERNAME>
must be registered as a developer of the OAuth 2 client ID you send.i want to add parameter for HTTP Request PUT on the body, but i only can do like this
http://localhost:9996/Events/employee/{id}.json?name={name}
so how to put name on body?
here my controller
public class EmployeeController implements ModelDriven<Object>{ private static final long serialVersionUID = 1L; private String id; private String name; private Object model; private EmployeeRepository employeeRepository = new EmployeeRepository(); //GET public HttpHeaders index() { model = employeeRepository.findAllEmployee(); return new DefaultHttpHeaders("index").disableCaching(); } // GET public HttpHeaders show() { model = employeeRepository.getEmployeeById(id); return new DefaultHttpHeaders("show").disableCaching(); } //POST public HttpHeaders create() { Integer empId = Integer.parseInt(id); Employee emp = new Employee(empId, name, "PQR"); employeeRepository.addEmployee(emp); model = employeeRepository.findAllEmployee(); return new DefaultHttpHeaders("create").disableCaching(); } //PUT public HttpHeaders update() { Integer empId = Integer.parseInt(id); Employee emp = new Employee(empId, name, "PQR"); employeeRepository.updateEmployee(emp); model = employeeRepository.findAllEmployee(); return new DefaultHttpHeaders("update").disableCaching(); } //DELETE public HttpHeaders destroy() { employeeRepository.deleteEmployee(id); model = employeeRepository.findAllEmployee(); return new DefaultHttpHeaders("destroy").disableCaching(); } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Object getModel() { return model; }
-1330927 0 Opinion Polling and PHP Okay, so I want to make a polling site but it doesn't work like a typical poll.
Here's how I would like mine to operate:
User registers and is sent confirmation email Once they confirm they can log in From there they get to one giant poll with several topics but apposed to choosing one topic, they would have 20 or so "tokens" where they may distribute them among each topic as desired. These users then save their votes, and it goes into a database where results can then be displayed. These 20 tokens would replenish once a week, or month, or bi-weekly or something.
This is the basic idea. I'm not asking if this is a good idea. I would just like to know if there is a poll plugin/add-on type thing that I can just install on my site that would support this or if this would have to be custom made?
Additional features on this site would be that there would be a different section, where users would vote on a typical poll. This poll would ask what topics should be added to the first main poll.
If a plugin exist that would support this could someone tell me or it.
Or if this were custom made. How intense would it be? I have a novice understanding of PHP and MySQL is this something I could do?
I appreciate the help,
Thanks
-35464022 0dt = as.data.table(DF) # or setDT to convert in place # cumulative mean, but without the date restriction dt[, rawAvgRets := cumsum(Return) / (1:.N), by = Ticker] # find the latest matching date using a rolling merge (assumes sorted dates) # if you run into > vs >= issues, adjust enter or exit date by a day dt[, avgRets := dt[dt, rawAvgRets, roll = TRUE, on = c('Ticker' = 'Ticker', 'Exit Date' = 'Enter Date')]] # Ticker Enter Date Exit Date Return rawAvgRets avgRets # 1: ABC 2005-02-08 2005-03-09 4.669 4.6690000 NA # 2: ABC 2005-02-23 2005-03-23 4.034 4.3515000 NA # 3: ABC 2005-06-07 2005-07-06 3.796 4.1663333 4.3515000 # 4: ABC 2005-06-08 2005-07-07 -4.059 2.1100000 4.3515000 # 5: ABC 2005-08-16 2005-09-14 -11.168 -0.5456000 2.1100000 # 6: ABC 2005-09-07 2005-10-05 -0.496 -0.5373333 2.1100000 # 7: ABC 2005-11-15 2005-12-14 -3.597 -0.9744286 -0.5373333 # 8: ABC 2005-11-17 2005-12-16 3.450 -0.4213750 -0.5373333 # 9: ABC 2005-12-06 2006-01-05 -4.428 -0.8665556 -0.5373333 #10: ABC 2005-12-23 2006-01-25 1.914 -0.5885000 -0.4213750 #11: ABC 2006-02-09 2006-03-10 3.577 -0.2098182 -0.5885000 #12: ABC 2006-02-10 2006-03-13 4.000 0.1410000 -0.5885000 #13: ABC 2006-02-15 2006-03-16 8.451 0.7802308 -0.5885000 #14: ABC 2006-02-22 2006-03-22 5.521 1.1188571 -0.5885000 #15: ABC 2006-05-01 2006-05-30 10.324 1.7325333 1.1188571 #16: XYZ 2005-02-22 2005-03-22 3.104 3.1040000 NA #17: XYZ 2005-02-28 2005-03-29 0.787 1.9455000 NA #18: XYZ 2005-03-01 2005-03-30 -3.407 0.1613333 NA #19: XYZ 2005-03-03 2005-04-01 -1.441 -0.2392500 NA #20: XYZ 2005-03-04 2005-04-04 -4.157 -1.0228000 NA #21: XYZ 2005-03-11 2005-04-11 4.343 -0.1285000 NA #22: XYZ 2005-03-15 2005-04-13 2.827 0.2937143 NA #23: XYZ 2005-04-04 2005-05-02 0.425 0.3101250 -1.0228000 #24: XYZ 2005-04-05 2005-05-03 -1.370 0.1234444 -1.0228000 #25: XYZ 2005-04-15 2005-05-13 -3.175 -0.2064000 0.2937143 #26: XYZ 2005-04-22 2005-05-20 -11.027 -1.1900909 0.2937143 #27: XYZ 2005-04-28 2005-05-26 8.144 -0.4122500 0.2937143 # Ticker Enter Date Exit Date Return rawAvgRets avgRets
-33837904 0 Re-read the $set
documentation https://docs.mongodb.org/v3.0/reference/operator/update/set/ It specifically says it will replace what is there. So it doesn't care if a document exists or not that's why it doesn't return the error. you need additional operators to reject the query if it exists and is the same.
edit/update to below comment
You have to trigger the error in order to know if the DB as the collection already and if it's up to date. So an additional operator is required to check if the collection found already has the updated information. MongoDB uses operators represented with $
so $gt or $lt or $nor
(greater than , less than, Select everything but this) there's more but i'll let you explore the possibilities. https://docs.mongodb.org/v3.0/reference/operator/query/nor/
this line needs to trigger the error based on your expressions and operators. when you get that working don't just throw the error allow the program to continue to the next because this error isn't meant to break (throw) on that error it's only there to tell you hey the DB has this and it's updated, and on error will let you know nothing was done.
collection.updateOne(query, {"$set": data},{w: "majority"},function (err,result){ console.error(err);console.log(result); });
I have a Rails 3.1 application with an usual file layout. Heroku detects it as Ruby/Rack rather than Ruby/Rails. assets:precompile
isn't run, so pages that require them fail with a javascript error.
What do I need in my file structure to trick Heroku into running the precompile task? Or, can I configure a command to run during slug compilation?
-13150911 0This just happened to me. I reclone the repository in a new folder and move my latest changes over manually. Low tech but works every time. Hopefully you can remember your last changes.
-23328499 0For sorting numbers you can use counting sort algorithm: you have numbers of limited range, from 0 to 999. So, you can count how many times each number occurred in input file:
int[] count = new int[1000]; //depending of scope, maybe you need to fill array with zeroes ... int number = ...;//read number from file; count[number]++;
Now, in order to output it as sorted, you just need two loops like this:
for (int i = 0; i < 1000; ++i) { for (int j = 0; j < count[i]; ++j) { System.out.println(i); } }
I wrote this just to make sure idea is clear, although your task doesn't require to output them all. Now, let's imagine you read these two numbers;
int start, finish = 0; //value read from input
We gonna modify the loops above like this:
int counter = 0; for (int i = 0; i < 1000; ++i) { for (int j = 0; j < count[i]; ++j) { if ((counter >= start) && (counter < finish)) {//or maybe <=, depending on what exactly do you need System.out.println(i); } counter++; if (counter > finish) { //we finished, further iterations are waste of CPU time break(2); } } }
This method is not optimal, but easy to understand and implement. For more fast solutions, you may want to get rid of inner loop, replacing it with logic to add count[i]
to counter
at once and detecting moment when we need to start output.
From terminal:
sudo service mysqld start
Error show that the mysql server is not running on your ubuntu machine.
-32151141 0 WebStorm+Typescript: How to use without reference path?In Visual Studio, it's possible to use internal modules without having to include /// <reference path="..." />
tags.
How can one accomplish the same in WebStorm 10?
Another question, how can I get WebStorm to import the typings to a project? WebStorm 10 puts typings in the cache folder.
-17623882 0You need to build the options in the case statement and then execute wc
:
# Set WC_OPTS to empty string WC_OPTS=(); while getopts lwc choice do case $choice in l) WC_OPTS+='-l';; w) WC_OPTS+='-w';; c) WC_OPTS+='-c';; ?) echo wrong option. esac done # Call wc with the options shift $((OPTIND-1)) wc "${WC_OPTS[@]}" "$@"
-19506163 0 How to correctly chain conditional(?) promises with Q.js I've still not quite got a complete understanding of promises so apologies if this is a simple misunderstanding.
I have a function for deleting an item on a page but I have a specific behaviour depending on the state of the page. Psuedo code-wise it's something like this:
Does the page have changes? If yes - prompt to save changes first If yes - save changes If no - exit function If no - continue Prompt to confirm delete If yes - delete item and reload data If no - exit function
Hopefully that makes sense. Essentially if there are changes, the data must be saved first. Then if the data has been saved, or if there were no changes to begin with, prompt the user to confirm deletion. The problem is I'm using durandal and breeze, and I can't seem to chain the promises they return together correctly.
My function currently looks like this, which I know is wrong, but I'm struggling to work out where to fix it.
if (this.hasChanges()) { app.showMessage('Changes must be saved before removing external accounts. Would you like to save your changes now?', 'Unsaved Changes...', ['Yes', 'No']) .then(function (selectedOption) { if (selectedOption === 'Yes') { return this.save(); } else { Q.resolve() } }); } app.showMessage('Are you sure you want to delete this item?', 'Delete?', ['Yes', 'No']) .then(function (selectedOption) { if (selectedOption === 'Yes') { item.entityAspect.setDeleted(); datacontext.saveChanges() .then(function () { logger.logNotificationInfo('Item deleted.', '', router.activeInstruction().config.moduleId); Q.resolve(this.refresh(true)); }.bind(this)); } }.bind(this));
The app.showMessage call from durandal returns a promise, then the this.save returns a promise, and finally the this.refresh also returns a promise.
So I guess I need to check the hasChanges, then if necessary call save, and resolve it. Then after that conditional section has finished resolving, call the second prompt, and then resolve all the promises within that.
I'm sorry I don't think this is super clear, but that's also I think coming from the fact I'm not completely following the chains here.
Any help much appreciated! Thanks.
-6968927 0Basically, you are temporarily assigning to the object reference to variable pi
. The variable is overwritten, but the object is not. It safely gets added to your list for any future use.
So i have an problem with method of Canvas.DrawBitmap(), that draws unexpected result.
Lets see my example:
Source image
I have two cases(just for test):
i'm doing this:
//source imageview Source.SetImageResource(Resource.Drawable.lena30); //bitmap bt = ((BitmapDrawable)Source.Drawable).Bitmap.Copy(Bitmap.Config.Argb8888, true); //second imageview, where i fill result Draw.SetImageBitmap(bt); can = new Canvas(bt); Paint paint = new Paint(); paint.Color = Color.Red; paint.SetStyle(Paint.Style.Fill); //draw Red Rect with 1/4 size and locate Top.Left can.DrawRect(0,0,bt.Width/2,bt.Height/2,paint); //redraw new bitmap(all subset) and locate to Bottom.Right with 1/4 size can.DrawBitmap(bt, null, new Rect(bt.Width/2, bt.Height / 2, bt.Width, bt.Height), null);
same,but getting now part of bitmap(not full subset of bitmap):
//source imageview Source.SetImageResource(Resource.Drawable.lena30); //bitmap bt = ((BitmapDrawable)Source.Drawable).Bitmap.Copy(Bitmap.Config.Argb8888, true); //second imageview, where i fill result Draw.SetImageBitmap(bt); can = new Canvas(bt); Paint paint = new Paint(); paint.Color = Color.Red; paint.SetStyle(Paint.Style.Fill); //draw Red Rect with 1/4 size and locate Top.Left can.DrawRect(0,0,bt.Width/2,bt.Height/2,paint); //redraw new bitmap(not full,only part of Source Rectangle) and locate to Bottom.Right with 1/4 size can.DrawBitmap(bt, new Rect(bt.Width/2,0,bt.Width,bt.Height), new Rect(bt.Width/2, bt.Height / 2, bt.Width, bt.Height), null);
So i cant understand,why that happens?(Why image no scaling to fit size and duplicate Rectangles!?).
Any ideas? Thanks!
C allows you to not specify any arguments in a declaration (function prototype), and the compiler will parse it as the function takes an unknown number of unspecified arguments. In C++ a function declaration without arguments means that the function doesn't take any arguments, it's the same as using the argument void
. You need to specify the arguments in the declaration.
Which leads to your error: It's impossible to answer why you get the errors when you add the arguments as the question doesn't show more context, but an educated guess is that you miss some header file. Do you include the header file where XDR
is declared? Do you include <stdio.h>
(for FILE
)?
I've looped through an document.form.element the names are constructed into an array name like so:
Some of the names of they keys are like so in JSON:
{ data[name]: "foo", data[address]: "baz drive", data[city]: "Dallas", data[state]: "Texas", data[phone]: "555-1212" }
Is there a way to convert it to this with Pure JavaScript (and without frameworks like jQuery) without using eval
?:
{ data: { name: "foo", address: "baz drive", city: "Dallas", state: "Texas", phone: "555-1212" } }
<script type="javascript"> var o = { data[name]: "foo", data[address]: "baz drive", data[city]: "Dallas", data[state]: "Texas", data[phone]: "555-1212" } var temp = []; for (key in o) { temp[JSON.parse(key)] = o; } </script>
Fiddle is here: http://jsfiddle.net/chrisjlee/medbzv9a/
Or is this not totally possible?
-4361522 0 iPhone - sending message to deallocated instance - why?I keep geting this error and I just don't understand why. I am new to this so maybe someone can point out the problem.
The error :
-[ShareXML release]: message sent to deallocated instance
The code:
if(self.share){ NSLog(@"SHARE ALREADY EXISTS"); [self.share startSomeProcess]; }else{ NSLog(@"share xml"); ShareXML *shareXML = [[ShareXML alloc] init]; self.share = shareXML; self.share.delegate = self; [self.share startSomeProcess]; NSLog(@"SHARE XML RELEASED"); [shareXML release]; }
ShareXML is an NSObject. I use almost identical code on a view controller and it works. Thanks!
-13620904 0It's because you are using Dictionary.prototype
on your methods. Replace them with this
and it will work:
this.put = function() this.firstKey = function() this.lastKey = function() ...
Using the this
keyword, you are assigning methods to your Dictionary
[sort of] class. You are simply making the functions public. If you look at your functions such as removeItemArray()
then these are private and only accessible from within the object.
Prototype works differently. This is a nice quote from an answer to this question about prototype:
The protoype is the base that will be used to construct all new instances and also, will modify dinamically all already constructed objects because in Javascript objects retain a pointer to the prototype
The purpose of prototype is to give the ability to add methods to an object at runtime. This may seem somewhat of an alien concept if you're coming from classical OOP languages, where you traditionally pre-define a class and its methods.
Have a look at the other answers in that question which explain prototype really well.
-34251378 0As the error says, you cannot view the keys of a boolean, aka, True.viewkeys() does not work. Change your default dictionary's to be empty, leaving:
def merge_many_dics(dic1,dic2,dic3={},dic4={},dic5={},dic6={},dic7={},dic8={},dic9={},dic10={}): """ Merging up to 10 dictionaries with same keys and different values :return: a dictionary containing the common dates as keys and both values as values """ manydics = {} for k in dic1.viewkeys() & dic2.viewkeys() & dic3.viewkeys() & dic4.viewkeys() & dic5.viewkeys() & dic6.viewkeys()\ & dic7.viewkeys() & dic8.viewkeys() & dic9.viewkeys() & dic10.viewkeys(): manydics[k] = (dic1[k], dic2[k],dic3[k],dic4[k],dic5[k],dic6[k],dic7[k],dic8[k],dic9[k],dic10[k]) return manydics
Here is an implementation in which you create a list for every key and add each item, I'm sure it can be optimized a lot more, but it's very readable:
def merge_many_dicts(*args): """ Merging all dictionaries suposing all dictionaries share keys :return: a dictionary containing the common dates as keys and both values as values """ manydicts = {} for k in args: for key in k.iterkeys(): manydicts[key] = [] for k in args: for key, value in k.iteritems(): manydicts[key].append(value) return manydicts
-26633832 0 A pointer is not a variable. A pointer is a value.
A variable, in C, designates a storage location, and a value can be stored in that location. Thus, if you have a variable a
declared with int a
, then a
is a variable in which an integer value can be stored. If you have a variable int *x
, then x
is a variable in which a pointer to an integer value can be stored.
The address of a storage location can be obtained using the &
operator. E.g., &a
is the address of the storage location designated by a
, or the address of a
, and can be stored in (among other things) a variable of the corresponding type. Thus you can have:
int a = 42; /* a is a variable of type int, and has value 42 */ int* x = &a; /* x is a variable of type int*, and has value &a */
Although analogies in programming are often dangerous, you might think of things like page numbers in a book. The page number of a page is not the same thing as the page, but page numbers can still be written down on pages. E.g., the table of contents page has lots of page numbers written down on it. Thus:
actual_page p = ...; /* a page structure */ page_number n = &p; /* a page number */
-9585338 0 You seem to have two questions.
The second is the more specific question regarding AjaxControlToolkit.dll. For that, take a look at ERROR Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies.
As to your original question, as long as you only need to deploy the DLL (in other words, you don't need to run an install program, modify the web.config, etc), the way to go is to place your DLL into your WSP solution package. This is easier than ever with Visual Studio 2010. For more information, see How to: Add and Remove Additional Assemblies and Including additional assemblies in the WSP with Visual Studio SharePoint development tools.
-8995385 0 "Symbol 'cin' can not be resolved" error in Eclipse on OS XI am just beginning a C++ class and I am working on our first homework. I am using Eclipse and it's giving me some problems. Here is my code:
#include <iostream> using namespace std; int main() { int first, second; cout<< "Type the first number and press enter.\n"; cin>>first; cout << "Type the second number and press enter.\n"; cin>>second; cout<<"The sum of "<<first<<" and "<<second<<" is "<<(first+second)<<", and the product is "<<(first*second)<<endl; }
I am fairly sure that the code is good and should compile and run, but Eclipse is giving me a bunch of errors. For each of the cin and cout statements, I am getting an error which says: "Symbol 'cin'/'cout' could not be resolved." I am also getting an error which says: "symbol(s) not found for architecture x86_64."
I am running Mac OS X v10.7.2, GNU Make 3.81, and i686-apple-darwin11-llvm-g++-4.2 (GCC) 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.1.00).
Like I said, I'm new, so if you need more info, just let me know. Thank you.
-12300121 0Use a centralized logger and disable output when you're taking user input.
-3278280 0 PHP: Is it programatically possible to append iterator value to array key name in loop?I have a multidimensional array object, and in a loop I would like to append an iterator to the key and obtain the value. Sample code for demonstration:
$array_object->example1 = 1; $array_object->example2 = 2; $i = 1; while ($i <= 2) { echo ($array_object->example . $i); //this does not work //how to accomplish same? $i++ }
Thank you in advance for any suggestions.
-38367304 0 Confusion over behavior of Publish().Refcount()I've got a simple program here that displays the number of letters in various words. It works as expected.
static void Main(string[] args) { var word = new Subject<string>(); var wordPub = word.Publish().RefCount(); var length = word.Select(i => i.Length); var report = wordPub .GroupJoin(length, s => wordPub, s => Observable.Empty<int>(), (w, a) => new { Word = w, Lengths = a }) .SelectMany(i => i.Lengths.Select(j => new { Word = i.Word, Length = j })); report.Subscribe(i => Console.WriteLine($"{i.Word} {i.Length}")); word.OnNext("Apple"); word.OnNext("Banana"); word.OnNext("Cat"); word.OnNext("Donkey"); word.OnNext("Elephant"); word.OnNext("Zebra"); Console.ReadLine(); }
And the output is:
Apple 5 Banana 6 Cat 3 Donkey 6 Elephant 8 Zebra 5
I used the Publish().RefCount() because "wordpub" is included in "report" twice. Without it, when a word is emitted first one part of the report would get notified by a callback, and then the other part of report would be notified, double the notifications. That is kindof what happens; the output ends up having 11 items rather than 6. At least that is what I think is going on. I think of using Publish().RefCount() in this situation as simultaneously updating both parts of the report.
However if I change the length function to ALSO use the published source like this:
var length = wordPub.Select(i => i.Length);
Then the output is this:
Apple 5 Apple 6 Banana 6 Cat 3 Banana 3 Cat 6 Donkey 6 Elephant 8 Donkey 8 Elephant 5 Zebra 5
Why can't the length function also use the same published source?
-37337203 0update may 27:
we just released an update (version 9.0.1
) to fix the incompatibility I mentioned in my first edit.
Please update your dependencies and let us know if this is still an issue.
Thanks!
original answer May 20:
The issue you are experiencing is due to an incompatibility between
play-services / firebase sdk v9.0.0
and com.android.support:appcompat-v7 >= 24
(the version released with android-N sdk)
You should be able to fix it by targeting an earlier version of the support library. Like:
compile 'com.android.support:appcompat-v7:23.4.0'
-17113057 0 Generate Pinterest Share Button That Specifies URL I am trying to create a "pinterest share" button, but am running into a snag.
Currently, I have the pinterest button (generated from their Widget Builder) appearing in a Lightbox. (For certain reasons, it must appear this way.)
The issue is the Lightbox code has direct linking on it, so the code for the lightbox window is something like: www.domain.com/#/social/4
Pinterest is picking up that URL (which has no images since it's just the lightbox) instead of the URL for the main page (www.domain.com).
Does anyone know how I can specify the exact URL to share via the pinterest button?
I have read some posts that said doing this would work:
<a href="http://pinterest.com/pin/create/button/?url=http://www.domain.com" class="pin-it-button" count-layout="none"><img src="//assets.pinterest.com/images/PinExt.png" alt="Pin it" / ></a> <script type="text/javascript" src="http://assets.pinterest.com/js/pinit.js"></script>
However, specifying the URL does not seem to work at all. It appears to be totally ignored and has no impact.
Any ideas?
Thanks in advance!
-24680396 0I would up doing this in a snippet instead:
<?php //getgalleryAlbumCover $output = ''; $sql = "select * from modx_gallery_albums mga where mga.id = $id"; $album = $modx->query($sql); if (!is_object($album)) {return;} $data = $album->fetch(PDO::FETCH_ASSOC); // just in case ;) $modx->toPlaceholders($data); $output = $data['cover_filename']; return $output;
-16518605 0 Paypal Overage Pricing I'm using Paypal website payment subscription. I want to charge overage price from my customers when it's needed. Is that possible? I don't want to use express checkout or double modify existing subscription.
For example, I'm charging $20 each month. For only current month, I want to be able to charge $22. Still my regular payment is $20. Do I need any permission or do I need to take my customers' credit card info and use payflow sdk?
Any solution?
-10376877 0The member function public String[] getCost()
returns null and not an actual cost value. Therefore, double[] doubleRunningCosts = new double[RunningCosts.length];
at line 31 will fail, because RunningCosts is null.
Simply use the filter()
method of the jQuery object:
var active = c.filter('.active');
Reference:
-4883990 0By looking at your loops you don't seem that you are visiting any cell more than once. Wouldn't a simple if statement work here ?
if(Cells(i,j).Value = ',') Cells(i,j).Value = '.' Elsif(Cells(i,j).Value = '.') Cells(i,j).Value = ',') End
-19221669 0 Is it possible to set a border to overlay (like in photoshop) I am having a quite exotic question: I am currently working on a "borderless" WPF Application. I successfully removed the standard windows window controls and added my own. Now I wanted to add a border to the programm. But I don't want the border to have specifc color, I want it to be in some kind of overlay mode like when you set a layer in photoshop to overlay. You can see what I mean in an example:
I really want it to look like on the left. But unfortunately I really have no idea how. Basically what the overlay does is that it takes the background color and it makes it a bit darker. Do you have any suggestions what I could do?
Edit: Here is a better picture of the effect
Edit2 : So, as a short explanation because it may not be as clear as I have hoped: I am not talking about a semi-transparency. I know how to do that. The right box in both images uses that. It has a black-semitransparent look. While on the left I set the border to "overlay" mode. As you can see it gets darker but also a bit stronger in color.
-7043639 0 Operator 'op ' cannot be applied to operands of type 'dynamic' and 'lambda expression'I can't seem to apply binary operations to lambda expressions, delegates and method groups.
dynamic MyObject = new MyDynamicClass(); MyObject >>= () => 1 + 1;
The second line gives me error: Operator '>>=' cannot be applied to operands of type 'dynamic' and 'lambda expression'
Why?
Isn't the operator functionality determined by my custom TryBinaryOperation
override?
This should be doable in O(n) time... A hash map is usually implemented as a large bucket array, the bucket's size is (usually) directly proportional to the size of the hash map. In order to retrieve the key set, the bucket must be iterated through, and for each set item, the key must be retrieved (either through an intermediate collection or an iterator with direct access to the bucket)...
**EDIT: As others have pointed out, the actual keyset() method will run in O(1) time, however, iterating over the keyset or transferring it to a dedicated collection will be an O(n) operation. Not quite sure which one you are looking for **
-23574165 0Putting @j08291's comment into an answer.
You can only have one element with an ID. Change them to classes, and you'll need to do some tree traversing to get the reference to the correct form elements to show and hide http://jsfiddle.net/pcUBr/
Also, your CSS class names (show,hide
) aren't very semantic. Try the following
CSS
.question_form { display: none; } .question_form.current { display: inline; }
JS
$(".button").click(function(e){ var form = $(e.target).closest('form'); form.toggleClass("current"); form.next().toggleClass("current"); });
HTML
<form class="question_form current" > <img src="image1.png" class="current_image" alt=""> <h3 class="question"> Question 1: </h3> <hr> <input type="radio" name="q1" value="q1-a">Answer 1 <br> <input type="radio" name="q1" value="q1-b">Answer 2 <br> <input type="radio" name="q1" value="q1-c">Answer 3 <br> <br> <input name="button" type="button" class="button" value="Next"> </form>
-25546664 0 You can use JQuery to toggle Menu http://jsfiddle.net/bLbdavqu/8/
Just Change the CSS of the ul.
Hide List- $( "#mylist" ).css("display","none");
Show List- $( "#mylist" ).css("display","block");
I'm following a Gif tutorial and created a custom class in my wear/java/com.example.marcus.prog
folder called 'GIFView', but I can't reference this class from my XML layout. I've tried all sorts of combinations but I keep getting two errors about not finding the class.
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.marcus.prog/com.example.marcus.prog.AttackScreen}: android.view.InflateException: Binary XML file line #20: Error inflating class com.example.marcus.prog.GIFView Caused by: java.lang.ClassNotFoundException: Didn't find class "com.example.marcus.prog.GIFView" on path: DexPathList[[zip file "/system/framework/com.google.android.wearable.jar", zip file "/data/app/com.example.marcus.prog-4/base.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]
My XML file looks like
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" tools:deviceIds="wear" android:orientation="vertical" > <prog.GIFView android:layout_width="wrap_content" android:layout_height="wrap_content" />
Thanks
-27641942 0This turned out to be a permissions issue on the updated html file. Went to file info and adjusted permissions to match the original html file and it worked.
-16316088 0I fixed my problem using a new function in my controller.
My controller:
$data['counts'] = $this->bedrijven_model->bedrijf_categorie();
My model:
function bedrijf_categorie() { $sql = " SELECT count(b.idbedrijven) as ItemCount, c.Categorie as Categorie FROM `bedrijven` b INNER JOIN `bedrijfcategorieen` bc ON bc.idbedrijven = b.idbedrijven INNER JOIN `categorieen` c ON c.idcategorieen = bc.idcategorieen GROUP BY c.idcategorieen "; $query = $this->db->query($sql); return $query->result_array(); }
my views:
<?php echo '<ul>'; foreach($counts as $count){ echo '<li>'; echo '<a href="'.base_url().'home/categorieen/'.$count['Categorie'].' ">' .$count['Categorie']. '</a>'; echo nbs(1); echo '('; echo $count['ItemCount']; echo ')'; echo '</li>'; } echo '</ul>'; ?>
Anyway. thanks people who helped.
-11515001 0 Android CookieSyncManagerAre the cookies kept persistent when we use this? Are the cookies still available even after the phone restarts? I am referring to this link: http://developer.android.com/reference/android/webkit/CookieSyncManager.html
Say we are using DefaultHttpClient, CookieSyncManager would know to grab the cookies or are there other commands then the ones in the link that we will still need to provoke? How do we get the cookies back?
-29140399 0 Yii2: Do DefaultValueValidator or FilterValidator influence other validation rules?Both validators are no real validators, rather they can change an attribute value. If such pseudo validators are used in model rules, do they have any effect on other real validators?
For example, when a default and a required validator are used for the same attribute, will the required validator never fail?
Or are there any precedences with such validators? Or is the order of the validation rules crucial?
-25469326 1 Delete "usr/lib/python2.7" byMistake, how to fix it?During editting the Django apps, I deleted the python2.7 folder in "usr/lib/python2.7" by mistake.
After that problem happened, I always got the msg as following when using :
Could not find platform independent libraries <prefix> Could not find platform dependent libraries <exec_prefix> Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>] ImportError: No module named site
--- os is Ubuntu12.04 ----
I have tried to refer to these pages:
and also try to use
sudo apt-get install --reinstall
to reinstall the python2.7.8 version
My PYTHONPATH now looks like
PYTHONDIR= usr/local/lib/python2.7,
PYTHONHOME= usr/local/lib/python2.7,
PYTHONPATH=
but I still get "ImportError: No module named site" msg
If I try to type
Import sys
I would get the msg "import: unable to open image `sys': @ error/blob.c/OpenBlob/2587."
Many thanks,
-12587271 0 re-initiate a jQuery plug-in after dynamically inserting contentI have a jQuery tabs plug-in which works well... However I have a lightbox (also dynamicaly generated) that allows users to choose content which then gets shown in tabs.
This works fine if the user chooses content, leaves the page and comes back.. however i want the tabs to work as soon as the user finishes selecting content.
I have tried the usual .delegate() tags, but which event do I attach them to? I have tried doing it on the 'save' button on the lightbox but as this is also dynamically generated it doesn't appear to work.
Any ideas?
Thanks!
-32244937 0There is a problem with different number of arguments.
The simplest way is to use data type for "parameters". And to use data type for "result".
And to use just pattern-matching instead of class.
Something like that:
type GreenMix a = (Scalar a, Complex (Scalar a)) data ResultType a = Clomb (Scalar a) | Lrenz (Complex (Scalar a)) | Mix (GreenMix a) data Gauge a = Gauge1 (Scalar a) (Scalar a) | Gauge2 (Scalar a) (Scalar a) (Scalar a) greenF :: (Scalar a -> a) -> (Scalar a -> a) -> Gauge a -> Result a greenF f1 f2 (Gauge1 g1 g2) = Clomb $ greenF_Gauge1 f1 f2 g1 g2 greenF f1 f2 (Gauge2 g1 g2 g3) = Lrenz $ greenF_Gauge2 f1 f2 g1 g2 g3
-40865113 0 I think of file descriptors as (indirect, higher-level) pointers to opaque file objects maintained by the kernel.
Normally, when you deal with objects maintained by a library, you pass to the library pointers to objects that you're not supposed to dereference and manipulate yourself.
For kernel objects, this it's not just that you're not supposed to manipulate them yourself -- you literally can't because they live in a different address space that's not at all accessible to you. And because they live in a different address space, pointers wouldn't be a meaningful way of referring to them.
You need a token or handle which the kernel would internally resolve to a pointer that's meaningful in the kernel address space. File descriptors are such tokens in integer form.
For the kernel:
your_process_id + your_file_descriptor => kernels_file_object_pointer
(or an EBADF error if a given filedescriptor may not be resolved to a file object pointer for the given process)
-32341235 0No, there is no such functionality. Instead of managing cluster with advisory messages, kafka relies on zookeeper and whenever some action is required (e.g. delete topic, perform rebalance) it creates appropriate "command" node in zk.
Having said this, kafka exposes a lot of it's underpinnings as JMX accessible statistics.
-21073120 0In general you should avoid performing multiple calls with aov
and rather use a mixed effects linear model.
You can find several examples in this post by Paul Gribble
I often use the nlme
package, such as:
require(nlme) model <- lme(dv ~ myfactor, random = ~1|subject/myfactor, data=mydata)
Depending on the situation you may run in more complex situations, I would suggest to have a look at the very clear book by Julian Faraway "Extending the Linear Model with R: Generalized Linear, Mixed Effects and Nonparametric Regression Models".
Also, you may want to ask on CrossValidated if you have more specific statistical questions.
-16359919 0That's what some browsers do to present a decent default look on some tags. Just override them in your stylesheet once you detect them.
-16198579 0I am in the process of writing my first REST service, so I am no expert, but in my opinion, I think it would be best to use a GET request, since that is exactly what you are doing -- getting data from the server. This will make it easier for other developers to support the app, instead of trying to figure out why you used PUT for a basic data retrieval.
If possible, I suggest that you try casting the UserSearchDTO XML as a string on the client and passing it to the GetUsers method as a string, then load the string into an XmlDocument() on the server and parse it into the DTO. Then your method signature would look like:
MyResponse GetUsers(string userSearchXmlString, int pageno, int totalrecords);
-28705242 0 If you use copy-on-write collections it will work; however when you use list.iterator(), the returned Iterator will always reference the collection of elements as it was when ( as below ) list.iterator() was called, even if another thread modifies the collection. Any mutating methods called on a copy-on-write–based Iterator or ListIterator (such as add, set, or remove) will throw an UnsupportedOperationException.
import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; public class RemoveListElementDemo { private static final List<Integer> integerList; static { integerList = new CopyOnWriteArrayList<>(); integerList.add(1); integerList.add(2); integerList.add(3); } public static void remove(Integer remove) { for(Integer integer : integerList) { if(integer.equals(remove)) { integerList.remove(integer); } } } public static void main(String... args) { remove(Integer.valueOf(2)); Integer remove = Integer.valueOf(3); for(Integer integer : integerList) { if(integer.equals(remove)) { integerList.remove(integer); } } } }
-13413138 0 Like you said, after navigating away from original page you're losing track of what windows you may have opened.
As far as I can tell, there's no way to "regain" reference to that particular window. You may (using cookies, server side session or whatever) know that window was opened already, but you won't ever have a direct access to it from different page (even on the same domain). This kind of communication between already opened windows may be simulated with help of ajax and server side code, that would serve as agent when sharing some information between two windows. It's not an easy nor clean solution however.
-21148955 0Try this code:
# BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteCond %{THE_REQUEST} \s/+[?\s] RewriteRule /anmelden/ [L,R] RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress
-25767683 0 This is a shot in the dark, but try return false
after the trigger reset and the alertify success stuff.
you start your server but its bound to 127.0.0.1 / localhost IP so its only accessible from the VM
you need to start it using the IP of the VM or the 0.0.0.0 IP. something like this should work
php bin/console server:start 0.0.0.0:8000
-14966810 0 Provided that PreCalcCurrentMonth
is a Date variable, try something like this (untested):
mySQL = "DELETE * FROM [tblBillingData]" & _ "WHERE (((tblBillingData.[Billing Month]) > " & _ Format(PreCalcCurrentMonth,"\#mm\/dd\/yyyy\#") & _ "));" DoCmd.RunSQL mySQL
Format(PreCalcCurrentMonth,"\#mm\/dd\/yyyy\#")
ensures that your date is converted to a string in US date format #mm/dd/yyyy#, whatever your regional settings. # is the date separator.
The assignment is to create a struct array with 10 elements as "students" and each have a score and an ID. There are some things I am not allowed to change in the code (like anything in main).
#include <stdio.h> #include <stdlib.h> struct student* allocate(){ struct student* array = malloc(10 * sizeof(struct student)); return array; } void deallocate(struct student* stud){ int i = 0; for(;i<10;i++) free(&stud[i]); }
So this compiles fine and the rest of the code runs fine but then the core dumps when it gets to the free(). Also, this is the main that my professor gave me and told me not to change. There was no call to the deallocate function so now I am wondering if it automatically gets called when main is done or if he left it out by mistake. I added it in because I think that seems reasonable.
int main(){ struct student* stud = allocate(); generate(stud); output(stud); sort(stud); for(int i=0;i<10;i++){ printf("%d %d\n", stud[i].id,stud[i].score); } printf("Avg: %f \n", avg(stud)); printf("Min: %d \n", min(stud)); deallocate(stud); return 0; }
-8404170 0 Sure. In your click event, simply unbind the click event handler for that div. See updated fiddle here:
-33745378 0 R connection to Redshift using AWS driver doesn't work but does work with Postgre driverI am trying establish a connection to my redshift database after following the example provided by AWS https://blogs.aws.amazon.com/bigdata/post/Tx1G8828SPGX3PK/Connecting-R-with-Amazon-Redshift. However, I get errors when trying to establish the connection using their recommended driver. However, when I use the Postgre driver I can establish a connection to the redshift DB.
AWS says their driver is "optimized for performance and memory management", so I would rather use it. Can someone please review my code below, and let me know if they see something wrong? I suspect that I am not setting the URL up correctly, but not sure what I should be using instead? Thanks in advance for any help.
#' This code attempts to establish a connection to redshift database. It #' attempts to establish a connection using the suggested redshift but doesn't #' work. ## Clear up space and set working directory #Clear Variables rm(list=ls(all=TRUE)) gc() ## Libriries for analyis library(RJDBC) library(RPostgreSQL) #Create DBI driver for working with redshift driver directly # download Amazon Redshift JDBC driver download.file('http://s3.amazonaws.com/redshift-downloads/drivers/RedshiftJDBC41-1.1.9.1009.jar', 'RedshiftJDBC41-1.1.9.1009.jar') # connect to Amazon Redshift using specific driver driver_redshift <- JDBC("com.amazon.redshift.jdbc41.Driver", "RedshiftJDBC41-1.1.9.1009.jar", identifier.quote="`") ## Using postgre connection that works #postgre driver driver_postgre <- dbDriver("PostgreSQL") #establish connection conn_postgre <- dbConnect(driver_postgre, host="nhdev.c6htwjfdocsl.us-west-2.redshift.amazonaws.com", port="5439",dbname="dev", user="xxxx", password="xxxx") #list the tables available tables = dbListTables(conn_postgre) ## Use URL option to establish connection like the example on AWS website # url <- "<JDBCURL>:<PORT>/<DBNAME>?user=<USER>&password=<PW> # url <- "jdbc:redshift://demo.ckffhmu2rolb.eu-west-1.redshift.amazonaws.com # :5439/demo?user=XXX&password=XXX" #useses example from AWS instructions #url using my redshift database url <- "jdbc:redshift://nhdev.c6htwjfdocsl.us-west-2.redshift.amazonaws.com :5439/dev?user=xxxx&password=xxxx" #attempt connect but gives an error conn_redshift <- dbConnect(driver_redshift, url) #gives the following error: # Error in .jcall(drv@jdrv, "Ljava/sql/Connection;", "connect", as.character(url)[1], : # java.sql.SQLException: Error message not found: CONN_GENERAL_ERR. Can't find bundle for base name com.amazon.redshift.core.messages, locale en ## Similier to postgre example that works but doesn't work when using redshift specific driver #gives an error saying url is missing, but I am not sure which url to use? conn <- dbConnect(driver_redshift, host="nhdev.c6htwjfdocsl.us-west-2.redshift.amazonaws.com", port="5439",dbname="dev", user="xxxx", password="xxxx") # gives the following error: #Error in .jcall("java/sql/DriverManager", "Ljava/sql/Connection;", "getConnection", : # argument "url" is missing, with no default
-20635854 0 How to Add Data Labels in Google Chart I have created a bar chart using google spreadsheet. I just want to ask how I can put data labels (just like in Excel) to show the value of each bar. Is there a way to do that without using a script? Thank you
-11153960 0I was having the same issue of the whole list view highlighting, when using a color as the background. Curiously this only happened below api 11.
Solution was to use a solid shape drawable to wrap the colour:
list_selector_shaped_background_press.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android" > <solid android:color="@color/list_selector_pressed"/> </shape>
List_selector_background.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android" > <item android:state_window_focused="false" android:drawable="@android:color/transparent" /> <!-- Even though these two point to the same resource, have two states so the drawable will invalidate itself when coming out of pressed state. --> <item android:state_focused="true" android:state_enabled="false" android:state_pressed="true" android:drawable="@drawable/list_selector_background_disabled" /> <item android:state_focused="true" android:state_enabled="false" android:drawable="@drawable/list_selector_background_disabled" /> <!-- this has to be in a shaped drawable otherwise the whole list is highlighted selects --> <item android:state_focused="true" android:state_pressed="true" android:drawable="@drawable/list_selector_shaped_background_pressed" /> <item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/list_selector_shaped_background_pressed" /> <item android:state_focused="true" android:drawable="@drawable/list_selector_background_focus" /> </selector>
-3835087 0 Whenever you declare a variable in XSLT 1.0 without @select, but with some content template, the variable type will be of Result Tree Fragment. The variable holds the root node of this tree fragment.
So, with this:
<xsl:variable name="source"> <xsl:copy-of select="$currentPage" /> </xsl:variable>
You are declaring $source
as the root of a RTF containing the copy of the nodes (self and descendants) in $currentPage
node set.
You can't use /
step operator with RTF. That's why you are ussing node-set
extension function.
But, when you say:
node-set($source)/ancestor-or-self::*
This will be evaluate to an empty node set, because a root node hasn't ancestors an it's not an element.
EDIT: If you have two node sets, and you want to declare a variable with the content of one of the two node sets depending on some condition, you could use:
<xsl:variable name="current" select="umbraco.library:GetXmlNodeById($source)[$source > 0] |$currentPage[0 >= $source]" />
-2986624 0 Correct, it's still not kosher. It will cause warnings in many browsers about "mixing secure and insecure content."
-34738139 0 Dotnetopenauth oAuth 2.0 server example - how does it work?Can someone give me some help? I can't undestarnd how OAuth sample works.. and you?
I'm trying to understand the example of dotnetopenauth. I want to create my own oAuth 2.0 server and I'd like to study these examples.
If I run the OAuthConsumerWpf, I see a screen like this:
where, as you can see, in the Generic 2.0 tab it asks me for some urls. I think, like for the tab WCF sample, that I have to run another project of the examples zip, but I don't know which.
I have tried almost all, and nothing worked.
This is the list of the project in the zip:
Which one of those have I to run like oAuth 2.0 server?
I thought it is "OAuthAuthorizationServer", but it ask for a openID server url and it doens't seem to be the right one, although it is under the OAuth folder.
Do you have done it before? How?
Further, none of the project I've started binds on the port 18916.
WHAT DO I NEED?
I need someone tells me which one of these projects is the OAuth 2.0 server to be used with the OAuthConsumerWpf application, as I said above. In the wpf project I've found the client I need to study, but which is the server?
UPDATE: I think there is something incomplete in the samples.. or not? I have tried all of them, but nothing... do you have any hints?
-19795402 0 Is there such a thing a 'domain' variables in node.js?Is there a way to set a variable globally in node.js on a per domain-like basis? I say domain-like because at first I though of creating a domain and attaching a value to it so any piece of code that runs inside the domain will have access to it. The code would have looked similar to this:
var myDomain = domain.create() myDomain.someVariable = 1; myDomain.run(function () { console.log(domain.getCurrentDomain().someVariable); });
Unfortunately, that's not how domains work and can be used. Is there something similar to this that can be done however?
Having nested scopes is not a solution because there's multiple files involed.
Thanks
-2543904 0 drscheme c# adapterHi guys i need to integrate drscheme into my c# code for my assignment but i could find any luck on the web. Can anyone help me ? I tried ironscheme but got the following error.
The type or namespace name 'Dynamic' does not exist in the namespace 'System' (are you missing an assembly reference?) C:\Documents and Settings\Administrator\My Documents\Visual Studio 2008\Projects\Integration\Integration\Form1.cs 2 14 Integration
Have tried googling the error message but could find any related stuff.
-15747658 0I would write it like so:
$.each(data, function () { $('#make1').append('<option>' + this.name + '</option>'); });
Also, @Mike Bryant makes a good point; if you are going cross domain, this will never work without something like JSON-P.
-22609983 0Date date = new Date(); String str="2013-08-23"; Date date=new SimpleDateFormat("yyyy-MM-dd").parse(str); Calendar cal = Calendar.getInstance(); cal.setTime(date); Calendar cal1 = Calendar.getInstance(); cal1.setTime(date1); if(cal.get(Calendar.YEAR) == cal1.get(Calendar.YEAR)){ System.out.println("Years are equal"); } else{ System.out.println("Years not equal"); } if(cal.get(Calendar.MONTH) == cal1.get(Calendar.MONTH)){ System.out.println("Months are equal"); } else{ System.out.println("Months not equal"); }
-4901643 0 Animate max-width on img [JQuery] I have tried looking for a solution, but can't find anything good.
I am customizing a blog for a friend of mine. When it loads, I want all the img's in each post to have a max-width and max-height of 150px. When the user pushes the img, the max-values should increase to 500px, which is easy enough. The problem with my code is that I can't get an animation on it, which I want. Any help out there?
var cssObj = {'max-width' : '500px','max-height' : '500px;'} $("img").click(function(){ $(this).css(cssObj); });
-12040122 0 Just do this:
<we:AScreenUserControl x:Class="ProgramManagementV2.screens.MainUserControl" xmlns:we="clr-namespace:ProgramManagementV2.screens" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300"> <Grid> <TextBlock Height="23" HorizontalAlignment="Center" Name="textBlock1" Text="asdfasdf" VerticalAlignment="Center" /> </Grid> </we:AScreenUserControl>
-17801465 0 Joomla 3 PHP errors when uploading files through the media manager Whenever I try to upload files I get a blank white screen with the following PHP error:
Notice: Undefined index: CONTENT_LENGTH in /administrator/components/com_media/controllers/file.php on line 61 Notice: Undefined index: CONTENT_LENGTH in /administrator/components/com_media/controllers/file.php on line 62 Notice: Undefined index: CONTENT_LENGTH in /administrator/components/com_media/controllers/file.php on line 63 Notice: Undefined index: CONTENT_LENGTH in /administrator/components/com_media/controllers/file.php on line 64 Warning: Invalid argument supplied for foreach() in /administrator/components/com_media/controllers/file.php on line 72 Warning: Invalid argument supplied for foreach() in /administrator/components/com_media/controllers/file.php on line 109
-1722486 0 Inject Index of Current item when binding to a repeater I am binding a List<HtmlImage>
to a repeater
Its actually a nested repeater and the list is one of the properties that the parent repeater is binding to
I want to spit out the index of the current dataitem into the id property of the <li>
I've put a comment where I want the index to appear below
I have the following:
<asp:Repeater ID="ImageListRepeater" runat="server" DataSource='<%# DataBinder.Eval(Container.DataItem, "Images") %>'> <HeaderTemplate><ul></HeaderTemplate> <ItemTemplate> <li id='<% **I want the Index Here** %>'><%# RenderImage(Container.DataItem)%></li> </ItemTemplate> <FooterTemplate></ul></FooterTemplate> </asp:Repeater>
What are the options?
thanks
-24766964 0Use a Bitmap to reference the BitmapData and mask it with your MovieClip as seen here: AS3 get Bitmap from Movieclip with Mask
-39995047 0Thank you again for your quick reply Amitesh.
I checked the file "modules/Accounts/metadata/subpaneldefs.php", and I find that there is no array('widget_class' => 'SubPanelTopSelectButton', 'mode' => 'MultiSelect') in the declaration of $layout_defs['Accounts']['subpanel_setup']['opportunities'] array, so I add it manually and it works now.
There is also another alternative, this one consists of deleting the subpanel and creating a new one.
-28372815 0The issue is with this line
dynamic var environment = RLMObject(object: PSTChannelEnv.className())
It just needs to be
dynamic var environment: PSTChannelEnv
The reason we have objectClassName... is because you are creating an array with type objectClassName. When doing a to-one relationship, you already know the object class, so you can set the type directly.
Here are more docs on the setting up your models in Realm
We should throw an error though when you try to do something like this. Thanks for pointing that out!
-30680324 0echo "Ametlla de Mar (L') to Ametlla de Mar" | sed 's/([^)]*)//g'
Ametlla de Mar to Ametlla de Mar
-8076903 0try to tweak this
var subquery = DetachedCriteria.For<Event>() .Add(Restrictions.Eq("Success", true)) .Add(Restrictions.EqProperty("User.Id", "u.id")) .AddOrder(Order.Desc("TimeStamp")) .SetProjection(Projections.Property("EventType")) .SetMaxResults(1); session.CreateCriteria<User>("u") .Add(Restrictions.Ge("LastActivityTimeStamp", cutoff)) .Add(Subqueries.Ne(EventType.LogOff, subquery));
-26388576 0 Set the initial values for the select
and radio
inputs in the controller itself. E.g.
$scope.selectedCES = 'whatever'
Note that you'll have to add an ng-model
to your radio input too.
To validate when the input is required:
<select ... required="true"> ... </select> <input ... required="true"/>
See the angular docs:
https://docs.angularjs.org/api/ng/directive/select
https://docs.angularjs.org/api/ng/directive/input
https://docs.angularjs.org/guide/forms
-20276200 0 Java Play get value of dropdownbox and put it in Form objectWhen hitting the "Save simulation" button I need to know which "option" has been selected in the dropdown box. How to create a field using scala and put it in the testForm object?
@(testForm: Form[Test], areas: List[AreaDefinition]) @import helper._ @main("Test") { @form(routes.TestController.newTest()) { <table border="0" id="areasensor_table"> <tr id="areasensor_row0"> <td> <div id="wrapperForArea"> <select id="selectedArea"> @for(area <- areas) { <option value="@area.uniqueid">@area.name</option>} </select> </div> </td> </tr> </table> <div class="pull-right"> <button class="btn btn-large btn-primary" type="submit">Save simulation</button> </div> } }
TestController:
Form<Test> filledForm = Form.form(Test.class).bindFromRequest();
-21293359 0 recs = unique_recs_in
simply creates a new reference to the list object, to get a completely new copy of a list of lists use copy.deepcopy
.
>>> lis = [[1, 2], [3, 4]] >>> a = lis >>> a.append(4) #changes both `a` and `lis` >>> a, lis ([[1, 2], [3, 4], 4], [[1, 2], [3, 4], 4])
Even a shallow copy is not enough for list of lists:
>>> a = lis[:] >>> a[0].append(100) #Inner lists are still same object, just the outer list has changed. >>> a, lis ([[1, 2, 100], [3, 4]], [[1, 2, 100], [3, 4]])
copy.deepcopy
returns a completely new copy:
>>> import copy >>> a = copy.deepcopy(lis) >>> lis [[1, 2, 100], [3, 4], 4] >>> a.append(999) >>> a, lis ([[1, 2, 100], [3, 4], 4, 999], [[1, 2, 100], [3, 4], 4]) >>> a[0].append(1000) >>> a, lis ([[1, 2, 100, 1000], [3, 4], 4, 999], [[1, 2, 100], [3, 4], 4])
If the list contains only immutable objects, then only a shallow copy is enough:
recs = unique_recs_in[:]
You might find this helpful as well: Python list([])
and []
Int
is the Best type for Id column in a table in SQL Server
If the table eventually has too many records we can change to BigInt
We can also create the Id as the Identity and/or PK of the table.
CREATE TABLE [dbo].[TableName]( [TableNameId] [int] IDENTITY(1,1) NOT NULL ) ON [PRIMARY]
Example of Identity & Primary Key
CREATE TABLE [dbo].[TableName3]( [TableName3Id] [int] IDENTITY(1,1) NOT NULL, CONSTRAINT [PK_TableName3] PRIMARY KEY CLUSTERED ( [TableName3Id] ASC ) )
Hope this helps your question helped me.
-13283408 0 File downloading in phpPresently I am working on a company's website on which if job seeker posts their CV, it will be visible in the admin panel with a download option.
Now I need help in that download part. In admin section i am displaying information about the newly registered job seeker, along with a button which should allow administrator to download the job seeker's CV. I need at least one working example for doing this at least, if I got a good discussion about file downloading I will be very greatful.
I worked on website having file download option in asp.net in C# but no idea how to achieve it in html PHP.
-34856388 0 How to add retina image to responsive emailLogo image is doubled and reduced to smaller size with set pixel width and height. I want the image cleaner and not blurry. Logo still is original size in outlook.
Do I need to wrap this in it's own table to a set pixel width? Do I need to set a certain class to it? How can I clean up this code to work more efficiently?
<td bgcolor="#FFFFFF" width="150" align="center" target="_blank"><a href="http://www...."><img src="http://..t_lgo-300.jpg" width="150px" height="89px" alt="" style="display: block; border: 0; font-family: 'Open Sans', Arial, sans-serif; color: #86898B; font-style: normal; font-size: 18px; line-height:10px; width: 150px; height: 89px;"></a></td>
styles - the logo does not have a class....
td[class="logo"] img{ margin:0 auto!important; } img[class="img-max"]{ max-width: 100% !important; width: 100% !important; height:auto !important; }
-35716794 0 The JoinColumn annotation is not mandatory. I am not sure why so many tutorials use this annotation since it only overrides the default behaviour. When they do not like the default generated name a custom naming strategy would be the better choice.
To keep it short:
I was just About to create a Sample for Proper Understanding on how the Hello Android for ORMLite works in Android.
public class SchoolDataBean { // id is generated by the database and set on the object automagically @DatabaseField(generatedId = true) int rollNo; @DatabaseField(index = true) String name; @DatabaseField String gender; @DatabaseField boolean presence; public SchoolDataBean() { //required by ORM :) } public void setRollNo(int rollNo) { this.rollNo = rollNo; } public void setName(String name) { this.name = name; } public void setGender(String gender) { this.gender = gender; } public void setPresence(boolean presence) { this.presence = presence; } }
In the Database Helper when I try Inserting the initial Values and creating the table with
SchoolDataBean schoolDataSecond = new SchoolDataBean(); schoolDataSecond.setName("Ram"); schoolDataSecond.setGender("F"); schoolDataSecond.setPresence(true); schoolDataSecond.setRollNo(2); dao.create(schoolDataSecond);
I get this exception from the ORMLite Library as
sqlite returned: error code = 1, msg = duplicate column name: gender java.sql.SQLException: SQL statement failed: CREATE TABLE `schooldata` (`rollNo` INTEGER PRIMARY KEY AUTOINCREMENT , `name` VARCHAR , `gender` VARCHAR , `gender` VARCHAR , `presence` SMALLINT )
thanks everyone.
The Exception seems to be caused at this line TableUtils.createTable(connectionSource, SchoolDataBean.class);
-7982311 0 Why does the Facebook Public Search via API return different results when using an access token and when not? You can try it out yourself.
Be logged in to Facebook and go here: https://developers.facebook.com/docs/reference/api/
Hit the first link in the "Searching" section, called https://graph.facebook.com/search?q=watermelon&type=post. Be sure that it contains your access token as a parameter. Look at the results.
Now remove the access token from the url, hit enter, and look at the results again. They differ. Why?
As far as I'm concerned, the search method does not make use of any permissions. So why is the result not the same?
-17781280 0 php character match and allow special charactersI am trying to make a website which will use registration, login actions
.
I am trying it in my localhost. At this stage I've created only database for users and login action.
The problem is I've set my username "viral4ever" in database. Login action is working properly but I can login using "viral4ever", "VIRAL4EVER" and all. I don't want that in my system. I want to check every character in my database to login, if it matches "viral4ever" then it should get me in, not with Viral4ever or vIRAL4ever or VIRAL4EVER and all.
I also want to allow users to use ".", "_","-" in their username. So kindly help me with this.
I am using MySQL database and to login and check users I am using this function...
function user_exists($username){ $username = sanitize($username); return (mysql_result(mysql_query("SELECT `user_id` FROM `users` WHERE `username` = '$username'"), 0) == 1) ? true : false; } function sanitize($data) { return mysql_real_escape_string($data); }
-27394691 0 The app or user may change either the default time zone for an application (using +[NSTimeZone setDefaultTimeZone]) or the system time zone (using System Preferences) at any time. +[NSTimeZone localTimeZone] returns a proxy that will always act as if it is the current default time zone for the application, even if that default changes. You could change the default time zone for an application to make it behave as if it were in a different time zone.
+[NSTimeZone systemTimeZone] returns the current system time zone (as set using System Preferences). In most cases, these will be the same (the app's default time zone is set to the system time zone at app startup, I believe).
If you want to know the system's time zone setting, you probably want to use +[NSTimeZone systemTimeZone]. If you just want the correct time zone for your app to work in, you probably want +[NSTimeZone localTimeZone].
refere to the link: NSTimeZone
-18121657 0This looks to me like more of a SQL question so I will answer it accordingly. If you aren't looking for a SQL-based answer please be more clear in the question. And if you are please amend your tags.
As long as the number of types is fixed and known, the following SQL can form your underlying SQL query (assuming the source is a SQL database):
SELECT a.StaffID, Name, CASE WHEN b.ID IS NOT NULL THEN 1 ELSE 0 END AS Type1, CASE WHEN c.ID IS NOT NULL THEN 1 ELSE 0 END AS Type2, CASE WHEN d.ID IS NOT NULL THEN 1 ELSE 0 END AS Type3 FROM dbo.Staff a LEFT JOIN dbo.StaffType b ON a.StaffID = b.StaffID AND b.TypeID = 1 LEFT JOIN dbo.StaffType c ON a.StaffID = c.StaffID AND c.TypeID = 2 LEFT JOIN dbo.StaffType d ON a.StaffID = d.StaffID AND d.TypeID = 3
In your GridView each checkbox will know its StaffID (from the row) and TypeID (from the column) so simply handle its OnChanged event and call something like:
DECLARE @StaffID INT = 1, @TypeID INT = 1 IF EXISTS (SELECT * FROM dbo.StaffType WHERE StaffID = @StaffID AND TypeID = @TypeID) DELETE FROM dbo.StaffType WHERE StaffID = @StaffID AND TypeID = @TypeID ELSE INSERT INTO dbo.StaffType ( StaffID, TypeID ) VALUES ( @StaffID, @TypeID )
Updated with LINQ version:
var q2 = from staff in staffList from type1 in typesList .Where(t => t.StaffID == staff.StaffID && t.TypeID == 1) .DefaultIfEmpty() from type2 in typesList .Where(t => t.StaffID == staff.StaffID && t.TypeID == 2) .DefaultIfEmpty() from type3 in typesList .Where(t => t.StaffID == staff.StaffID && t.TypeID == 3) .DefaultIfEmpty() select new { StaffID = staff.StaffID, Name = staff.Name, Type1 = (type1 != null), Type2 = (type2 != null), Type3 = (type3 != null) };
-14954415 0 Dip x screen density = pixels (actual image size)
dp to px formula
displayMetrics = context.getResources().getDisplayMetrics(); return (int)((dp * displayMetrics.density) + 0.5);
As answered by Bram.
-12353712 0double
is not an exact type, as you can see by applying the std::numeric_limits
typetrait:
#include <limits> static_assert(std::numeric_limits<double>::is_exact == false);
Thus computations involving doubles are only approximate, and there is nothing wrong about what you observe.
There is no problem with your code.
-8215683 0 How to inflate a expandable list in Android?i want to inflate a expandable list with some different text and different images on each row if i use albumCovers.get(i)
instead of getResources().getDrawable(R.drawable.icon)
then it throws an error, any one help us out? thanks ;p.
public class ExpandActivity extends ExpandableListActivity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // Construct Expandable List final String NAME = "name"; final String IMAGE = "image"; final LayoutInflater layoutInflater = (LayoutInflater) this .getSystemService(Context.LAYOUT_INFLATER_SERVICE); final ArrayList<HashMap<String, String>> headerData = new ArrayList<HashMap<String, String>>(); final HashMap<String, String> group1 = new HashMap<String, String>(); group1.put(NAME, "Group 1"); headerData.add(group1); final ArrayList<ArrayList<HashMap<String, Object>>> childData = new ArrayList<ArrayList<HashMap<String, Object>>>(); final ArrayList<HashMap<String, Object>> group1data = new ArrayList<HashMap<String, Object>>(); childData.add(group1data); Resources res = this.getResources(); Drawable photo = (Drawable) res.getDrawable(R.drawable.icon); ArrayList<Drawable> albumCovers = new ArrayList<Drawable>(); albumCovers.add(photo); // Set up some sample data in both groups for (int i = 0; i < 10; ++i) { final HashMap<String, Object> map = new HashMap<String, Object>(); map.put(NAME, "Child " + i); map.put(IMAGE, getResources().getDrawable(R.drawable.icon)); (group1data).add(map); } setListAdapter(new SimpleExpandableListAdapter(this, headerData, android.R.layout.simple_expandable_list_item_1, new String[] { NAME }, // the name of the field data new int[] { android.R.id.text1 }, // the text field to populate // with the field data childData, 0, null, new int[] {}) { @Override public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { final View v = super.getChildView(groupPosition, childPosition, isLastChild, convertView, parent); // Populate your custom view here ((TextView) v.findViewById(R.id.name)) .setText((String) ((Map<String, Object>) getChild( groupPosition, childPosition)).get(NAME)); ((ImageView) v.findViewById(R.id.image)) .setImageDrawable((Drawable) ((Map<String, Object>) getChild( groupPosition, childPosition)).get(IMAGE)); return v; } @Override public View newChildView(boolean isLastChild, ViewGroup parent) { return layoutInflater.inflate( R.layout.expandable_list_item_with_image, null, false); } }); } }
-33537142 0 If you want to disable only zooming with pinch gesture, below code does the trick.
scrollView.pinchGestureRecognizer?.requireGestureRecognizerToFail(scrollView.panGestureRecognizer)
-39417474 0 Instead of release() and create() the mediaplayer object every time user clicks the button, try to create() only once. Then inside of onClick(), try seekTo(0) to rewind from the beginning of the media file, then call start() to play again.
-6017219 0Roughly, Magento is creating an order collection for you and attempting to load all the records. This collection has a rule that only allows it to create one order object for each ID, so when your additional object is loaded an exception is thrown.
The left joins could be the issue, but it's hard to say off the bat. Could you post a little detail on how you are making the API call? An incorrect join can often have this problem.
EDIT:
If you're using the default code, my first guess would be that there are erroneous records in the database, or that this is an upgraded Magento system which had a bad upgrade in the past. Try this on a clean copy of your EE version pointing to the same database. If the same problem occurs, you may need to spelunk in the database looking for the reason for the problematic data load. Since you already have the query, you may want to separate out parts of the query to see if some subquery is returning too much data.
-2439684 0Without CTEs you can do:
Select Z.Department, Z.AvgWage From ( Select Department, Avg(Wage) AvgWage From Employees Group By Department ) As Z Where AvgWage = ( Select Max(Z1.AvgWage) From ( Select Department, Avg(Wage) AvgWage From Employees Group By Department ) Z1 )
With CTEs you could do:
With AvgWages As ( Select Department , Avg(Wage) AvgWage , Rank() Over( Order By Avg(Wage) Desc ) WageRank From Employees Group By Department ) Select Department, AvgWage, WageRank From AvgWages Where WageRank = 1
-31640354 0 JQGrid getCell Attiribute I was wondering if there was a way to retrieve the rowspan and columnspan attribute value of a cell in jqGrid? My intent is to get the currentrowspan and columnspan attribute value and increase it by one if needed based on the previous row's cell value.
I have looked through all the documentation but it doesn't look like there is a way to getthe attribute values like rowspan and columnspan of a cell.
Thank you
-4118798 0I know you said there's no dangling extern "C"... But why would that even be an issue given how you are compiling with gcc and not g++??? (Which will, in fact, happily treat smsdk_ext.cpp as a C and NOT C++ file... With all the errors and pain that come from doing so...)
Often you will see such error messages when the wrong include files are tagged extern "C". (Or not properly tagged as the case may be.)
Your error messages also indicate difficulty overloading functions...
platform.h: In function ‘double fsel(double, double, double)’: platform.h:470: error: declaration of C function 'double fsel(double, double, double)' conflicts with platform.h:466: error: previous declaration 'float fsel(float, float, float)'
And problems with system (compiler) files.
In file included from /usr/include/sys/signal.h:104, from /usr/include/signal.h:5, from /usr/include/pthread.h:15, from /cygdrive/... /usr/include/cygwin/signal.h:74: error: expected ‘;’ before ‘*’ token /usr/include/cygwin/signal.h:97: error: ‘uid_t’ does not name a type In file included from /usr/include/signal.h:5, from /usr/include/pthread.h:15, from /cygdrive/... /usr/include/sys/signal.h:163: error: ‘pthread_t’ was not declared in this scope /usr/include/sys/signal.h:163: error: expected primary-expression before ‘int’ /usr/include/sys/signal.h:163: error: initializer expression list treated as compound expression
So either your compiler installation is really munged OR...
Alternatively, another approach is to start with a minimal Hello World program and see if that compiles. Then build up, including what you need to, until you hit a problem. (Or take the existing software and simplify it down until you find the problem area. Start with one "g++" line, copy the file, and pare it down until the problem goes away. Perhaps you have a #define or typedef that conflicts with something in a system file.)
-15398954 0 Something wrong either with lParam or with WCHAR[]First, this function is called many times. It should be noted that wString[] does contain the character constant '\n'.
void D2DResources::PutToLog(WCHAR wString[]) { int strLen=wcslen(wString); int logLen=wcslen(log); if(strLen+logLen>=MaxLogSize) wcsncpy(log, log, logLen-strLen); wcscat (log, wString); int nLines=0; for(int x=0; x<wcslen(log); x++) { if(log[x]=='\n') { nLines++; if(nLines>5) { log[x]='\0'; } } } SendMessage (m_hWnd, WM_PAINT, NULL, (LPARAM)nLines); }
At the end, a WM_PAINT message is sent while nLines should be non-zero since log contains multiples '\n'. My WndProc receives the message and processes it.
case WM_PAINT: { pD2DResources->OnRender((int)lParam); ValidateRect(hWnd, NULL); } break;
After which OnRender is called with a (supposedly) non-zero int as an lParam.
void D2DResources::OnRender(int nLogLines) { D2D1_SIZE_F screenSize = pCurrentScreen->GetSize(); D2D1_SIZE_F rTSize = pRT->GetSize(); pRT->BeginDraw(); pRT->DrawBitmap( pCurrentScreen, D2D1::RectF(0.0f, 0.0f, screenSize.width, screenSize.height) ); pRT->DrawText( log, ARRAYSIZE(log) - 1, pTextFormat, D2D1::RectF(0, rTSize.height - ((nLogLines*textSize)+textSize) , rTSize.width, rTSize.height), pWhiteBrush ); pRT->EndDraw(); }
For some reason, in the OnRender function, nLogLines' value is 0. What is wrong?
-41051059 1 SQLITE SUBQUERIESI have a SQLITE Table that holds information in the following format. The first column is ID, second is ID_1, third is ID_2 and final column is Volume.
ID ID_1 ID_2 Volume 1000 111 0 1000 111 1 1000 111 2 1000 111 3 1000 112 0 1000 112 1 1000 112 2 1000 112 3 1000 113 0
There are 10 or more unique ID
values, about 2000 unique ID_1
values and 4 unique values for ID_2
.
At the end I want to select volume for selected IDs, selected ID_1 and selected ID_2. Things work well this far. The output format should be - ID, ID_1, Volume
What I am confused about is to get the following data.
I need the following data:
For a given ID and ID_1, if ID_2 = 1, then
Volume = (Volume for ID, ID_1 and ID_2 = 1) - (Volume for ID, ID_1 and ID_2 = 2)- (Volume for ID, ID_1 and ID_2 = 3)
Otherwise print volume like it is.
I am using python to extract this data in a csv file. I am trying to store ID and ID_1 into value1 and value2 and using that in subquery but it doesnt seem to be working.
My code looks like the following:
import os import sqlite3 import shutil import csv import time import datetime from pprint import pprint value1 ="va" value2 ="pa" working_dir = "C:\Path" aimsun_db_filename = os.path.join(working_dir,"File.sqlite") conn = sqlite3.connect(filename) c= conn.cursor() SQL = ''' SELECT TableName.ID '''= value1 +''', TableName.ID_1 '''= value2 +''', CASE WHEN ID_2 = 1 THEN (SELECT TableName.volume FROM TableName WHERE ID_2 = 2 and TableName.oid = '''+value1+''' AND TableName.did = '''+value2+''' ) WHEN ID_2 = 2 THEN TableName.volume WHEN ID_2 = 3 THEN TableName.volume ELSE "Other" END, FROM TableName WHERE AND NOT sid = 0 AND NOT ent = 0 ''' with conn: c = conn.cursor() c.execute(SQL) while True: row = c.fetchone() if row ==None: break
-31792478 0 Your struct here:
struct weighted_pointer{ mutable int weight; unique_ptr<likeatree> ptr; };
contains a std::unique_ptr
. A std::unique_ptr
cannot be copied, so your entire weighted_pointer
cannot be copied as well.
There are three places in your code where you attempt to copy it, which causes the errors you see:
bool operator()(const weighted_pointer lhs, const weighted_pointer rhs) {
Must be:
bool operator()(weighted_pointer const& lhs, weighted_pointer const& rhs) {
stdSet.insert(tmp);
This could theoretically be fixed by:
stdSet.insert(std::move(tmp));
However, you then cannot use tmp
anymore, which you do, not only in the same loop but also in the loop below. So you must find a different solution altogether. Perhaps use emplace
. Or restructure your code entirely.
auto it = find_if(stdSet.begin(),stdSet.end(),[&](weighted_pointer temp){ return temp.ptr.get() == treeVector[i]; });
Must be:
auto it = find_if(stdSet.begin(),stdSet.end(),[&](weighted_pointer const& temp){ return temp.ptr.get() == treeVector[i]; });
For VC++ 2013, the std::move
fix will not suffice. You will have to add an explicit move constructor to your struct:
struct weighted_pointer{ mutable int weight; unique_ptr<likeatree> ptr; weighted_pointer() = default; weighted_pointer(weighted_pointer&& src) : weight(std::move(src.weight)), ptr(std::move(src.ptr)) { } };
VC++ 2015 fixes this problem. More information: Default Move Constructor in Visual Studio 2013 (Update 3)
-9229310 0 How to attach the UIProgressView with the HTTPRequest processMy purpose is to show a nice UIProgressView
that display the progress of the HTTPRequest to the user (loading). It seems everything is okay, however my UIProgressView
well configured and setup in interface builder doesn't show the progress of the request, it doesn't even appear on the screen. Here is my relevant code:
// Start request //..... //Specify the address of the webservice (url) NSURL *url = [NSURL URLWithString:@"http://xxx.xxxxxx.com/xxxxxx/webservices/"]; ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url]; NSString *jsonStringArray=[aMutableArray JSONRepresentation]; [request setPostValue:jsonStringArray forKey:@"liste_des_themes"]; [request setDelegate:self]; [request setUploadProgressDelegate:progress];//when i remove this line, the ProgressVie appear, although not working :( [request startSynchronous];
My UIProgressView
is named progress
, does anybody know how to make the UIProgressView interact with the HTTPRequest
Request? thanx in advance.
I have created a multiuploadField object in wicket project which allows to select files and submit the files after clicking on submit button. But I want to auto submit the form once the file are selected by the user and upload the file without clicking the submit button. Is it possible to do this? Is there any way of doing it using onChange event or anything else.
<form wicket:id="simpleUpload"> <fieldset> <legend>Upload form</legend> <p> <div wicket:id="fileInput" class="mfuex" /> </p> <input type="submit" value="Upload!" /> </fieldset> </form>
Thanks in advance.
-31475613 0Use focus and simplify your css a little to something like this if possible:
.sky-form-orange input:focus { background-color: #f5b093 !important; }
<head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=10"> <title>Blog – Magma Machine - Graphic and Digital Design</title> <link rel="profile" href="http://gmpg.org/xfn/11"> <link rel="pingback" href="http://www.magmamachine.co.uk/xmlrpc.php"> <script type="text/javascript">document.documentElement.className = document.documentElement.className + ' yes-js js_active js'</script> <style> .wishlist_table .add_to_cart, a.add_to_wishlist.button.alt { border-radius: 16px; -moz-border-radius: 16px; -webkit-border-radius: 16px; } </style> <script type="text/javascript"> var yith_wcwl_plugin_ajax_web_url = 'http://www.magmamachine.co.uk/wp-admin/admin-ajax.php'; </script> <link rel="alternate" type="application/rss+xml" title="Magma Machine » Feed" href="http://www.magmamachine.co.uk/feed/"> <link rel="alternate" type="application/rss+xml" title="Magma Machine » Comments Feed" href="http://www.magmamachine.co.uk/comments/feed/"> <script type="text/javascript"> window._wpemojiSettings = {"baseUrl":"http:\/\/s.w.org\/images\/core\/emoji\/72x72\/","ext":".png","source":{"concatemoji":"http:\/\/www.magmamachine.co.uk\/wp-includes\/js\/wp-emoji-release.min.js?ver=4.2.2"}}; !function(a,b,c){function d(a){var c=b.createElement("canvas"),d=c.getContext&&c.getContext("2d");return d&&d.fillText?(d.textBaseline="top",d.font="600 32px Arial","flag"===a?(d.fillText(String.fromCharCode(55356,56812,55356,56807),0,0),c.toDataURL().length>3e3):(d.fillText(String.fromCharCode(55357,56835),0,0),0!==d.getImageData(16,16,1,1).data[0])):!1}function e(a){var c=b.createElement("script");c.src=a,c.type="text/javascript",b.getElementsByTagName("head")[0].appendChild(c)}var f,g;c.supports={simple:d("simple"),flag:d("flag")},c.DOMReady=!1,c.readyCallback=function(){c.DOMReady=!0},c.supports.simple&&c.supports.flag||(g=function(){c.readyCallback()},b.addEventListener?(b.addEventListener("DOMContentLoaded",g,!1),a.addEventListener("load",g,!1)):(a.attachEvent("onload",g),b.attachEvent("onreadystatechange",function(){"complete"===b.readyState&&c.readyCallback()})),f=c.source||{},f.concatemoji?e(f.concatemoji):f.wpemoji&&f.twemoji&&(e(f.twemoji),e(f.wpemoji)))}(window,document,window._wpemojiSettings); </script><script src="http://www.magmamachine.co.uk/wp-includes/js/wp-emoji-release.min.js?ver=4.2.2" type="text/javascript"></script> <style type="text/css"> img.wp-smiley, img.emoji { display: inline !important; border: none !important; box-shadow: none !important; height: 1em !important; width: 1em !important; margin: 0 .07em !important; vertical-align: -0.1em !important; background: none !important; padding: 0 !important; } </style> <link rel="stylesheet" id="mmpm_mega_main_menu-css" href="http://www.magmamachine.co.uk/wp-content/plugins/mega_main_menu/src/css/cache.skin.css?ver=4.2.2" type="text/css" media="all"> <link rel="stylesheet" id="chimpy-css" href="http://www.magmamachine.co.uk/wp-content/plugins/chimpy/assets/css/style-frontend.css?ver=2.1.3" type="text/css" media="all"> <link rel="stylesheet" id="chimpy-font-awesome-css" href="http://www.magmamachine.co.uk/wp-content/plugins/chimpy/assets/css/font-awesome/css/font-awesome.min.css?ver=4.0.3" type="text/css" media="all"> <link rel="stylesheet" id="chimpy-sky-forms-style-css" href="http://www.magmamachine.co.uk/wp-content/plugins/chimpy/assets/forms/css/sky-forms.css?ver=2.1.3" type="text/css" media="all"> <link rel="stylesheet" id="chimpy-sky-forms-color-schemes-css" href="http://www.magmamachine.co.uk/wp-content/plugins/chimpy/assets/forms/css/sky-forms-color-schemes.css?ver=2.1.3" type="text/css" media="all"> <link rel="stylesheet" id="sb_instagram_styles-css" href="http://www.magmamachine.co.uk/wp-content/plugins/instagram-feed/css/sb-instagram.css?ver=1.3.7" type="text/css" media="all"> <link rel="stylesheet" id="sb_instagram_icons-css" href="//netdna.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css?1&ver=4.2.0" type="text/css" media="all"> <link rel="stylesheet" id="rs-plugin-settings-css" href="http://www.magmamachine.co.uk/wp-content/plugins/revslider/rs-plugin/css/settings.css?ver=4.6.5" type="text/css" media="all"> <style id="rs-plugin-settings-inline-css" type="text/css"> .tp-caption a{color:#ff7302;text-shadow:none;-webkit-transition:all 0.2s ease-out;-moz-transition:all 0.2s ease-out;-o-transition:all 0.2s ease-out;-ms-transition:all 0.2s ease-out}.tp-caption a:hover{color:#ffa902} </style> <link rel="stylesheet" id="woocommerce_prettyPhoto_css-css" href="//www.magmamachine.co.uk/wp-content/plugins/woocommerce/assets/css/prettyPhoto.css?ver=4.2.2" type="text/css" media="all"> <link rel="stylesheet" id="jquery-selectBox-css" href="http://www.magmamachine.co.uk/wp-content/plugins/yith-woocommerce-wishlist/assets/css/jquery.selectBox.css?ver=4.2.2" type="text/css" media="all"> <link rel="stylesheet" id="yith-wcwl-main-css" href="http://www.magmamachine.co.uk/wp-content/plugins/yith-woocommerce-wishlist/assets/css/style.css?ver=4.2.2" type="text/css" media="all"> <link rel="stylesheet" id="yith-wcwl-font-awesome-css" href="http://www.magmamachine.co.uk/wp-content/plugins/yith-woocommerce-wishlist/assets/css/font-awesome.min.css?ver=4.2.2" type="text/css" media="all"> <link rel="stylesheet" id="js_composer_front-css" href="http://www.magmamachine.co.uk/wp-content/plugins/js_composer/assets/css/js_composer.css?ver=4.5.3" type="text/css" media="all"> <link rel="stylesheet" id="magnific-popup-css" href="http://www.magmamachine.co.uk/wp-content/plugins/elite-addons-vc/assets/libs/magnific-popup/magnific-popup.min.css?ver=0.9.9" type="text/css" media="all"> <link rel="stylesheet" id="iv-oswald-webfont-css" href="http://fonts.googleapis.com/css?family=Oswald%3A400%2C700&ver=1" type="text/css" media="all"> <link rel="stylesheet" id="iv-roboto-cond-webfont-css" href="http://fonts.googleapis.com/css?family=Roboto+Condensed%3A400%2C700&ver=1" type="text/css" media="all"> <link rel="stylesheet" id="ivan-font-awesome-css" href="http://www.magmamachine.co.uk/wp-content/themes/october/css/libs/font-awesome-css/font-awesome.min.css?ver=4.1.0" type="text/css" media="all"> <link rel="stylesheet" id="ivan-elegant-icons-css" href="http://www.magmamachine.co.uk/wp-content/themes/october/css/libs/elegant-icons/elegant-icons.min.css?ver=1.0" type="text/css" media="all"> <link rel="stylesheet" id="ivan_owl_carousel-css" href="http://www.magmamachine.co.uk/wp-content/themes/october/css/libs/owl-carousel/owl.carousel.min.css?ver=4.2.2" type="text/css" media="all"> <link rel="stylesheet" id="ivan-theme-styles-css" href="http://www.magmamachine.co.uk/wp-content/themes/october/css/theme-styles.min.css?ver=1" type="text/css" media="all"> <link rel="stylesheet" id="ivan-default-style-css" href="http://www.magmamachine.co.uk/wp-content/themes/october/style.css?ver=4.2.2" type="text/css" media="all"> <!--[if IE]> <link rel='stylesheet' id='ie-ivan-theme-styles-css' href='http://www.magmamachine.co.uk/wp-content/themes/october/css/ie.css' type='text/css' media='all' /> <![endif]--> <link rel="stylesheet" id="redux-google-fonts-iv_aries-css" href="http://fonts.googleapis.com/css?family=Roboto+Condensed%3A400&ver=4.2.2" type="text/css" media="all"> <link rel="stylesheet" id="woocommerce-layout-css" href="http://www.magmamachine.co.uk/wp-content/themes/october/css/woocommerce/css/woocommerce-layout.css?ver=2.3.13" type="text/css" media="all"> <link rel="stylesheet" id="woocommerce-smallscreen-css" href="http://www.magmamachine.co.uk/wp-content/themes/october/css/woocommerce/css/woocommerce-smallscreen.css?ver=2.3.13" type="text/css" media="only screen and (max-width: 768px)"> <link rel="stylesheet" id="woocommerce-general-css" href="http://www.magmamachine.co.uk/wp-content/themes/october/css/woocommerce/css/woocommerce.css?ver=2.3.13" type="text/css" media="all"> <script type="text/javascript" src="http://www.magmamachine.co.uk/wp-includes/js/jquery/jquery.js?ver=1.11.2"></script> <script type="text/javascript" src="http://www.magmamachine.co.uk/wp-includes/js/jquery/jquery-migrate.min.js?ver=1.2.1"></script> <script type="text/javascript" src="http://www.magmamachine.co.uk/wp-content/themes/october/plugins/login-with-ajax/login-with-ajax.js?ver=4.2.2"></script> <script type="text/javascript" src="http://www.magmamachine.co.uk/wp-content/plugins/chimpy/assets/js/chimpy-frontend.js?ver=2.1.3"></script> <script type="text/javascript" src="http://www.magmamachine.co.uk/wp-content/plugins/chimpy/assets/forms/js/jquery.form.min.js?ver=20130711"></script> <script type="text/javascript" src="http://www.magmamachine.co.uk/wp-content/plugins/chimpy/assets/forms/js/jquery.validate.min.js?ver=1.11.0"></script> <script type="text/javascript" src="http://www.magmamachine.co.uk/wp-content/plugins/chimpy/assets/forms/js/jquery.maskedinput.min.js?ver=1.3.1"></script> <script type="text/javascript" src="http://www.magmamachine.co.uk/wp-content/plugins/revslider/rs-plugin/js/jquery.themepunch.tools.min.js?ver=4.6.5"></script> <script type="text/javascript" src="http://www.magmamachine.co.uk/wp-content/plugins/revslider/rs-plugin/js/jquery.themepunch.revolution.min.js?ver=4.6.5"></script> <script type="text/javascript"> /* <![CDATA[ */ var wc_add_to_cart_params = {"ajax_url":"\/wp-admin\/admin-ajax.php","i18n_view_cart":"View Basket","cart_url":"","is_cart":"","cart_redirect_after_add":"no"}; /* ]]> */ </script> <script type="text/javascript" src="//www.magmamachine.co.uk/wp-content/plugins/woocommerce/assets/js/frontend/add-to-cart.min.js?ver=2.3.13"></script> <script type="text/javascript" src="http://www.magmamachine.co.uk/wp-content/plugins/js_composer/assets/js/vendors/woocommerce-add-to-cart.js?ver=4.5.3"></script> <link rel="EditURI" type="application/rsd+xml" title="RSD" href="http://www.magmamachine.co.uk/xmlrpc.php?rsd"> <link rel="wlwmanifest" type="application/wlwmanifest+xml" href="http://www.magmamachine.co.uk/wp-includes/wlwmanifest.xml"> <meta name="generator" content="WordPress 4.2.2"> <meta name="generator" content="WooCommerce 2.3.13"> <script type="text/javascript"> jQuery(document).ready(function() { // CUSTOM AJAX CONTENT LOADING FUNCTION var ajaxRevslider = function(obj) { // obj.type : Post Type // obj.id : ID of Content to Load // obj.aspectratio : The Aspect Ratio of the Container / Media // obj.selector : The Container Selector where the Content of Ajax will be injected. It is done via the Essential Grid on Return of Content var content = ""; data = {}; data.action = 'revslider_ajax_call_front'; data.client_action = 'get_slider_html'; data.token = 'fb1a3202b0'; data.type = obj.type; data.id = obj.id; data.aspectratio = obj.aspectratio; // SYNC AJAX REQUEST jQuery.ajax({ type:"post", url:"http://www.magmamachine.co.uk/wp-admin/admin-ajax.php", dataType: 'json', data:data, async:false, success: function(ret, textStatus, XMLHttpRequest) { if(ret.success == true) content = ret.data; }, error: function(e) { console.log(e); } }); // FIRST RETURN THE CONTENT WHEN IT IS LOADED !! return content; }; // CUSTOM AJAX FUNCTION TO REMOVE THE SLIDER var ajaxRemoveRevslider = function(obj) { return jQuery(obj.selector+" .rev_slider").revkill(); }; // EXTEND THE AJAX CONTENT LOADING TYPES WITH TYPE AND FUNCTION var extendessential = setInterval(function() { if (jQuery.fn.tpessential != undefined) { clearInterval(extendessential); if(typeof(jQuery.fn.tpessential.defaults) !== 'undefined') { jQuery.fn.tpessential.defaults.ajaxTypes.push({type:"revslider",func:ajaxRevslider,killfunc:ajaxRemoveRevslider,openAnimationSpeed:0.3}); // type: Name of the Post to load via Ajax into the Essential Grid Ajax Container // func: the Function Name which is Called once the Item with the Post Type has been clicked // killfunc: function to kill in case the Ajax Window going to be removed (before Remove function ! // openAnimationSpeed: how quick the Ajax Content window should be animated (default is 0.3) } } },30); }); </script> <style type="text/css">.recentcomments a{display:inline !important;padding:0 !important;margin:0 !important;}</style> <meta name="generator" content="Powered by Visual Composer - drag and drop page builder for WordPress."> <!--[if IE 8]><link rel="stylesheet" type="text/css" href="http://www.magmamachine.co.uk/wp-content/plugins/js_composer/assets/css/vc-ie8.css" media="screen"><![endif]--> <!--[if gte IE 9]> <style type="text/css"> ..mega_main_menu, ..mega_main_menu * { filter: none; } </style> <![endif]--> <!-- BEGIN Typekit Fonts for WordPress --> <script type="text/javascript" src="//use.typekit.net/prl6byj.js"></script> <style type="text/css">.tk-proxima-nova{font-family:"proxima-nova",sans-serif;}</style><link rel="stylesheet" href="http://use.typekit.net/c/22bbac/1w;proxima-nova,7cdcb44be4a7db8877ffa5c0007b8dd865b3bbc383831fe2ea177f62257a9191,gbm:V:i4,gbt:V:i7,gbl:V:n4,gbs:V:n7/d?3bb2a6e53c9684ffdc9a9aff1b5b2a6276adde0ff798449a3bfbdbf9b6f1614fe7f047719e422580edd9d4512a6f131617d729a1e2861c6f1d559f758f16e5f4f033898b8bfbc0aca15c145112888b3d2a478ead4718a4e9956bc4" media="all"><script type="text/javascript">try{Typekit.load();}catch(e){}</script> <!-- END Typekit Fonts for WordPress --> <style type="text/css" title="dynamic-css" class="options-output">.iv-layout.header{margin-top:30px;}#iv-layout-title-wrapper{border-top-width:1px;border-top-color:#f7f7f7;border-bottom-color:#f7f7f7;}#iv-layout-title-wrapper h2{font-family:Roboto Condensed;letter-spacing:-2px;font-weight:400;font-size:50px;}.iv-layout.bottom-footer{background-color:#303030;}</style><style type="text/css"></style><style type="text/css"></style><style type="text/css"></style> <style type="text/css"> </style> <noscript><style> .wpb_animate_when_almost_visible { opacity: 1; }</style></noscript></head> <aside id="chimpy_form-3" class="widget widget_chimpy_form"> <form id="chimpy_widget_1" class="chimpy_signup_form sky-form sky-form-orange chimpy_custom_css" novalidate="novalidate"> <input type="hidden" name="chimpy_widget_subscribe[form]" value="1"> <input type="hidden" id="chimpy_form_context" name="chimpy_widget_subscribe[context]" value="widget"> <header>Join our mailing list</header> <div class="chimpy_status_underlay"> <fieldset> <div class="description">blog updates and exclusive offers for members</div> <section> <label class="input"><i class="icon-append fa-user"></i> <input type="text" id="chimpy_widget_field_FNAME" name="chimpy_widget_subscribe[custom][FNAME]" placeholder="First Name ..."> </label> </section> <section> <label class="input"><i class="icon-append fa-user"></i> <input type="text" id="chimpy_widget_field_LNAME" name="chimpy_widget_subscribe[custom][LNAME]" placeholder="Last Name ..."> </label> </section> <section> <label class="input"><i class="icon-append fa-envelope-o"></i> <input type="text" id="chimpy_widget_field_EMAIL" name="chimpy_widget_subscribe[custom][EMAIL]" placeholder="Email Address ..."> </label> </section> </fieldset> <div id="chimpy_signup_widget_processing" class="chimpy_signup_processing" style="display: none;"></div> <div id="chimpy_signup_widget_error" class="chimpy_signup_error" style="display: none;"> <div></div> </div> <div id="chimpy_signup_widget_success" class="chimpy_signup_success" style="display: none;"> <div></div> </div> </div> <footer> <button type="button" id="chimpy_widget_submit" class="button">sign me up</button> </footer> </form> <script type="text/javascript"> jQuery(function() { jQuery("#chimpy_widget_1").validate({ rules: { "chimpy_widget_subscribe[custom][FNAME]": { "required": false, "maxlength": 200 }, "chimpy_widget_subscribe[custom][LNAME]": { "required": false, "maxlength": 200 }, "chimpy_widget_subscribe[custom][EMAIL]": { "required": true, "maxlength": 200, "email": true } }, messages: { "chimpy_widget_subscribe[custom][FNAME]": [], "chimpy_widget_subscribe[custom][LNAME]": [], "chimpy_widget_subscribe[custom][EMAIL]": { "required": "Please enter a value", "email": "Invalid format" } }, errorPlacement: function(error, element) { error.insertAfter(element.parent()); } }); }); </script> </aside>
Try out this framework : https://github.com/AdrianFlorian/AFImageViewer to present images in a scroll view using a page controll to indicate the current page.
I have't added documentation yet, but you can see examples if you clone the project.
You can easily: - download images from the internet in a separate thread by only giving an array of urls (image urls) - give it an array of UIImage objects - implement a delegate and manage the image for each page yourself
-30541294 0 Computation with Floating Point Numbers: When to Round?I'm performing some computations in C with floating point numbers. I'm specifically dealing with the case where I get the lowest possible single precision value for the exponent.
Say my exponent is -126 and I have to decrement it. In this case, I can't go any lower, so I need to right shift my mantissa once. I know I'm supposed to get the exact answer for a calculation and then round (to whatever place is specified).
I'm thinking of doing (let M
be the mantissa):
M >>= 1; //round mantissa
since I'm shifting the mantissa to the right and there was an implied 1 to the left of the floating point, do I need to modify M after shifting with something like:
M |= (1 << 23)
to ensure I have a 1 in the most significant bit?
It seems weird to round after losing a bit of information but is this standard / accepted practice? Or should I calculate the full result by using more bits and then rounding?
You might have have to set the temporary download path so that it writes it to disk while downloading the document. As is, it could be keeping the whole thing in memory and crashing when the memory footprint has become unacceptable to the system. The documentation isn't entirely clear on this.
When downloading data to a file using downloadDestinationPath, data will be saved in a temporary file while the request is in progress. This file’s path is stored in temporaryFileDownloadPath.
I can't seem to find out what happens if temporaryFileDownloadPath is nil.
-16435041 0 Changing a displayedI would like to ask some help on this thing. I created a site that has a lot of div and what I want is that when a link is clicked only one div will be displayed without reloading the whole page.
Sample code:
<ul> <li><a href="">Div 1</a></li> <li><a href="">Div 2</a></li> <li><a href="">Div 3</a></li> </ul> <div id="content1"> <p>This is content 1</p> </div> <div id="content2"> <p>This is content 2</p> </div> <div id="content3"> <p>This is content 13</p> </div>
Is it possible if I'll just use php? And please help me on how I will do it.
-1450629 0 how to connect and sends data betweens many computers using Java networkingI am beginner of learning Java Networking.I want to connect 3 or more computers. One for server and others(eg A and B )for clients .But I want to connect
First I want to send message from either A or B to server and server sends stored data to sender (eg A) and sender (A) will connect to B. Then A and B will confirm message and A and B will send data one to another. But this occasion can occurs from A and B concurrently.
But I just learned simple code for connection of one server and one client using Server socket and socket. Will all 3 computers require to act for both server and client? Is there other ways to connect between clients. I don't know how to consider to solve data conflict between computers. I also want to satisfy if new clients are added. If anyone know to solve above problem including data conflicts, pls help me with simple sample code for both server and clients.
Thanks !!
-2678296 0 Padding to the left and right of a floated image, in IE onlyGenerally I seem to be able to fix IE problems nowadays.. but this one realy has me stuck!
Take a look at the screenshot below to see the problem or visit the url to see the problem.
http://homedynamics.com/sawgrass/floorplan.php
I have made sure the ul li and img's are all cleared (padding:0; margin:0; border:0;) and still there is padding added to the left and right of the images. I also did "display: block" on images with no luck.
Can anyone point me in the right direction? Thanks!!
-14883721 0I've been looking at your issue and haven't been able to get it working either. I tried using the XJC schema compiler and it is also having problems with schema conflicts, and EclipseLink depends on XJC for Dynamic JAXB context creation.
First off, when I ran your test case in Eclipse I got a slightly different error:
com.sun.istack.SAXParseException2: Property "Title" is already defined. Use <jaxb:property> to resolve this conflict.
But I see that in your bindings file you're already using jaxb:property for title (lowercase), and I couldn't find any Title (uppercase) in any of the related XSDs.
Second, when I ran XJC I got:
C:\...\src\omar>xjc example-feature.xsd -b xlink-bindings.xjb parsing a schema... compiling a schema... [ERROR] Two declarations cause a collision in the ObjectFactory class. line 28 of http://schemas.opengis.net/gml/2.1.2/feature.xsd [ERROR] (Related to above error) This is the other declaration. line 29 of http://schemas.opengis.net/gml/2.1.2/feature.xsd Failed to produce code.
But this is also strange because line 29 of feature.xsd is:
<element name="geometryProperty" type="gml:GeometryAssociationType"/>
But I can't find any conflict with geometryProperty.
Hopefully this is enough information for you get a bindings file in order that will get XJC working. At that point you should be able to bootstrap a DynamicJAXBContext. The xjc executable is located in your JAVA_HOME\bin directory.
Note change
event fires after the input
loses focus. You may want to use input
event instead.
To convert the string to numbers, you can use the unary operator +
instead of Number
.
To default to 0
when some expression is falsy, you can use expr || 0
.
var field1 = document.getElementById('field1'), field2 = document.getElementById('field2'), total = document.getElementById('total'); field1.oninput = field2.oninput = function updateTotalCosts() { total.value = (+field1.value || 0) + (+field2.value || 0); };
<input id="field1" /> + <input id="field2" /> = <input id="total" />
Or, using jQuery,
var $field1 = $('#field1'), $field2 = $('#field2'), $total = $('#total'); $field1.add($field2).on('input change', function updateTotalCosts() { $total.val((+$field1.val() || 0) + (+$field2.val() || 0)); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <input id="field1" /> + <input id="field2" /> = <input id="total" />
This would print a JSON with all of the properties (public, private and protected) of class foo
:
$reflection = new ReflectionClass('foo'); $properties = $reflection->getdefaultProperties(); echo json_encode($properties);
-1104109 0 If it's a functional explanation you're looking for, you could draw the analogy with an organization:
I poked at your program for a while without having much to show for it. Perhaps I realized too late that it was not supposed to reproduce the problem :( I can only provide some possibly helpful hints to get you to look under the right kind of rock.
yet it was solved via a hack that doesn't work for me
These programmers made a simple mistake, they forgot to call CoInitialize/Ex()
. A very common oversight. Using the /clr build option works around that mistake because it is now the CLR that calls it. You can easily repro this mishap, just comment out the CoInitialize() call. Unfortunately it works for a while without any loud errors being produced, but you do get 0 for certain accobjects. You'll notice your program no longer finds the tabs.
Not so sure I can cleanly explain this, certain COM-style object models don't actually use the COM infrastructure. DirectX is the best example, we can add UIAutomation to that list. I assume it will silently fail like this when the client app's component is COM-based. Unclear if it is, DirectUIHWnd is quite undocumented.
So stop looking for that as a workaround, you did not forget to call CoInitialize() and it will be taken care of by IE before it activates your extension.
If you run IE with administrator privileges, it works properly.
That's a better rock. Many programmers run VS elevated all the time, the roles might be reversed in the case of UIA. Do keep in mind that your extension runs in a sandbox inside IE. No real idea how elevating IE affects this. One thing you cannot do from code running in the low-integrity sandbox is poke at UI components owned by a code that runs in a higher integrity mode. Google "disable IE enhanced protected mode" and follow the guideline to see what effect that has on your addin.
-17225845 0This problem is not specific to Entity Framework (although EF certainly also has other limitations around UNIQUE constraints). This is common with any similar server-client model. Since the uniqueness will be enforced by the database server at the time of the request, there is no fool-proof way to know in advance if the constraint will be violated, until you attempt the insert.
That said, checking for uniqueness in advance should be a very cheap operation (on SQL Server, a UNIQUE constraint will also give you an index on that column), so depending on how often you expect the application to be attempting duplicate insertion, this should cover the large majority of your cases. But if the duplicate insert attempts would be quite rare to begin with, you can avoid making the extra round-trip per insert and just handle the exception when it happens.
Handling the exception doesn't need to be very complicated, especially if there is a way for the end user to modify the data and attempt a retry. In the case where, as you said, you're queuing-up several inserts in a single transaction, you may need to check the exception (or inner exception) for specific constraint names, so that you know which entity object is a duplicate. (Again, EF doesn't really support handling UNIQUE constraint exceptions directly, so this is probably the part that is causing you the most pain right now.)
Note: I would not recommend re-working the insert as a stored procedure just to circumvent the rare chance that duplicate entries get attempted concurrently. You're better off making sure your application handles this (and other SQL exceptions, of which there may be many) as gracefully as possible. However, if you are finding that in your case there is really no other way, a sproc may be the easiest approach for now. Just keep in mind that it's probably foregoing more maintainable code in order to solve a very rare edge case.
-3665231 0You can add functions to Studio by putting PHP files with stub function descriptions into special directory. Find this directory in filesystem in a following way: write something like gmdate(), select the name and press F3. You will be taken to one of the prototype files. Note the directory where this file resides (shown on the top and if you hover over the tab). Now you need to create stubs for functions you are missing just like the one you're looking at. You can put them into any file, generally, but I suggest putting them into separate file - like geoip.php - and put this file into that directory. You may also want to do right-click/Show In/PHP Explorer and browse other prototype files if you need examples of how to do it right.
-8313007 0fixed it with this function:
CREATE FUNCTION [dbo].[ReplaceWithDefault] ( @InputString VARCHAR(4000) ) RETURNS VARCHAR(4000) AS BEGIN DECLARE @Pattern VARCHAR(100) SET @Pattern = '$[%]_%##%[%]$' -- working copy of the string DECLARE @Result VARCHAR(4000) SET @Result = @InputString -- current match of the pattern DECLARE @CurMatch VARCHAR(500) SET @curMatch = '' -- string to replace the current match DECLARE @Replace VARCHAR(500) SET @Replace = '' -- start + end of the current match DECLARE @Start INT DECLARE @End INT -- length of current match DECLARE @CurLen INT -- Length of the total string -- 8001 if @InputString is NULL DECLARE @Len INT SET @Len = COALESCE(LEN(@InputString), 8001) WHILE (PATINDEX('%' + @Pattern + '%', @Result) != 0) BEGIN SET @Replace = '' SET @Start = PATINDEX('%' + @Pattern + '%', @Result) SET @CurMatch = SUBSTRING(@Result, @Start, @Len) SET @End = PATINDEX('%[%]$%', @CurMatch) + 2 SET @CurMatch = SUBSTRING(@CurMatch, 0, @End) SET @CurLen = LEN(@CurMatch) SET @Replace = REPLACE(RIGHT(@CurMatch, @CurLen - (PATINDEX('%##%', @CurMatch)+1)), '%$', '') SET @Result = REPLACE(@Result, @CurMatch, @Replace) END RETURN(@Result) END
-11843865 0 It's very simple:
DocsList.getFileById(SpreadsheetApp.getActiveSpreadsheet().getId()).makeCopy(SpreadsheetApp.getActiveSpreadsheet().getName() + "_copy");
-11390945 0 To make the scrollbar always visible in an Android view add the following property to the relevant container in the layout xml
android:scrollbarFadeDuration="0"
Refer this.
Specifically for Android 4.0.3
API level 15 you can use,
android:fadeScrollbars
It defines whether to fade out scrollbars when they are not in use. Must be a boolean value, either "true" or "false". Source.
Using code the View.setScrollbarFadingEnabled(boolean) is what you can use.
-15150483 0I think StringTokenizer based solution will be the fastest
public static int[] splitDateTime(String dateTime) { int[] intParts = new int[5]; StringTokenizer t = new StringTokenizer(dateTime, "/ :"); for (int i = 0; t.hasMoreTokens(); i++) { intParts[i] = Integer.parseInt(t.nextToken()); } return intParts; } public static void main(final String[] args) throws IOException { System.out.println(Arrays.toString(splitDateTime("01/03/2013 09:00"))); }
output
[1, 3, 2013, 9, 0]
-22496898 0 Refresh a page in MVC How to refresh the current page in MVC.
[HttpGet] public ActionResult Request() { if (Session["type"] != null && Session["resulttype"] != null) { return View(); } else { return null; } }
I want to refresh my page in else part. That is when return null value.
-12503507 0 SpringMVC Restful Web ServiceI am trying to build a RESTFUL Web Service however I am getting an error under is my code:
jsp
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script> <style> <%@ include file="../css/forms.css" %> </style> <script type="text/javascript"> <%@ include file="../js/off_reg.js"%> $(document).ready(function(){ $('#userName').blur(function(evt){ CheckAvailability(); }); }); function CheckAvailability(){ $.ajax( { type:'GET', //Could be 'get' depending on your needs url:'validateUserName.htm', data:{userName:$('#userName').val()}, dataType: 'json', success:function(data) { alert(data); } }); } </script>
DAO
public boolean OfficerExist(String userName){ try{ logger.debug("About to check if officers existing"); String sql = "SELECT userName FROM crimetrack.tblofficers WHERE userName = ?"; logger.info("at this point 1"); //String dbUserName = (String)results.get("userName"); String dbUserName = (String)getJdbcTemplate().queryForObject(sql, new Object[]{userName},String.class); logger.info("after JdbcTemplate"); if (dbUserName.equals(userName)) { logger.info("User Name Exists"); return true; }else{ logger.info("User Name Does NOT Exists"); return false; } }catch(Exception e){ logger.info(e.getMessage()); return false; } }
FireBug Console Error:
GET http://localhost:8084/crimeTrack/validateUserName.htm?userName=hello 500 Internal Server Error 70ms jquery.min.js (line 2) "NetworkError: 500 Internal Server Error - http://localhost:8084/crimeTrack /validateUserName.htm?userName=hello"
TomCat Error Log:
com.crimetrack.web.OfficerRegistrationController.validateUserName(java.lang.String,com.crimetrack.business.Officers,org.springframework.validation.BindingResult,org.springframework.ui.ModelMap) throws java.lang.Exception 306270 [http-8084-1] DEBUG com.crimetrack.web.OfficerRegistrationController - Inside Controller validateUserName 306270 [http-8084-1] DEBUG com.crimetrack.web.OfficerRegistrationController - The user name that came in is hello 306270 [http-8084-1] INFO com.crimetrack.service.ValidateUserNameManager - Inside Do UserNameExist 306270 [http-8084-1] DEBUG com.crimetrack.jdbc.JdbcOfficersDAO - About to check if officers existing 306270 [http-8084-1] INFO com.crimetrack.jdbc.JdbcOfficersDAO - User Name Found 1 306270 [http-8084-1] INFO com.crimetrack.jdbc.JdbcOfficersDAO - User Name Found 2 306270 [http-8084-1] DEBUG org.springframework.jdbc.core.JdbcTemplate - Executing prepared SQL query 306270 [http-8084-1] DEBUG org.springframework.jdbc.core.JdbcTemplate - Executing prepared SQL statement [SELECT userName FROM crimetrack.tblofficers WHERE userName = ?] 306270 [http-8084-1] DEBUG org.springframework.jdbc.datasource.DataSourceUtils - Fetching JDBC Connection from DataSource 306285 [http-8084-1] DEBUG org.springframework.jdbc.core.StatementCreatorUtils - Setting SQL statement parameter value: column index 1, parameter value [hello], value class [java.lang.String], SQL type unknown 306289 [http-8084-1] DEBUG org.springframework.jdbc.datasource.DataSourceUtils - Returning JDBC Connection to DataSource 306289 [http-8084-1] INFO com.crimetrack.jdbc.JdbcOfficersDAO - Incorrect result size: expected 1, actual 0 306289 [http-8084-1] DEBUG org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver - Resolving exception from handler [com.crimetrack.web.OfficerRegistrationController@a32cdd]: java.lang.IllegalArgumentException: Invalid handler method return value: false 306289 [http-8084-1] DEBUG org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver - Resolving exception from handler [com.crimetrack.web.OfficerRegistrationController@a32cdd]: java.lang.IllegalArgumentException: Invalid handler method return value: false 306289 [http-8084-1] DEBUG org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver - Resolving exception from handler [com.crimetrack.web.OfficerRegistrationController@a32cdd]: java.lang.IllegalArgumentException: Invalid handler method return value: false 306290 [http-8084-1] DEBUG org.springframework.web.servlet.DispatcherServlet - Cleared thread-bound request context: org.apache.catalina.connector.RequestFacade@1cbab62 306290 [http-8084-1] DEBUG org.springframework.web.servlet.DispatcherServlet - Could not complete request java.lang.IllegalArgumentException: Invalid handler method return value: false at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter$ServletHandlerMethodInvoker.getModelAndView(AnnotationMethodHandlerAdapter.java:971) at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:438) at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:424) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778) at javax.servlet.http.HttpServlet.service(HttpServlet.java:617) at javax.servlet.http.HttpServlet.service(HttpServlet.java:717) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:602) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489) at java.lang.Thread.run(Unknown Source) 306290 [http-8084-1] DEBUG org.springframework.web.context.support.XmlWebApplicationContext - Publishing event in WebApplicationContext for namespace 'crimetrack-servlet': ServletRequestHandledEvent: url=[/crimeTrack/validateUserName.htm]; client=[127.0.0.1]; method=[GET]; servlet=[crimetrack]; session=[null]; user=[null]; time=[28ms]; status=[failed: java.lang.IllegalArgumentException: Invalid handler method return value: false] 306290 [http-8084-1] DEBUG org.springframework.web.context.support.XmlWebApplicationContext - Publishing event in Root WebApplicationContext: ServletRequestHandledEvent: url=[/crimeTrack/validateUserName.htm]; client=[127.0.0.1]; method=[GET]; servlet=[crimetrack]; session=[null]; user=[null]; time=[28ms]; status=[failed: java.lang.IllegalArgumentException: Invalid handler method return value: false]
OfficerRegistrationController
package com.crimetrack.web; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import org.apache.log4j.Logger; import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.beans.propertyeditors.StringTrimmerEditor; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.crimetrack.business.Login; import com.crimetrack.business.Officers; import com.crimetrack.service.DivisionManager; import com.crimetrack.service.GenderManager; import com.crimetrack.service.OfficerRegistrationValidation; import com.crimetrack.service.PositionManager; import com.crimetrack.service.ValidateUserNameManager; @Controller public class OfficerRegistrationController { private final Logger logger = Logger.getLogger(getClass()); private DivisionManager divisionManager; private PositionManager positionManager; private GenderManager genderManager; private Officers officer = new Officers(); private ValidateUserNameManager validateUserNameManager; Map<String, Object> myDivision = new HashMap<String, Object>(); Map<String, Object> myPosition = new HashMap<String, Object>(); Map<String, Object> myGender = new HashMap<String, Object>(); OfficerRegistrationValidation validateData = new OfficerRegistrationValidation(); @InitBinder("officers") protected void initBinder(WebDataBinder binder){ //removes white spaces binder.registerCustomEditor(String.class, new StringTrimmerEditor(true)); //formats date SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); //By passing true this will convert empty strings to null binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); dateFormat.setLenient(false); binder.setValidator(new OfficerRegistrationValidation()); } @RequestMapping(value="officer_registration.htm", method = RequestMethod.GET) public ModelAndView loadPage(HttpServletRequest request, HttpServletResponse response,@ModelAttribute Officers officer, BindingResult result, ModelMap m, Model model) throws Exception { try{ logger.debug("In Http method for OfficerRegistrationController"); myDivision.put("divisionList", this.divisionManager.getDivisions()); myPosition.put("positionList", this.positionManager.getPositionList()); myGender.put("genderList", this.genderManager.getGenderList()); model.addAttribute("division", myDivision); model.addAttribute("position", myPosition); model.addAttribute("gender", myGender); return new ModelAndView("officer_registration"); }catch(Exception e){ request.setAttribute("error",e.getMessage()); return new ModelAndView("error_page"); } } @RequestMapping(value="officer_registration.htm", method=RequestMethod.POST) public ModelAndView handleRequest(@Valid @ModelAttribute Officers officer, BindingResult result, ModelMap m, Model model)throws Exception{ if(result.hasErrors()){ model.addAttribute("division", myDivision); model.addAttribute("position", myPosition); model.addAttribute("gender", myGender); return new ModelAndView("officer_registration"); }else{ return null; } } @RequestMapping(value="validateUserName.htm", method=RequestMethod.GET) public boolean validateUserName(@RequestParam String userName, @ModelAttribute Officers officer, BindingResult result, ModelMap m)throws Exception{ try{ logger.debug("Inside Controller validateUserName"); logger.debug("The user name that came in is " + userName); if (validateUserNameManager.DoesUserNameExist(userName)== true){ return true; } return false; // return true; }catch(Exception e){ logger.debug("Error in validateUserName Controller " + e.getMessage()); return false; } } public void setDivisionManager(DivisionManager divisionManager){ this.divisionManager = divisionManager; } public void setPositionManager(PositionManager positionManager){ this.positionManager = positionManager; } public void setGenderManager(GenderManager genderManager){ this.genderManager = genderManager; } /** * @return the validateUserNameManager */ public ValidateUserNameManager getValidateUserNameManager() { return validateUserNameManager; } /** * @param validateUserNameManager the validateUserNameManager to set */ public void setValidateUserNameManager( ValidateUserNameManager validateUserNameManager) { this.validateUserNameManager = validateUserNameManager; } /** * @return the officer */ public Officers getOfficer() { return officer; } /** * @param officer the officer to set */ public void setOfficer(Officers officer) { this.officer = officer; } }
-11935566 0 From the top of my mind:
void * const var; // The pointer is constant and var can change const void * var; // The pointer can change but not var
so I would think that your syntax
const void * const *ptr;
means that ptr is a pointer to a pointer. So ptr would point to an address and that address cannot change (the first const). Also the address that ptr is located cannot change (the second const). But I am not totally sure of this.
-33791188 0Your getting that error because your building against the simulator in Xcode.
Switch to your device and this goes away.
If you didn't intent to run against the bundle re-comment this in AppDelegate.m
jsCodeLocation = [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
and turn your local dev server back on:
jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/index.ios.bundle?platform=ios&dev=true"];
-29518495 0 pyinstaller single exe of program which uses google api client lib I have a python program which I've successfully packaged up as a single exe using pyinstaller in the past. Recently I added new features which make use of the google api python client ( https://developers.google.com/api-client-library/python/ ). I've attempted to make a new single exe package of the new version and it fails to run.
I enable debugging and the console and initially the issue was that it hadn't picked up the oauth lib. I fixed that by adding the following to my spec file:
hiddenimports=['googleapiclient', 'apiclient']
When I build I can see this:
53092 INFO: Hidden import 'googleapiclient' has been found otherwise 53093 INFO: Hidden import 'apiclient' has been found otherwise
However, now when I run the rebuilt exe I get the following error before it exits:
pkg_resources.DistributionNotFound: google-api-python-client
I can't see any reference to that and I'm not sure how to force it to be packaged up with the exe.
I figure I can't be the only person to have ever wanted to package up a python program that makes use of the google api, but I failed to find any help during a lot of time with my friend google...
Any tips?
-3290669 0You could look at the trace module in the standard library, which
allows you to trace program execution, generate annotated statement coverage listings, print caller/callee relationships and list functions executed during a program run. It can be used in another program or from the command line.
You can also log to disk:
import sys import trace # create a Trace object, telling it what to ignore, and whether to # do tracing or line-counting or both. tracer = trace.Trace( ignoredirs=[sys.prefix, sys.exec_prefix], trace=0, count=1) # run the new command using the given tracer tracer.run('main()') # make a report, placing output in /tmp r = tracer.results() r.write_results(show_missing=True, coverdir="/tmp")
-33326362 0 Check that your "client" table allows ID value as NULL. I believe that's the problem because if you setup your table correctly that would be your primary key which should not be NULL.
-21430842 0It's a conflict of slugs.
You will get conflicts if you have the same slug for a page and a CPT that uses that too. So for you, your CPT is using 'product
', and your page is too. That's conflicting and causing the 404.
Rename your page Product Info
page' slug to product-info
.
For safety purposes flush your permalink cache by setting them to Default, saving, then saving them as what you had previously.
-14244807 0 Line feed is being removed from echo when called in double-quotesI'm trying to populate a shell variable called $recipient
which should contain a value followed by a new-line.
$ set -x # force bash to show commands as it executes them
I start by populating $user
, which is the value that I want to be followed by the newline.
$ user=user@xxx.com + user=user@xxx.com
I then call echo $user
inside a double-quoted command substitution. The echo
statement should create a newline after $user
, and the double-quotes should preserve the newline.
$ recipient="$(echo $user)" ++ echo user@xxx.com + recipient=user@xxx.com
However when I print $recipient
, I can see that the newline has been discarded.
$ echo "'recipient'" + echo ''\''recipient'\''' 'recipient'
I've found the same behaviour under bash versions 4.1.5 and 3.1.17, and also replicated the issue under dash.
I tried using "printf" rather than echo; this didn't change anything.
Is this expected behaviour?
-1035520 0Try "cleaning" the solution, i.e. delete (rename) all temporary files like *.ncb, *.suo etc that have been created by Visual Studio. One of these files might have got corrupted (Your problem sounds like the IntelliSense database is broken).
-22243004 0Solved: replace '@' character with '%40' at parse time it will automatically got converted to '@'.
URL url = new URL("ftp://p%40g.com:g%401234@ftp.xyz.com/testjar/2014-03-06-p.txt;type=i"); URLConnection urlc = url.openConnection(); OutputStream os = urlc.getOutputStream(); // To upload OutputStream buffer = new BufferedOutputStream(os); PrintStream output = new PrintStream(buffer); output.print("wowhii"); buffer.close(); os.close(); output.close();
-12796529 0 If you still need to write code under -(void)methodA
do
-(void)methodA { if(!isKeyBoarHidden){ [textField resignFirstResponder]; } else{ //code here } } - (void)keyboardHidden:(NSNotification *)notification { isKeyBoarHidden = YES; [self methodA]; }
sometime it may be helpful if we have some local variables inside methodA
and we dont need to make variables global.
I ended up using this middleware https://github.com/rs/cors, and that got everything working correctly.
-4992848 0As a starting point I'd look at the WinSock API. You may find a way of pulling traffic information on a per process basis. If you want to see total network usage, I'd use the Performance Monitoring tools. I found this example from a web search:
private static void ShowNetworkTraffic() { PerformanceCounterCategory performanceCounterCategory = new PerformanceCounterCategory("Network Interface"); string instance = performanceCounterCategory.GetInstanceNames()[0]; // 1st NIC ! PerformanceCounter performanceCounterSent = new PerformanceCounter("Network Interface", "Bytes Sent/sec", instance); PerformanceCounter performanceCounterReceived = new PerformanceCounter("Network Interface", "Bytes Received/sec", instance); for (int i = 0; i < 10; i++) { Console.WriteLine("bytes sent: {0}k\tbytes received: {1}k", performanceCounterSent.NextValue() / 1024, performanceCounterReceived.NextValue() / 1024); Thread.Sleep(500); } }
-16382578 0 Stopping UIScrollView at specific place while scrolling with pagingEnabled I have the following code to create a scroll view with additional area at the beginning and the end of the images (50 points).
UIScrollView* scroll = [[UIScrollView alloc] initWithFrame: CGRectMake(0,0,200,100)]; scroll.contentSize = CGSizeMake(400,100); UIImageView* img1 = [[UIImageView alloc] initWithFrame: CGRectMake(50,0,100,100); UIImageView* img2 = [[UIImageView alloc] initWithFrame: CGRectMake(150,0,100,100); UIImageView* img3 = [[UIImageView alloc] initWithFrame: CGRectMake(250,0,100,100); //Adding images to ImageViews scroll.pagingEnabled = YES; [scroll addSubView:img1]; [scroll addSubView:img2]; [scroll addSubView:img3];
The first time I see the view, I will see the additional area on the left (0-50), then the first image (50-150) and then half of the second image (150-200). When I swipe left, I want to see half of the first image on the right, the second image at the center, and half of the third image on the right.
When I swipe left again, I want to see the third image at center, with half of the second image on the left, and the additional area on the right.
Can it be possible?
-13107387 0I guess you may be seeing a NPE, as you may be violating the paragraph you were citing:
String custData = custFacade.find(customerId).toString();
The find
seems to implicitly querying for the object (as you describe), which may not be fully synced to the database and thus not yet accessible.
I am trying to code an alternative to LoadLibrary function, based on the idea of calling the function LdrLoadDll from ntdll. This function needs as a parameter the dll file to load, in a UNICODE_STRING format. I really can't get what I am doing wrong here (string seems to be correctly initialized), but when LdrLoadDll is called, I get the following error:
Unhandled exception in "Test.exe" (NTDLL.DLL): 0xC0000005: Access Violation.
I use Visual C++ 6.0 for this test, and I am using Windows 7 64 bit.
I post full code here, thanks in advance for any help:
#include <Windows.h> typedef LONG NTSTATUS; //To be used with VC++ 6, since NTSTATUS type is not defined typedef struct _UNICODE_STRING { //UNICODE_STRING structure USHORT Length; USHORT MaximumLength; PWSTR Buffer; } UNICODE_STRING; typedef UNICODE_STRING *PUNICODE_STRING; typedef NTSTATUS (WINAPI *fLdrLoadDll) //LdrLoadDll function prototype ( IN PWCHAR PathToFile OPTIONAL, IN ULONG Flags OPTIONAL, IN PUNICODE_STRING ModuleFileName, OUT PHANDLE ModuleHandle ); /************************************************************************** * RtlInitUnicodeString (NTDLL.@) * * Initializes a buffered unicode string. * * RETURNS * Nothing. * * NOTES * Assigns source to target->Buffer. The length of source is assigned to * target->Length and target->MaximumLength. If source is NULL the length * of source is assumed to be 0. */ void WINAPI RtlInitUnicodeString( PUNICODE_STRING target, /* [I/O] Buffered unicode string to be initialized */ PCWSTR source) /* [I] '\0' terminated unicode string used to initialize target */ { if ((target->Buffer = (PWSTR) source)) { unsigned int length = lstrlenW(source) * sizeof(WCHAR); if (length > 0xfffc) length = 0xfffc; target->Length = length; target->MaximumLength = target->Length + sizeof(WCHAR); } else target->Length = target->MaximumLength = 0; } NTSTATUS LoadDll( LPCSTR lpFileName) { HMODULE hmodule = GetModuleHandleA("ntdll.dll"); fLdrLoadDll _LdrLoadDll = (fLdrLoadDll) GetProcAddress ( hmodule, "LdrLoadDll" ); int AnsiLen = lstrlenA(lpFileName); BSTR WideStr = SysAllocStringLen(NULL, AnsiLen); ::MultiByteToWideChar(CP_ACP, 0, lpFileName, AnsiLen, WideStr, AnsiLen); UNICODE_STRING usDllFile; RtlInitUnicodeString(&usDllFile, WideStr); //Initialize UNICODE_STRING for LdrLoadDll function ::SysFreeString(WideStr); NTSTATUS result = _LdrLoadDll(NULL, LOAD_WITH_ALTERED_SEARCH_PATH, &usDllFile,0); //Error on this line! return result; } void main() { LoadDll("Kernel32.dll"); }
-38543468 1 php shell_exec won't run a working shell script? I want to run a python script independent of apache. I wrote a shell script containing the following
#!/bin/bash sudo nohup python dejavu/sniffer.py $1 $2 $3 > /var/log/apache2/sniffer.log 2>&1 & echo $!
for some reason the following does nothing however, it does return a PID.
$cmd = ' ./sniffer.sh '.$audioStream." ".$content_type." ".$bit_rate; $command = escapeshellcmd($cmd); $out = shell_exec($command)
The shell script works fine on it's own. exec($cmd) does nothing as well.
I have checked the disabled functions in the ini file, thats not the issue.
-40798146 0 accessing class instances in all classesFor a school assignment, I have created a program that add and searches for products, the adding and searching are performed in the class EStoreSearch
, I've created 3 other classes to create GUI JFrames
. My question is how do I allow the JFrame
classes to access the same instance of the EStoreSearch
class that stores the ArrayList
data(which stores all the products) so that I can add and search for products in the GUI?
I think that the term you're looking for is Software Configuration Management. There's a pretty hefty document about it here too: http://www.sei.cmu.edu/reports/87cm004.pdf.
-16819118 0 AnythingSlider in a "random access" modeI would like to use AnythingSlider to implement a multiple-panel login dialog. One requirement is that I will want to navigate to different panels in a random order, and I want the transitions to only show the source and destination panels, none of the intervening ones.
For example:
Navigation between panels is controlled by buttons and logic outside of the slider element.
If the user starts at Panel 1, and wants to try Password Recovery, I would like to slide in Panel 3 from the right without seeing panel 2 on the way by.
Is there a way to accomplish this with AnythingSlider?
-33460100 0 What's wrong with my CodeEval challenge solution?I'm new to coding, and after doing some online tutorials I decided to do a few challenges on CodeEval, and just got the balls to try a hard one. I submitted my solution, and it says it's partially solved, and I just can't figure out what I'm doing wrong. I'm not sure if these challenges are something that I'm supposed to do 100% on my own, in which case I won't submit a solution that includes any input from people on here. I just want to know what I should do better.
Here is the link to the challenge: https://www.codeeval.com/open_challenges/126/
And here is my code (JavaScript):
function compareSegments(segment1, segment2) { var totalMisMatches = 0; for (var i = 0; i < segment1.length; i++) { if (segment1[i] != segment2[i]) { totalMisMatches++; } } return totalMisMatches; } function makeInnerSegment(array, index, length) { var newArray = []; for (var j = 0; j < length; j++) { newArray.push(array[index + j]); } return newArray; } function compare(a, b) { for (var i = 0; i < a.length; i++) { if (a[i] < b[i]) { return -1; } if (a[i] > b[i]) { return 1; } } return 0; } function makeArrayOfPossibleSegments(array, segment, maxMismatches) { var newArray = []; for (var i = 0; i <= array.length - segment.length; i++) { var innerSegment = makeInnerSegment(array, i, segment.length); var mismatches = compareSegments(segment, innerSegment); if (!(mismatches > maxMismatches)) { innerSegment.unshift(mismatches); newArray.push(innerSegment); } } return newArray.sort(compare); } var fs = require("fs"); fs.readFileSync(process.argv[2]).toString().split('\n').forEach(function (line) { if (line !== "") { var output = ""; var splitArray = line.split(" "); var DNASegment = splitArray[0].split(""); var maxMisMatches = parseInt(splitArray[1]); var DNAString = splitArray[2].split(""); var possibleSegments = makeArrayOfPossibleSegments(DNAString, DNASegment, maxMisMatches); if (possibleSegments.length === 0) { output = "No match"; } else { for (var i = 0; i < possibleSegments.length; i++) { for (var j = 1; j < possibleSegments[i].length; j++) { output += possibleSegments[i][j]; } output += " "; } output = output.substring(0, output.length - 1) } console.log(output); } });
-23563835 0 You are close.
What you are doing:
Tag
of TreeView
to its own DataContext
. This is unnecessary.Tag.MyText
from your ContextMenu.PlacementTarget
- which is TextBlock
. The TextBlock
has no Tag
set.What you should do:
Tag
of the TextBlock to DataContext
of the Window (Window is TextBlock
ancestor and you should look it up via RelativeSource Mode=FindAncestor
).TextBlock.Tag
set in the first step.I have a situation where an element is shown using ajax. I have attached mouseenter and mouseleave events to it to show a menu connected to the element using prototype. This works fine, but the problem I am having is that if a user has his/her mouse in the place where the element is shown before it is shown, the mouseenter does not get triggered and the attached menu does not get shown. I already have an afterFinish function that is called after a SlideDown effect, so I was thinking I could put another function in there to check if the users mouse is over the element or not. How would I go about checking what element the users mouse is over in prototype?
-13196477 0consider each part of the order by as a different column... Apply a case to each component. Get the first part first... then the second part. If it doesn't apply to the second part, just have it always the same value... something like...
ORDER BY CASE WHEN PortalName = 'Company, Inc' THEN 1 WHEN PortalName = 'Setup' THEN 2 WHEN PortalName = 'Daily Routine' THEN 3 WHEN PortalName = 'Master Option' THEN 4 ELSE 5 END, CASE WHEN IsActive = 1 THEN 1 ELSE 2 END, PortalName ASC
-13258264 0 textBox1.Enter += new EventHandler(txtSearch_TextChanged); private void txtSearch_TextChanged(object sender, EventArgs e) { foreach (TreeNode node in this.treeView1.Nodes) { if (node.Text.ToUpper().Contains(this.textBox1.Text.ToUpper())) { treeView1.Select(); // First give the focus to the treeview control, //doing this, the control is able to show the selectednode. treeView1.SelectedNode = node; break; } }
-32993646 0
-40630263 0 This is happening because you're calling message+=
on a null
string, so you're adding currentLine
to null.
Simplest fix would be to set massage
to ""
when you initialise it:
String message = ""; //Rest of code...
-32441279 0 How can I add custom entries into iOS watchKit extension info.plist? I use info.plist to define variables into my app and its today extension.
But I can't add those variables to the WatchKit
info.plist without getting an error while building :
Am I missing something?
(xCode 7.0 beta 6)
-10589688 0If what you're talking about is the space in between each box, the class "box" is inline-block, so the line-breaks in the markup are interpreted as implied spaces. Place all the inline-block markup on a single line <div></div><div></div>...
and the "space" between will collapse.
I have adapted the solution from http://craftycodeblog.com/2010/05/15/asp-net-mvc-render-partial-view-to-string/ to your case.
Change your code from project B to this:
public ActionResult Index() { var form = pa.Index(); // <-- This is the controller from controller A using (var sw = new StringWriter()) { // Find the actual partial view. var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, form.ViewName); // Build a view context. var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw); // Render the view. viewResult.View.Render(viewContext, sw); // Get the string rendered. ViewBag.CMSForm = sw.GetStringBuilder().ToString(); } return View(); }
-9614206 0 Without knowing the contents of 'BBnormalLinks.txt' or the final value of $rand_link, it is difficult to say precisely what is going wrong.
Your usage of file()
and mt_rand()
appear to be correct, though you aren't doing anything to ensure that you are getting a valid URL.
This is purely conjecture, but I suspect that you don't have PHP properly configured to display errors. If the file fails to load, $links will have a null value going into your penultimate line. You will then try to access element 0 of a null array and receive an empty value. This will result in header('refresh:2;url=')
and your page will simply refresh itself every 2 seconds.
I am trying to customize the font on my Navigation Bar. Everything is fine except for some reason, when the title is too long for the Navigation Bar, it gives me a semicolon instead of ellipses (...)
How do I get the ... to show that the title is cut off?
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, 240, 24)]; label.backgroundColor = [UIColor clearColor]; label.font = [UIFont fontWithName:@"My Font" size:20.0]; label.numberOfLines = 1; label.lineBreakMode = NSLineBreakByTruncatingTail; label.textAlignment = UITextAlignmentCenter; label.textColor =[UIColor whiteColor]; label.text=@"Some Really Long Title Name That's Normally Dynamic"; self.navigationItem.titleView = label;
So I want the Navigation Bar to say "Some Really Long Titl..." However it keeps saying "Some Really Long Title ;"
Thanks!
-28190598 0You could use CountDownLatch
In your main method, you could define how many threads you would have, inject it within each of your threads and wait for their completion. Once a thread completes, its would call countdown api and once all your thread completes, your main method can continue further.
-28691322 0Because .validation-alert
is not the next sibling of .validation-control-is-not-empty
, they are the children of same tr
, so you can find the tr
parent of this
and then find the .validation-alert
element within it.
$('.validation-control-is-not-empty').focusout(function () { if ($(this).val() === '') { $(this).closest('tr').find('.validation-alert').show(); } else { $(this).closest('tr').find('.validation-alert').hide(); } });
You can shorten it using .toggle() like
$('.validation-control-is-not-empty').focusout(function () { $(this).closest('tr').find('.validation-alert').toggle($(this).val() === ''); });
Demo: Fiddle
-2329375 0My 2 cents:
I am pretty sure I will get some downvotes if BlazeDS implements all of the above, but I didn't like what I found that was native to it, and I thought that using annotations was a good solution, especially because we were using annotations anyway to mark the methods that were BlazeDS methods (so IntelliJ would stop bothering us about methods that are not called anywhere).
-15320946 0You should build an url get parameter string:
<script> $(function() { var data = {kid:[]}; // we put here all checkbox value $("input[type=checkbox][checked]").each(function() { //iterate over all checked checkboxes data.kid.push($(this).attr('id')); //push the id of checkbox to data.kid array }); $("#kontakte_bezButton1_{kontakte_bez:rowNumber}").colorbox({ href:"testpage1.php?" + $.param(data), //create $_GET parameter string iframe:true, innerWidth:850, innerHeight:400, opacity:0.1, overlayClose:false }); }); </script>
The $.param function (http://api.jquery.com/jQuery.param/) generates get parameter string from an object. in this example the result like this:
kid[]=1&kid[]=4&.... (in urlencoded format: kid%5B%5D=1&kid%5B%5D=4 )
-26188795 0 Let's see if simplifying the code a bit can give a clearer picture:
if answer == "yes" return true elsif answer == "no" return false end puts "something"
is the most relevant part here. With the explicit return
, the code exits from the method and never reaches the puts
. The return value is therefore true
or false
.
Without the explicit return
:
if answer == "yes" true elsif answer == "no" false end puts "something"
The true
and false
statements merely exit the if-else
code and executes the puts
, the return value of which is nil
.
My rails_admin new action button is not shown on web UI.
My Initializers file
RailsAdmin.config do |config| config.actions do dashboard # mandatory index # mandatory new export # bulk_delete show edit delete do except ['Admin'] end end end
My admin_ability file
class AdminAbility include CanCan::Ability def initialize(user) roles = user.roles.collect(&:name) if !roles.blank? can :access, :rails_admin can :dashboard if roles.include?('admin') can :manage, [Admin, Music, Hobby, Cuisine] can :read, [User] end end end end
My Model:
class Music include Mongoid::Document include Mongoid::Timestamps field :name, :type => String mount_base64_uploader :image, AvatarUploader index({updated_at: -1}) index({created_at: -1}) validates :name, :presence => true has_and_belongs_to_many :users rails_admin do list do field :id field :name end show do field :_id field :name field :image end create do field :name field :image end edit do field :image end end end
My Gemfile.lock
rails_admin (0.8.1)
There is no option to add new music.
I have tried to do only method in initializer file by doing
new do only [Music] end
Help is appreciated.
-21628600 0 haskell problems with Data.Map updateI am trying to edit the vertices. I can add to it, but when I use update I get:
Couldn't match expected type `(GLfloat, GLfloat, GLfloat) -> Maybe (GLfloat, GLfloat, GLfloat)' with actual type `(t0, t1, t2)' In the first argument of `Map.update', namely `(- 0.75, 0.25, 0.0)' In the expression: Map.update (- 0.75, 0.25, 0.0) "v1" faceMap In an equation for `it': it = Map.update (- 0.75, 0.25, 0.0) "v1" faceMap
import qualified Data.Map as Map import Graphics.UI.GLUT import Graphics.Rendering.OpenGL faceMap :: Map.Map [Char] (GLfloat, GLfloat, GLfloat) faceMap = Map.fromList $ [("v1", (-0.25, 0.25, 0.0 )) ,("v1", (0.75, 0.35, 0.0)) ,("v3", (0.75, -0.15, 0.0)) ,("v4", (-0.75, -0.25, 0.0)) ]
If you know another way other than editing values that would be great, and yes this is OpenGL.
-37175314 0It sounds like what you're after is to make the fit closer to linear in-between, I think you can force that by interpolating the midpoint as a real point:
dat2 = data.frame(x = union(dat$x,dat$x - c(0,diff(dat$x)/2)), y = interp1(dat$x,dat$y,xi = union(dat$x,dat$x - c(0,diff(dat$x)/2))))
(interp1
may be unnecessary here, union(dat$y,dat$y - c(0,diff(dat$y)/2))
should do the same, but the code above works.)
EDIT: Note, in order for diff
to work, you need your data to be properly ordered first
this creates a new data.frame with points in between the previous ones, if you now spline it, you are weighting a more linear fit
EDIT2: You could also use smoothing splines with weights this way, and set the weights of the points in between lower than the weights of the primary points:
mod <- splinefun(dat$x, dat$y,method = 'monoH.FC') mod2 <- data.frame(x = seq(0.333, 5, by = 0.1), y = mod(seq(0.333, 5, by = 0.1))) # A set of weights, where each point in-between is weighted half as much dat2$w <- rep(c(0.5,1),ceiling(length(dat2$x)/2))[-1] # Smoothing Spline modelspline <- smooth.spline(dat2$x, dat2$y,dat2$w) # Plot points xplot <- seq(min(dat2$x),max(dat2$x),by = 0.1) # And Plot comparison ggplot() + geom_point(data = dat, aes(x = x, y = y)) + geom_line(data = mod2, aes(x = x, y = y)) + geom_line(data = data.frame(predict(modelspline,xplot)), aes(x = x, y = y),color = 'red')
-31988541 0 Your problem can be solved by following these steps
Step 1:
Add these two packages to your project (jackcess-encrypt.jar, bcprov-jdk15on-152.jar)
You can download the two packages from the following links:
Jackcess Encrypt
Bouncy Castle
Step 2:
You have to add this class to your project folder
import java.io.File; import java.io.IOException; import net.ucanaccess.jdbc.JackcessOpenerInterface; import com.healthmarketscience.jackcess.CryptCodecProvider; import com.healthmarketscience.jackcess.Database; import com.healthmarketscience.jackcess.DatabaseBuilder; public class CryptCodecOpener implements JackcessOpenerInterface { @Override public Database open(File fl,String pwd) throws IOException { DatabaseBuilder dbd =new DatabaseBuilder(fl); dbd.setAutoSync(false); dbd.setCodecProvider(new CryptCodecProvider(pwd)); dbd.setReadOnly(false); return dbd.open(); } //Notice that the parameter setting autosync =true is recommended with UCanAccess for performance reasons. //UCanAccess flushes the updates to disk at transaction end. //For more details about autosync parameter (and related tradeoff), see the Jackcess documentation. }
like this
step 3:
use the following connection code
public void connectToDB(){ try { conn = DriverManager.getConnection("jdbc:ucanaccess://words.accdb;jackcessOpener=CryptCodecOpener", "user", "pass"); } catch (SQLException ex) { ex.printStackTrace(); } }
be careful
-change words.accdb to the name of your Access database
-the "user" can be empty or username of your computer or something else
-the "pass" must be the password of your Access file.
I have a SQLITE3 database wherein I have stored various columns. One column (cmd) in particular contains the full command line and associated parameters. Is there a way to extract just the first word in this column (just before the first space)? I am not interested in seeing the various parameters used, but do want to see the command issued.
Here's an example:
select cmd from log2 limit 3;
user-sync //depot/PATH/interface.h user-info user-changes -s submitted //depot/PATH/build/...@2011/12/06:18:31:10,@2012/01/18:00:05:55
From the result above, I'd like to use an inline SQL function (if available in SQLITE3) to parse on the first instance of space, and perhaps use a left function call (I know this is not available in SQLITE3) to return just the "user-sync" string. Same for "user-info" and "user-changes".
Any ideas?
Thanks.
-27662985 0 SimpleDB SDB machine hours - How to check?So I know the AWS console removed simpleDB a little ago to promote DynamoDB, but how do you track how many "machine hours" you have consumed so far?
Ive read AWS documentation pretty thoroughly and several forums posts but most people just address the issue that machine hours are hard to estimate, but doesnt mention HOW to actually monitor the current usage.
Thanks
-9967575 0You could also use the Files.move
utility from Google Guava libraries to rename a file. Its easier than writing your own method.
From the docs:
-27712669 0 Best way to implement view like mapMoves the file from one path to another. This method can rename a file or move it to a different directory, like the Unix mv command.
I'm making view that represent something like map, with pan and pinch gestures. At current moment it's implemented via overriden drawRect that called in handlePan with setNeedsDisplay. So, the resulting performance a little bit awkward. Is there any more appropriate approaches?
-22228908 0I would add a ng-model on your select and then add a watch in your directive. Pass your variable into the directive and output your desired result. Pseudo code:
<select ng-model="myList" class="ng-scope ng-pristine ng-invalid ng-invalid-required"> <option value="" selected="selected" class="">Seleccione un estado</option> </select> <span state selectedItem="myList"></span>
and your directive might look like:
directive('state', ['$http', function($http){ return { restrict: 'A', scope: { myList: '=myList' }, link: function(scope, element, attrs) { scope.$watch('myList', function (newValue, oldValue) { console.log(changed); } } } }])
-12247660 0 I assume that a.ids
is some kind of id list, so you could use the find_in_set()
function:
select * from table1 a join table2 b on find_in_set(b.id, a.ids) > 0
-27396825 0 Try This:-
$('body').on('focus', '.datepicker_input', function() { $(this).datepicker({ dateFormat: 'dd-MM-yy', defaultDate: $(this).val(), ... }); });
-2579360 0 As far as syntax goes, you can use the null-coalescing operator if you want to be fancy, but it's not necessarily as readable.
get { return notes ?? (notes = CalcNotes()); }
Edit: Updated courtesy of Matthew. Also, I think the other answers are more helpful to the question asker!
-6139788 0Yes everything you've read is correct. Interlocked.Increment is designed so that normal reads will not be false while making the changes to the field. Reading a field is not dangerous, writing a field is.
-39978386 0This has been tested and works:
override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) tableView.contentSize.height = 2000 }
-7440844 0 If you are manipulating the components of a date you should use NSDateComponents
rather than trying to convert the date and process the string yourself.
In the documentation for NSDateFormatter it does mention that even hard coded formats like the one above may be overridden by locale specific settings.
-12250687 0 How do I debug certain Java classes with Eclipse?I have been using Eclipse for a year or so, and usually I have no problem debugging software. However, I have encountered a situation which has stumped me.
A test case which I am running is failing with the following stack trace:
com.sun.xml.internal.ws.protocol.soap.MessageCreationException: Couldn't create SOAP message due to exception: Unable to create StAX reader or writer at com.sun.xml.internal.ws.encoding.SOAPBindingCodec.decode(SOAPBindingCodec.java:283) at com.sun.xml.internal.ws.transport.http.client.HttpTransportPipe.process(HttpTransportPipe.java:180) at com.sun.xml.internal.ws.transport.http.client.HttpTransportPipe.processRequest(HttpTransportPipe.java:83) at com.sun.xml.internal.ws.transport.DeferredTransportPipe.processRequest(DeferredTransportPipe.java:105) at com.sun.xml.internal.ws.api.pipe.Fiber.__doRun(Fiber.java:587) at com.sun.xml.internal.ws.api.pipe.Fiber._doRun(Fiber.java:546) at com.sun.xml.internal.ws.api.pipe.Fiber.doRun(Fiber.java:531) at com.sun.xml.internal.ws.api.pipe.Fiber.runSync(Fiber.java:428) at com.sun.xml.internal.ws.client.Stub.process(Stub.java:211) at com.sun.xml.internal.ws.client.sei.SEIStub.doProcess(SEIStub.java:124) at com.sun.xml.internal.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:98) at com.sun.xml.internal.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:78) at com.sun.xml.internal.ws.client.sei.SEIStub.invoke(SEIStub.java:107) at $Proxy34.getCommission(Unknown Source) at uk.co.bglgroup.servicehub.external.lifehub.v1_0.fitnesse.ws.LifeHubWebServiceLifeHubWebServicePortClient.doCallGetCommission(LifeHubWebServiceLifeHubWebServicePortClient.java:51) at uk.co.bglgroup.servicehub.external.lifehub.v1_0.fitnesse.service.GetCommissionService.getCommissionService(GetCommissionService.java:40) at uk.co.bglgroup.servicehub.external.lifehub.v1_0.fitnesse.endToEnd.SkeletalEndToEndTest.run(SkeletalEndToEndTest.java:82) at uk.co.bglgroup.servicehub.external.lifehub.v1_0.fitnesse.endToEnd.SkeletalEndToEndTest.skeletalTestQA(SkeletalEndToEndTest.java:66) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184) at org.junit.runners.ParentRunner.run(ParentRunner.java:236) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) Caused by: com.sun.xml.internal.ws.streaming.XMLReaderException: Unable to create StAX reader or writer at com.sun.xml.internal.ws.api.streaming.XMLStreamReaderFactory$Default.doCreate(XMLStreamReaderFactory.java:358) at com.sun.xml.internal.ws.api.streaming.XMLStreamReaderFactory.create(XMLStreamReaderFactory.java:139) at com.sun.xml.internal.ws.api.streaming.XMLStreamReaderFactory.create(XMLStreamReaderFactory.java:143) at com.sun.xml.internal.ws.encoding.StreamSOAPCodec.decode(StreamSOAPCodec.java:290) at com.sun.xml.internal.ws.encoding.StreamSOAPCodec.decode(StreamSOAPCodec.java:118) at com.sun.xml.internal.ws.encoding.SOAPBindingCodec.decode(SOAPBindingCodec.java:278) ... 39 more Caused by: javax.xml.stream.XMLStreamException: java.net.MalformedURLException at com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl.setInputSource(XMLStreamReaderImpl.java:219) at com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl.<init>(XMLStreamReaderImpl.java:191) at com.sun.xml.internal.stream.XMLInputFactoryImpl.getXMLStreamReaderImpl(XMLInputFactoryImpl.java:279) at com.sun.xml.internal.stream.XMLInputFactoryImpl.createXMLStreamReader(XMLInputFactoryImpl.java:151) at com.sun.xml.internal.ws.api.streaming.XMLStreamReaderFactory$Default.doCreate(XMLStreamReaderFactory.java:356) ... 44 more Caused by: java.net.MalformedURLException at java.net.URL.<init>(URL.java:601) at java.net.URL.<init>(URL.java:464) at java.net.URL.<init>(URL.java:413) at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.setupCurrentEntity(XMLEntityManager.java:650) at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.startEntity(XMLEntityManager.java:1315) at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.startDocumentEntity(XMLEntityManager.java:1267) at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.setInputSource(XMLDocumentScannerImpl.java:281) at com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl.setInputSource(XMLStreamReaderImpl.java:206) ... 48 more
OK, so now I want to debug into the issue, and I can step down through the code I have written until I reach an object called SEIStub.class For this object, Eclipse is reporting "The source attachment does not include the source for file SEIStub.class"
If I select "Change Attached Source", then a box pops up which correctly identifies the location of src.zip within the correct JDK version. So nothing to change there ...
I have gone into the src.zip manually, and indeed there is no com.sun.internal folder.
One confusing aspect is that when I run my test in a development environment, everything works. When I run my test in a QA environment, I get the stack trace listed out above.
What is most confusing of all, is that although I can put a break point into com.sun.org.apache.xerces.internal.impl.XMLEntityManager, and I can reach that break point after passing through the SEIStub object, I am unable to view any of the variables within that program, and they do not even show up as valid variables when I look in the Eclipse Variables tab.
I am using JDK 1.6.0_25
Hmmm ... very confused and running out of hair to pull out !
Can anyone help me to get my debug operating on this class ?
Many Thanks, Mark
UPDATE: I have also tried downloading the http://openjdk.java.net/projects/jdk6/ and this set of source also seems to be missing all of the com.sun.internal objects.
UPDATE: I am using Eclipse Helios, and a colleague has repeated the same issue using Juno.
-142640 0Not with the default Route class, but you can make your own route class by deriving from RouteBase. You basically end up having to do all the work yourself of parsing the URL, but you can use the source from Route to help you get started.
-18316033 0Just change box #2 to float:right.
-14975130 0 iOS crash logs printed to consoleMy problem appeared when iOS 6 was introduced, but now seems to affect 5.1.1 too.
When the app crashes, the log is printed to the 'Console' and no 'Device Logs' is saved. This is frustrating in so many ways:
It may be worth mentioning, that we work with accessories and have no way to connect debugger at the same time.
An idea how to fix this would save my day, but any decent workaround will be good too.
Thank you
EDIT: 'Console' and 'Device Logs' are the ones I get in the Organizer.
-15728260 0ElementAt()
has to iterate from the beginning of the collection every time it's called. That's why it's so inefficient.
I would suggest another approach - save results generated after last save into a list, and save those results into file from there, not from HastSet
itself:
latest
list:
var latest = new List<string>();
Adding elements:
if(storage.Add(newElement)) { latest.Add(newElement); }
Saving latest to file:
foreach(var item in latest) { sb.AppendLine(item); } latest.Clear();
-2253950 0 Unit Testing Private Method in Resource Managing Class (C++) I previously asked this question under another name but deleted it because I didn't explain it very well.
Let's say I have a class which manages a file. Let's say that this class treats the file as having a specific file format, and contains methods to perform operations on this file:
class Foo { std::wstring fileName_; public: Foo(const std::wstring& fileName) : fileName_(fileName) { //Construct a Foo here. }; int getChecksum() { //Open the file and read some part of it //Long method to figure out what checksum it is. //Return the checksum. } };
Let's say I'd like to be able to unit test the part of this class that calculates the checksum. Unit testing the parts of the class that load in the file and such is impractical, because to test every part of the getChecksum()
method I might need to construct 40 or 50 files!
Now lets say I'd like to reuse the checksum method elsewhere in the class. I extract the method so that it now looks like this:
class Foo { std::wstring fileName_; static int calculateChecksum(const std::vector<unsigned char> &fileBytes) { //Long method to figure out what checksum it is. } public: Foo(const std::wstring& fileName) : fileName_(fileName) { //Construct a Foo here. }; int getChecksum() { //Open the file and read some part of it return calculateChecksum( something ); } void modifyThisFileSomehow() { //Perform modification int newChecksum = calculateChecksum( something ); //Apply the newChecksum to the file } };
Now I'd like to unit test the calculateChecksum()
method because it's easy to test and complicated, and I don't care about unit testing getChecksum()
because it's simple and very difficult to test. But I can't test calculateChecksum()
directly because it is private
.
Does anyone know of a solution to this problem?
-31471683 0 Mac: replace text inside files in directory using regular expressionI need to replace all matches (regular expression) in directory from "*::" to be "\*::" examples: (in multiple php files)
ID:: user:: process:: ....
to be:
\ID:: \user:: \process::
I currently use,single commands
find . -type f -name '*.php' -exec sed -i '' s/ID::/\\\\ID::/ {} + find . -type f -name '*.php' -exec sed -i '' s/user::/\\\\user::/ {} + find . -type f -name '*.php' -exec sed -i '' s/process::/\\\\process::/ {} +
how to write regular expression to replace any "*::" => "\*::"
thanks,
-31739018 0Are you trying to find the phrase _camera in the current selection? If so just use find and replace (ctrl + F) on the whole java file rather than Find in files and limiting the scope to the selection.
-5227908 0I made the following changes and things appear to be working as expected.
public class EntityResolver<id, entity> : ValueResolver<id, entity> where entity : Entity { protected override entity ResolveCore(id source) { if (source != null) return session.Get<entity>(source, LockMode.None); else return null; } }
...
cfg.CreateMap<CustomerEditModel, Customer>() .ForMember(d => d.SalesPerson, o => o.ResolveUsing<EntityResolver<Guid?, User>>().FromMember(s => s.SalesPerson));
-37461524 0 You could use an old javascript trick - an empty string is perceived is a false boolean.
-15124773 0 Highlight search results - whole expressions and single wordsI want highlight whole expresions and single words
$text ="text text aaa bbb ccc text aaa text xxaaayy text bbb ccc text bbb cccxxx text"; $words = array('aaa bbb ccc','aaa bbb','bbb ccc','aaa','bbb','ccc'); foreach ($words as $k=>$v){ $text = preg_replace('/(\w*?'.$v.'\w*)/i', '[b]$1[/b]', $text); }
this code will return:
text text [b][b]aaa[/b] [b]bbb[/b] [b]ccc[/b][/b] text [b]aaa[/b] text [b]xxaaayy[/b] text [b][b]bbb[/b] [b]ccc[/b][/b] text [b][b]bbb[/b] [b]cccxxx[/b][/b] text
how to get this result:
text text [b]aaa bbb ccc[/b] text [b]aaa[/b] text [b]xxaaayy[/b] text [b]bbb ccc[/b] text [b]bbb cccxxx[/b] text
how to modify preg_replace ?
-36366821 0Use the alternative <xsl:for-each>
notation to loop over a set of integers:
<xsl:for-each select="1 to 5"> ... '.' will be an integer from 1 to 5 here </xsl:for-each>
To create the filename from this, use
... fs:exists(fs:new(concat('/images/',$imageproductid,'_00', ., '.jpg')
and to create a properly named new element, use <xsl:element>
:
<xsl:element name="{concat('IMAGE', .)}"> .. <IMAGEx> contents .. </xsl:element>
You need the notation {..}
here because name
must be a valid QName (W3C, "11.2 Creating Element Nodes Using xsl:element
"), which I take as "the literal text must be a valid possible element name".
Putting that together, you end up with this concise code:
<xsl:template match="product"> <xsl:apply-templates /> <xsl:variable name="imageproductid" select="code" /> <xsl:for-each select="1 to 5"> <xsl:variable name="filename" select="concat('/images/',$imageproductid,'_00', ., '.jpg')" /> <xsl:if test="fs:exists(fs:new($filename))"> <xsl:element name="{concat('IMAGE', .)}"> <xsl:value-of select="$filename" /> </xsl:element> </xsl:if> </xsl:for-each> </xsl:template>
-28370643 0 It depends how much complexity is already in your GUI. If you have a hundred dialogs/controls then rewriting it in native C++ might be the wrong answer. In this case, making your GUI into a library makes more sense.
However, its probably a better option to keep your GUI as a process and build a proxy library in native C++ that passes the ICE calls onto your server. (so C++/CLI exe calls a function in a new C++ library that makes a ICE call to the server and vice-versa).
If your GUI is small, then rewriting it in a modern (and better supported that C++/CLI) system is the best thing. Qt is probably the ultimate in native GUIs nowadays (but there are alternatives such as MFC, or wxWidgets). Even in these cases, its still probably better to code your networking subsystem as a native library anyway. Then you can change your GUI and try out a load of the GUI stacks as you like, porting your game to Android or iOS with just 1 presentation layer change.
The third alternative is to choose a different comms system. Whilst RPC like ICE are nice, the 'where its at' today is web-based comms via REST services (try an embedded c++ webserver like Mongoose or NxWeb), if you need to push data back to the client, these support WebSockets, so will provide all the functionality you need. And then, you can rewrite your GUI to be HTML based!
So: put your comms in a native C++ library.
-3760600 0 Can android Emulate a HID device?I was attempting to design an app that would allow me to have android emulate a hardware device.
I.E. a generic keyboard, a generic mouse.
I could essentially plug in my android (HTC) to a computer, and program it to use a software keyboard as the computers hardware keyboard.
I don't have any direction on how to accomplish this.
I only wish to connect USB(not bluetooth). So that the computer needs 0 installation before working. And most devices will work in Dos Mode.
-19165754 0I think I have found a solution by using @Any or @ManyToAny annotation. Those are not standard JPA annotation but hibernate specific annotation.
-38852460 0 Login page redirect new page if sucessMy application uses Mithril.js and Play Framework.
I would like to know if there is a (good) way to divide my application between mithril and play. I would like to have play renders a login.html, this login.html will only contain only the import of my mithril.js component (login.js). If the login is a success I would like play to redirect my application to another html page. This pages will contain all the imports of all my mithril's components.
So my application will have only two html pages on the play framework side, one which imports only one mithril component and the other which import all the others components (only if credentials are checked).
Play router :
GET / controllers.Index.index
Play controller :
def index = Action { Ok(views.html.login()) }
login.html
<!DOCTYPE html> <html lang="en"> <head> <title>IHM</title> StylesSheet import.. </head> <body id="app" class="body"> <script src="https://cdnjs.cloudflare.com/ajax/libs/mithril/0.2.2-rc.1/mithril.min.js"></script> <script src="@routes.Assets.versioned("javascripts/claravista/login.js")" type="text/javascript"></script> <script type="text/javascript"> m.route.mode = "pathname"; m.route(document.getElementById('app'), "/", { "/": login, }); </script> </body>
Mithril ask play check credentials (in component login)
m.request({method: "PUT", url: "/check-user", data : login.user }).then(returnCall);
Case Credentials false : ask again (I already did this part)
Case Credentials true : redirect to another html page (How to do this?)
<!DOCTYPE html> <html lang="en"> <head> <title>IHM</title> </head> <body id="appmain" class="body"> <script src="https://cdnjs.cloudflare.com/ajax/libs/mithril/0.2.2-rc.1/mithril.min.js"></script> ALL MY MITHRIL COMPONENTS IMPORT <script type="text/javascript"> m.route.mode = "pathname"; m.route(document.getElementById('appmain'), "/main", { "/main": main, }); </script>
How can I redirect to another html page after credentials are checked? Is there a better way to prevent the server to send all the JavaScript files before the user is logged?
-40367483 1 Python determine whether an exception was thrown (regardless of whether it is caught or not)I am writing tests for some legacy code that is littered with catch-all constructs like
try: do_something() do_something_else() for x in some_huge_list(): do_more_things() except Exception: pass
and I want to tell whether an exception was thrown inside the try block.
I want to avoid introducing changes into the codebase just to support a few tests and I don't want to make the except
cases more specific for fear of unintentionally introducing regressions.
Is there a way of extracting information about exceptions that were raised and subsequently handled from the runtime? Or some function with a similar API to eval
/exec
/apply
/call
that either records information on every raised exception, lets the user supply an exception handler that gets run first, or lets the user register a callback that gets run on events like an exception being raised or caught.
If there isn't a way to detect whether an exception was thrown without getting under the (C)Python runtime in a really nasty way, what are some good strategies for testing code with catch-all exceptions inside the units you're testing?
-23044176 0I am not an VB.NET expert, but usually getting access to clipboard isn't as easy as it looks.
Check this:
It can be only a tip, not really solution. Look into your clipboard functionallity
I have a circuit that sends me two different data from sensors. Data is coming as packets. First data is '$' to separate one packet to another. After '$' it sends 16 bytes microphone data and 1 byte pulse sensor data. I have an array to store incoming data and after plotting the data in each 20 ms, i start to write new bytes from zero index of array. I need to plot these data to different graphs using ZedGraph. However i could not separate those data correctly. Sometimes one or more data of audio are shown in other graph. Here is my code:
for (int i = 0; i < 4; i++) { if (data[i * 18] == Convert.ToByte('$')) { for (int x = ((i * 18) + 1); x < ((i * 18) + 17); x++) { listAuido.Add(time, data[x]); } for (int a = ((i * 18) + 17); a < ((i * 18) + 18); a++) { listPulse.Add(time, data[a]); } } }
How can i solve this issue?
Circuit settings: BaudRate: 38400, Frequency: 200hz, CommunicationType: RS232.
Port Settings:ReadTimeOut=5 WrtieTimeOut=5;
While reading data i am using codes below. Read_Data1 refers data[] the code above. I have a counter and after plotting the data its value equals zero and i prevent my buffer index out of range exception
byte[] Read_Data1 = new byte[1000]; private void myPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { if (!myPort.IsOpen) return; if (myPort.BytesToRead > 0) { byte[] buffer = new byte[myPort.BytesToRead]; myPort.Read(buffer, 0, buffer.Length); DataConversion.bytetobyte(Read_Data1, buffer, buffer.Length, count); count += buffer.Length; DataRecord.SaveBytesToFile(buffer, save.FileName); } } public static void bytetobyte(byte[] Storage, byte[] databyte, int datacount, int count) { int abc; for (abc = 0; abc < datacount; abc++) { Storage[abc + count] = databyte[abc]; } }
-6128038 0 There are many scenarios when you need culture based formatting.
For example: - Number Format
5.25 in English is written as 5,25 in French
So, if you want to display French formatted number in your program which is in English culture the culture based string format
comes into action.
I would guess they outer join their friends
table with their likes
table to count both regular likes and friend likes at the same time.
With the proper indexes, it wouldn't be a slow query at all. Huge databases aren't necessarily slow, so there's really no reason to not store all of this information in a database. The trick is to make sure the indexes and partitions (if any) are set up well.
-36671301 0 How do you configure an emailAdapter for parse-server?I'm trying to test out the password reset flow on a locally running parse-server instance. Every time I send a password reset request I get the following error error: Uncaught internal server error. Trying to send a reset password but no adapter is set undefined
. I know I'm supposed to configure the emailAdapter in cli-definitions but I'm not too sure what exactly I'm supposed to put there. I tried changing the contructor in ParseServer.js to have
emailAdapter: { module: 'parse-server-simple-mailgun-adapter', options: { // The address that your emails come from fromAddress: 'parse@example.com', // Your domain from mailgun.com domain: 'example.com', // Your API key from mailgun.com apiKey: 'key-mykey', } }
but that did not work. Any help is greatly appreciated!
-31859440 0 How to get tables and views using DatabaseMetaData in JDBCI am practicing JDBC and trying to get the list of table names and view names with the help of DatabaseMetaData
interface.
Here is a sample code:
public class Sample { public static void main(String[] args) throws SQLException { try(Connection con = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe", "test", "test")){ DatabaseMetaData dbmd = con.getMetaData(); ResultSet rs = dbmd.getTables(null, null, null, new String[]{"TABLE"}); while(rs.next()){ System.out.println(rs.getString(1)); System.out.println(rs.getString(2)); System.out.println(rs.getString(3)); System.out.println(rs.getString(4)); } } } }
I was just trying to get the tables which are available for the login user "test" which I was using for creating DB connection, but in the output I am seeing so many records, so how I just get the table names and view names?
-1629194 0It's a good idea to see the coverage of your tests as it can point to problems. If your test code isn't being run then there wasn't much point in writing it!
The one I always get is when I give two unit test functions the same name - I add a new test several months after the original and just happen to pick the same name. The unittest framework won't complain about this - one of the functions hides the other and it just won't run one of the tests! The detailed coverage report shows the problem immediately though.
If you have other code in your tests that isn't being run then that may also point to other bugs, although typically there's often a couple of lines of boilerplate code that might not get covered depending on how the tests get invoked, so don't obsess about getting to 100%.
And if you have test code that really isn't needed any more then it's always good to delete!
-37819657 0I solved the problem by doing a couple things: Optimizing the layout following the dev guide. Then I simply scaled down the bitmap I was using to draw the grid, then scaled it back up when I wanted to save it onto the original image. That got everything moving nice and smoothly... (actually too fast)
-6686083 0 Alternatives to window.onloadIs there a different option than window.onload=function;
or <body onload="function();">
to call a function after the page loads.
I have a script found on the net satisfies my needs, but it overrides window.onload
, so this prevents me from using the native window.onload
.
Are there any alternatives?
-2902943 0Why, you can still static assert with const int:
#define static_assert(e) extern char (*ct_assert(void)) [sizeof(char[1 - 2*!(e)])] static_assert( THIS_LIMIT > OTHER_LIMIT )
Also, use boost!
BOOST_STATIC_ASSERT( THIS_LIMIT > OTHER_LIMIT )
... you'll get a lot nicer error messages...
-26880559 0Use a loop statement:
decode_process: process(clk) -- synchronous reset, no rst in sensitivity list begin if clk'event and clk = '1' then if rst = '1' then out_address <= (others => '0'); else for i in 0 to 10 loop if i = to_integer(unsigned(in_address)) then out_address(i) <= '1'; else out_address(i) <= '0' ; end if; end loop; -- name: for i in 0 to 10 generate -- if (i = to_integer(unsigned(in_address))) then -- out_address(i) <= '1'; -- else -- out_address(i) <= '0'; -- end if; -- end generate name; end if; end if; end process;
Also notice rst
was removed from the sensitivity list, it's written as a synchronous reset.
A loop statement can be synthesized, see now rescinded IEEE Std 1076.6-2004 8.8.9, Syntax, Sequential statements, Loop statement or your particular synthesis vendor's tool documentation. The sequential statements found in a loop are replicated for each value of the loop parameter which is treated as a constant.
So what's the difference between generate iteration and loop iteration?
Simulation cycles emulate concurrency for signal assignments even in sequential statements (e.g. in a process). There are no dependencies between one if statement and another in the synthesized (unrolled) loop. They will be i
number of in_address
recognizers comparing i
to in_address each providing one bit of out_address
. The first one assigning a(0)
, the second a(1)
... In this case the loop statement will produce the same logic a generate statement would (using conditional signal assignment, although the sequential logic (clock) semantics would make it look awkward).
Let's compare this to using a generate statement in a concurrent statement appropriate place:
architecture foo of address_decoder is function to_std_ulogic (inp: boolean) return std_ulogic is begin if inp = TRUE then return '1'; else return '0'; end if; end; begin decoder: for i in 0 to 10 generate out_address(i) <= to_std_ulogic(i = to_integer(unsigned(in_address))) when clk'event and clk = '1'; end generate; end architecture;
The function to_std_ulogic
taking a boolean argument has been added for brevity in the conditional signal assignment statement to out_address(i)
.
This looks nice and compact and may likely synthesize depending on the ability to use the function converting a boolean to a std_ulogic.
However, it expands out for elaboration:
architecture fum of address_decoder is function to_std_ulogic (inp: boolean) return std_ulogic is begin if inp = TRUE then return '1'; else return '0'; end if; end; begin decoder0: block constant i: integer := 0; begin out_address(i) <= to_std_ulogic(i = to_integer(unsigned(in_address))) when clk'event and clk = '1'; end block; decoder1: block constant i: integer := 1; begin out_address(i) <= to_std_ulogic(i = to_integer(unsigned(in_address))) when clk'event and clk = '1'; end block; decoder2: block constant i: integer := 2; begin out_address(i) <= to_std_ulogic(i = to_integer(unsigned(in_address))) when clk'event and clk = '1'; end block; decoder3: block constant i: integer := 3; begin out_address(i) <= to_std_ulogic(i = to_integer(unsigned(in_address))) when clk'event and clk = '1'; end block; decoder4: block constant i: integer := 4; begin out_address(i) <= to_std_ulogic(i = to_integer(unsigned(in_address))) when clk'event and clk = '1'; end block; decoder5: block constant i: integer := 5; begin out_address(i) <= to_std_ulogic(i = to_integer(unsigned(in_address))) when clk'event and clk = '1'; end block; decoder6: block constant i: integer := 6; begin out_address(i) <= to_std_ulogic(i = to_integer(unsigned(in_address))) when clk'event and clk = '1'; end block; decoder7: block constant i: integer := 7; begin out_address(i) <= to_std_ulogic(i = to_integer(unsigned(in_address))) when clk'event and clk = '1'; end block; decoder8: block constant i: integer := 8; begin out_address(i) <= to_std_ulogic(i = to_integer(unsigned(in_address))) when clk'event and clk = '1'; end block; decoder9: block constant i: integer := 9; begin out_address(i) <= to_std_ulogic(i = to_integer(unsigned(in_address))) when clk'event and clk = '1'; end block; decoder10: block constant i: integer := 10; begin out_address(i) <= to_std_ulogic(i = to_integer(unsigned(in_address))) when clk'event and clk = '1'; end block; end architecture;
And worse still, each of those block statement concurrent conditional signal assignment statements become a process statement of the form:
decoder10: block constant i: integer := 10; begin process begin if clk'event and clk = '1' then out_address(i) <= to_std_ulogic(i = to_integer(unsigned(in_address))); end if; wait on clk, in_address; end process;
So now all the sudden instead of simulating one process you have eleven and each of those processes is sensitive to both clk and in_address, meaning the process with become active more than on just both clock edges.
So not only do the loop statement and the generate statement equivalent produce the same hardware after elaboration and synthesis, the loop statement is guaranteed to be faster in simulation, which is it's intended purpose.
Everything in a VHDL design specification devolves into block statements, process statements and subprograms (functions, procedures). Concurrent procedures are also devolved, while functions are expressions.
It's guaranteed that synthesis elaborates a design first. The synthesis difference in this case between the generate statement and a single process containing a loop is grouping. A process statement is translated separately unless a synthesis tool accepts an attribute allowing flattening (e.g. DISSOLVE_HIERARCHY as an attribute on the generate statement).
In the loop statement in a single process case you have the opportunity to share address recognizer logic between the 10 signal assignments by default, potentially generating less logic.
So there can be little difference in synthesis, but a significant difference in simulation, where the practical impact depends on the size of your design.
-19465888 0 Matching groups of entries (rows) throughout data setI am working with a large data set containing information about certain items
The items are structured so that they all have seven main sections. Within each main section their is a variable number of parts, that the items are made of. The items uses only one part from each main section. So all items consists of seven (identical) main sections and seven parts.
I am looking to group items togheter which are precisely identical. I mean the items that uses the same part in all the main sections.
Is there an Excel/math wizard out there who can help me out with this? I have all the data, but I can't make Excel do this task for me..
-39294412 0That's very strange as flavor and ABI-name is automatically added to build name (if you make corresponding assemble)
can you try completely remove your custom made naming
applicationVariants.all { variant -> variant.outputs.each { output -> def flavor = .... // some code to parse flavor & determine an appropriate string from it output.outputFile = new File(output.outputFile.parent, "app_" + flavor + "_0" + variant.versionCode + ".apk") } }
and instead of that try to add to defaultConfig this line
archivesBaseName = "app_${versionCode}"
If this is will not resolve you issues you can try to get abi from output
output.getFilter(com.android.build.OutputFile.ABI)
-31170162 0 Note the Statement
documentation says:
By default, only one ResultSet object per Statement object can be open at the same time.
Now, you have these statements in your program:
ResultSet resultset = statement.executeQuery("select * from customer where first_name = '" + first_name + "'") ; statement.executeQuery("select * from customer where last_name = '" + last_name + "'") ; statement.executeQuery("select * from customer_order where amount = '" + amount + "'") ; statement.executeQuery("select * from customer_order where date_created = '" + date_created + "'") ; statement.executeQuery("select * from customer_order where reference_number = '" + reference_number + "'") ; statement.executeQuery("select * from customer_order where invoice_number = '" + invoice_number + "'") ; statement.executeQuery("select * from customer_order where status = '" + status + "'") ; statement.executeQuery("select * from ordered_product where quantity = '" + quantity + "'") ; statement.executeQuery("select * from ordered_product where product_name = '" + product_name + "'") ; statement.executeQuery("select * from ordered_product where product_price = '" + product_price + "'") ;
This means you are calling the executeQuery
several times with the same Statement
object. But you are only saving the result of the first execution into resultset
.
That is, the ResultSet
object that resultset
refers to is the one from this statement:
statement.executeQuery("select * from customer where first_name = '" + first_name + "'") ;
All the others that follow it are separate queries and are not stored in the same variable if that's what you thought you were doing. They just create the ResultSet
object, and then it gets thrown away because you don't assign the result to any variable.
As soon as you call the second executeQuery
, because only one ResultSet
object is allowed, the ResultSet
object stored in resultset
is closed, and a new one is opened. Then another, and then another.
Anyway, after you go through all these statements, you get to the part where you check resultset.next()
. But at this point, that object, as I said, has already been closed.
Basically, you should decide which of the queries you want to run, run only that particular query, and then you'll have a live, open ResultSet
in resultset
. And then you can fill it in.
In addition, the part that prints the values from the result set should be inside the else
block. You placed them after the curly brace of that else
, which means you'll have trouble when no rows are returned from the query, because you'll be trying to print them anyway.
Looking at your code it appears there are 2 errors with your JSON. In it's original for it produces the follwoing string:
{"guid" : "26fac319-604b-11e5-b1fe", "senderid" : "003001", "campaign" : Weekday_EGV_21Sept_4pm_Round2_Tier1_Part1}}
You are missing quotes around that final field value of campaign
and you have an extra }
at the end. If you make the following change:
json_body = "{\"guid\" : \""+ guid+"\", \"senderid\" : \""+ senderid+"\", \"campaign\" : \""+ str(campaign)+"\"}"
it should resolve the JsonParseException error.
-21450382 0basically any ajax routine will do, jQuery is more robust than this modern browser example:
server.asp:
<%= Application("NFC")%>
client.js:
function aGet(turl, callback) { var XHRt = new XMLHttpRequest(); XHRt.onload= callback; XHRt.open("GET", turl, true); XHRt.send(""); } aGet("server.asp", function(e){ alert(e.target.responseText); });
once you see how, it's simple, but it's hard to search for. that's got to be about the simplest back-end code ever... kudos on using the under-used yet awesome RAM cache that is the Application object: if used correctly, it can enable great real-time apps dues to the negligible cost of pinging that simple server page.
-35111500 0 Enabling hover css transition for div that's behind another div which is only there for textI've got a site which I'm trying to develop the same way I did a wordpress site but the wordpress site is super sluggish so just recreating the cool bits.
The wordpress site is http://myleisure.com.au and as you can see at the top there's the 3 boxes with the product images and then text inside them. I've recreated this at the site http://ozledgrowlights.com.au/#portfolio and you can see the useless codepen here http://codepen.io/anon/pen/Qyxxbp
<section id="portfolio"> <div class="container-fluid nopadding"> <div class="row nopadding"> <div class="col-lg-4 nopadding image"> <img class="imgwidth" src="img/11.jpg" alt="" /> <div class="absolute text-center"> <span> lol </span> </div> </div> <div class="col-lg-4 nopadding image"> <img class="imgwidth" src="img/22.jpg" alt="" /> <div class="absolute text-center"> <span> lol </span> </div> </div> <div class="col-lg-4 nopadding image"> <img class="imgwidth" src="img/33.jpg" alt="" /> <div class="absolute text-center"> <span> lol </span> </div> </div> </div> </div> </section>
Basically I'm getting the text on top of the <img>
via giving the img a relative position and the div for text an absolute position and top: 0px; the only issue is that because It's a div for the text, when I give it a height of 100%, it covers the hover zone of the img, any way around this? I saw a way to do the transition via javascript so might have to just do that.
But then I have a ...... part b to this question. Can anyone guess why the 2nd and 3rd image boxes get a thin black line between them when you hover over them?
-23982729 0You forgot about committing:
con.commit()
-22674611 0 Jquery Validate - require_from_group I'm using require_from_group from Jquery Validate Framework and I'm trying to display the error message in every single field that belongs to the group, but it is only being displayed in two of them.
HTML code:
<form id="myform"> <label for="mobile_phone">Mobile phone: </label> <input class="phoneUS contactMethod" id="mobile_phone" name="mobile_phone"> <br/> <label for="home_phone">Home phone: </label> <input class="phoneUS contactMethod" id="home_phone" name="home_phone"> <br/> <label for="work_phone">Work phone: </label> <input class="phoneUS contactMethod" id="Work_phone" name="work_phone"> <br/> <label for="work_phone">Fax phone: </label> <input class="phoneUS contactMethod" id="fax_phone" name="fax_phone"> <br/> <label for="work_phone">Email: </label> <input class="phoneUS contactMethod" id="email" name="email"> <br/> <input type="submit" value="Go!"> </form>
JS:
$.validator.addClassRules("contactMethod", { require_from_group: [1, ".contactMethod"] }); $( "#myform" ).validate();
This is my JSFiddle: http://jsfiddle.net/3jahT/
I want that, whenever user clicks on submit, message appears across all fields, as well as when user unfocus one of them without filling it. (Jquery default functionality).
-12809367 0 Android beta testing serviceI've developed android app and want to start some beta testing with as many users as possible. Are there web services to find mobile beta testers, preferrably volunteers?
-16347994 0 Application crash when anoter domain throws exceptionI'm studing C#. I read books of Andrew Troelsen "C# and the .NET Platform" and Jeffrey Richter's "CLR via C#". Now, I'm trying to make application, which will load assemblies from some directory, push them to AppDomain's and run the method's included (the application which supports plug-ins). Here is the DLL where is the common interface. I add it to my application, and in all DLLs with plugins. MainLib.DLL
namespace MainLib { public interface ICommonInterface { void ShowDllName(); } }
Here is plugins: PluginWithOutException
namespace PluginWithOutException { public class WithOutException : MarshalByRefObject, ICommonInterface { public void ShowDllName() { MessageBox.Show("PluginWithOutException"); } public WithOutException() { } } }
and another one: PluginWithException
namespace PluginWithException { public class WithException : MarshalByRefObject, ICommonInterface { public void ShowDllName() { MessageBox.Show("WithException"); throw new NotImplementedException(); } } }
And here is an application, which loads DLLs and runs them in another AppDomain's
namespace Plug_inApp { class Program { static void Main(string[] args) { ThreadPool.QueueUserWorkItem(CreateDomainAndLoadAssebly, @"E:\Plugins\PluginWithException.dll"); Console.ReadKey(); } public static void CreateDomainAndLoadAssebly(object name) { string assemblyName = (string)name; Assembly assemblyToLoad = null; AppDomain domain = AppDomain.CreateDomain(string.Format("{0} Domain", assemblyName)); domain.FirstChanceException += domain_FirstChanceException; try { assemblyToLoad = Assembly.LoadFrom(assemblyName); } catch (FileNotFoundException) { MessageBox.Show("Can't find assembly!"); throw; } var theClassTypes = from t in assemblyToLoad.GetTypes() where t.IsClass && (t.GetInterface("ICommonInterface") != null) select t; foreach (Type type in theClassTypes) { ICommonInterface instance = (ICommonInterface)domain.CreateInstanceFromAndUnwrap(assemblyName, type.FullName); instance.ShowDllName(); } } static void domain_FirstChanceException(object sender, System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs e) { MessageBox.Show(e.Exception.Message); } } }
I expect, that if I run instance.ShowDllName();
in another domain (maybe I do it wrong?) the unhandled exception will drop the domain where it runs, but the default domain will work. But in my case - default domain crashes after exception occurs in another domain. Please, tell me what I'm doing wrong?
i am using autolayout in my project. I added the contraints from the bottom to the top. Everything works fins in 4 inch screen . But screen is clipped when the project is run on 3.5 simulator.
I have two vectors of MyObj structs. MyObj is defined as follows:
struct MyObj { float x, y; unsigned int data[8]; unsigned int tmp[1]; MyObj(const MyObj &m) { x = m.x; y = m.y; tmp[0] = 0; for (int i = 0; i < 8; ++i) { data[i] = m.data[i]; } } };
I then have two vectors...
vector<MyObj> v1; vector<MyObj> v2; // both get data eventually. v1.insert(v1.end(), v2.begin(), v2.end());
v2 has 3535004 elements in my experiment. v1 is similarly sized. I've also tried building a new vector and just using .push_back to build it from both vectors.
Essentially, when I try to merge the two vectors I just get an error from visual studio saying "Debug error! R6010, abort() has been called". Very non-useful...
So my question is: what could be causing this error, and how can I solve it? Thank you
-31821474 0On Windows you can use the low level bitmap copying functions, which accurate match the old description without any OpenGL, etc.
BOOL BitBlt( _In_ HDC hdcDest, _In_ int nXDest, _In_ int nYDest, _In_ int nWidth, _In_ int nHeight, _In_ HDC hdcSrc, _In_ int nXSrc, _In_ int nYSrc, _In_ DWORD dwRop );
https://msdn.microsoft.com/en-us/library/dd183370%28v=vs.85%29.aspx
-39553320 0You have an incorrect understanding of the shared
folder. It is not a place to put files you wish to have copied to the build output folder. The folder you are looking for is entitled assets
those files will be copied to the output directory, dist
for both dev and prod builds.
The shared directory is a place to put common (or shared) portions of your application, whether they be components, directives, pipes, classes or services.
-11504746 0 MYSQL SELECT SUM() BY DATE IF NO MATCH RETURN 0I have connected three tables to each other. I'm querying keywords + statistics.
I need to get data out by date range, and if there is no data for that specific date range i would like it to return 0 statistics
Lets say my query is:
SELECT keyword,SUM(stat) FROM keywords WHERE date >='2012-07-10' GROUP BY keyword;
It would return
|my keyword 1|3|
|my keyword 2|6|
Example table content:
| id | keyword | stat | date | keywordGroup |
| 1 | my keyword 1 | 2 | 2012-07-11 | 1 |
| 2 | my keyword 1 | 1 | 2012-07-12 | 1 |
| 3 | my keyword 2 | 6 | 2012-07-11 | 1 |
| 4 | my keyword 3 | 10 | 2012-07-09 | 1 |
But there are some keywords which have no stats for that date range
but I would still like to get those keywords showing 0 as stats.
Like this:
|my keyword 1|3|
|my keyword 2|6|
|my keyword 3|0|
The problem is that the where clause blocks values that are not found, is there a workaround.
As I said I have three tables with relations, I use LEFT JOIN to query data, for simplification I left that part out of my example query.
Table: Campaigns
id
name
Table: KeywordGroup
id
name
campaign
Table: KeywordData
id
keyword
stat
date
keywordGroup
I am opening different browsers using
ProcessStartInfo startBrowser = new ProcessStartInfo(internetbrowser, website); Process.Start(startBrowser);
Which works great. However, I need to also know when the webpage has loaded. Is there a way that I can check this? Or even better, fire an event when the page is fully loaded?
Thanks
-13567323 0Change the main funciton:
public function Main() { generateField(); initTetrominoes(); nextTetromino=Math.floor(Math.random()*3); stage.addEventListener(KeyboardEvent.KEY_DOWN,onKDown); } // add new funciton private function start():void { generateTetromino(); } // edit the keydown callback to listen for the space bar - add it first in front of 37 case 32 : start(); break;
-14015852 1 Python reading hex numbers from file and writing to another. "Invalid literal" in 'int' assignment /dev/input/event0: 0003 0001 000081a5
Should become
sendevent 0003 0001 000081a5
in new file.
Code is
import sys import fileinput prefix = 'sendevent ' inputline = None complete = None part1len = 0 part1 = None part2 = None num1 = 0 num2 = 0 num3 = 0 rawfile = None outfile = None filename = None rawfile = sys.argv[-1] fo = open(rawfile, 'r') filename = rawfile.find('.'); outfile = rawfile[:filename] + '.scr' fw = open(outfile, 'w') fw.write('#!/bin/sh' + '\n') fw.write('echo Running - signature function ' + '\n') for inputline in fo.read().split('\n'): part1len = inputline.find(':'); if part1len > -1: part1 = inputline[:part1len] part2 = inputline.split(' ') num1 = int(part2[1], 16) num2 = int(part2[2], 16) num3 = int(part2[3], 16) complete = prefix + part1 + " " + str(num1) + " " + str(num2) + " " + str(num3) fw.write(complete + '\n') print 'Processing complete' print 'File created: ', outfile print print 'Copy file to the device' print 'adb push ' + outfile + ' /sdcard/' + outfile print print 'Run the script' print 'adb shell sh /sdcard/' + outfile fo.close() fw.close()
Error in output command line is :
Traceback (most recent call last): File "Android\decs.py", line 41, in <module> num1 = int(part2[1], 16) ValueError: invalid literal for int() with base 16: '='
Just started learning Python today. I am not sure what is going wrong. Have gone through similar errors posted online but cannot find a solution.
Thanks
-11046005 0Your row variable is not the a
tag, so there is no attribute href
on it.
Try with this:
Element table = doc.select("table.table"); Elements links = table.getElementsByTag("a"); for (Element link: links) { String url = link.attr("href"); String text = link.text(); System.out.println(text + ", " + url); }
This is pretty much extracted from the JSoup documentation
-11630989 0Basically you want to implement a set; check the list manual page for set operations. It appears that there is no add but there is union/3 so you can add elements by intersecting with a set of the new element (intersection([NewEl], OldSet, NewSet). Note that you dont have to convert a list to a set (a list is a set as long as it doesnt have duplicates; list_to_set/2 just eliminates them).
Now if you have a list with duplicates and you want sometimes to add an element the way you stated you will have to implement something yourself.
-19293131 0The error lines say
#if defined(_AMD64_) || defined(_X86_) #define PROBE_ALIGNMENT( _s ) TYPE_ALIGNMENT( DWORD ) #elif defined(_IA64_) || defined(_ARM_) #define PROBE_ALIGNMENT( _s ) (TYPE_ALIGNMENT( _s ) > TYPE_ALIGNMENT( DWORD ) ? \ TYPE_ALIGNMENT( _s ) : TYPE_ALIGNMENT( DWORD )) #elif !defined(RC_INVOKED) #error "No Target Architecture" #endif
You have #included that header, possibly indirectly by including another header. You can tell VS2012 to list all the includes it uses by setting "Show Includes" to yes in the Properties | C/C++ | Advanced
project menu. Then try not including the header that is dragging in winnt.h
if you don't need it.
winnt.h
can cause trouble e.g. see here
edit
So, the precompile header includes windef.h which includes the offending header. Try removing the line from the precompiled header.
Sure, just follow a few easy steps:
For example, if your current directory structure looks like this:
/www /application1 /protected /models /application2 /protected /models
Create another "shared" directory. It's a good idea to put some structure in there as well, in case you want to share more than just some models:
/www /application1 /protected /models /application2 /protected /models /shared /models
Put the active record models you want to share in /www/shared/models
.
Go to your main.php
configuration file in both applications and create an alias for the shared directory:
Yii::setPathOfAlias('shared','../shared/'); // or use an absolute path
Still in your main.php
configuration, import your shared models:
'import'=>array( // ...existing imports here... 'shared.models.*', ),
You can now directly refer to the shared classes anywhere in your application and Yii will load the appropriate classes automatically.
If you later add more directories to /shared
then simply add corresponding lines to the import
configuration.
I'm trying to create a stored procedure, either in command line or MySql Workbench editor.
In Mysql WOrkbench I have no message at all, no success no error, but the procedure is not created. In command line mysql --host=localhost ... < procedure-script.sql
I get the following error:
ERROR 1064 (42000) at line 4: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DELIMITER' at line 28
Line 28 is actually empty but I guess it refers to the final DELIMITER ;
in line 31. Here is the complete code:
DELIMITER $$; -- drop procedure if exists updPages$$ CREATE PROCEDURE updPages() BEGIN DECLARE _post_id INTEGER; DECLARE cur_pages CURSOR FOR select ID from wp_posts where post_type='page' and ID not in (select post_id from wp_postmeta); OPEN cur_pages; Reading_Pages: LOOP FETCH cur_pages INTO _post_id; IF done THEN LEAVE Reading_Pages; END IF; insert into wp_postmeta(post_id, meta_key, meta_value) values (_post_id, '_wp_page_template', 'default'), (_post_id, 'upside-show-page-title', '1'), (_post_id, 'upside-show-breadcrumb', '1'), (_post_id, 'upside-page-show-document-search', '0'), (_post_id, 'upside-show-page-title-middle', 'false'), (_post_id, '_vc_post_settings', 'a:1:{s:10:"vc_grid_id";a:0:{}}'); END LOOP; CLOSE cur_pages; END$$ DELIMITER ;
(1) Is there any error? (2) Do you know how to show compilation errors in Mysql Workbench? also, (3) can I use tab inside scripts when running them from command line? (I had to strip them out as I had errors)
-31037286 0Try changing your ng-options to something like:
<select class="form-control" id="Event_Cat" data-ng-model="vm.selectedCategory" data-ng-options="opt.id as opt.label for opt in categoryValues | orderBy:'label'" required> <option style="display:none" value="">Select a Category</option> </select>
And make this line change in your controller:
$scope.vm.selectedCategory = $scope.categoryValues[currentDetailIndex].id;
Edit for multiple selection:
<select class="form-control" id="Event_Cat" data-ng-model="selectedCategoriesIds" data-ng-options="opt.id as opt.label for opt in categoryValues | orderBy:'label'" required multiple> <option style="display:none" value="">Select a Category</option> </select>
In your controller, add the items you want selected to $scope.selectedCategoriesIds e.g.:
$scope.selectedCategoriesIds = []; $scope.selectedCategoriesIds.push('18'); $scope.selectedCategoriesIds.push('80');
-14660031 0 You don't need a doc ready
handler here: http://jsfiddle.net/RWnBQ/1/
$(".readmore").each(function () { if ($(this).text().length > 200) { //--- doc ready removed from here $('div.readmore').expander({ slicePoint: 200, expandSpeed: 1000, collapseSpeed: 1000, expandText: 'Read More', userCollapseText: 'Hide Text' }); //--- doc ready removed from here } });
-27075724 0 The exact sql query depends on what type of SQL server you have used.
For example in MySQL you can paginate by LIMIT and OFFSET at the end of a query.
SELECT something FROM table LIMIT 20, 40
It says that you get 20 records from 40. position.
-33499281 0 Fedex Shipping not showing on the Magento Website FrontendI have recently configured a magento website with fedex shipping. But it is not showing on the frontend.
What else the issue can be? Do I need to configure the table rates shipping to make fedex work? I just cannot make out what the issue can be.
-9156387 0Turn on tracing
You can turn on tracing on a single page using the Trace attribute in the Page directive.
<%@ Page Trace="true" %>
You can also turn on tracing for all pages in an asp.net application using the web.config setting.
<configuration> <system.web> <trace enabled="true" pageOutput="false" requestLimit="40" localOnly="false"/> </system.web> </configuration>
Add custom output to the trace output.
public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Trace.Write("custom start"); System.Threading.Thread.Sleep(2000); Trace.Write("custom end"); } }
The above code shows up like this
Try to:
private void getUserFriendsFacebookIds() { GraphRequest request = new GraphRequest( AccessToken.getCurrentAccessToken(), "/me/friends", null, HttpMethod.GET, new GraphRequest.Callback() { public void onCompleted(GraphResponse response) { /* handle the result */ Log.d("-@-", "graph response " + response.getJSONObject()); if (response.getError() != null) { Log.e(TAG, "User data error: " + response.getError(), response.getError().getException()); } else { setUserFriends(response.getRawResponse()); } } } ); Bundle parameters = new Bundle(); parameters.putString("fields", "id,name"); request.setParameters(parameters); request.executeAsync(); } private void setUserFriends(String json) { FacebookFriendsInfo ff = new Gson().fromJson(json, FacebookFriendsInfo.class); Log.i(TAG, "User friends: " + ff); ... }
To parse response try to use GSON library.
public class FacebookFriendsInfo { public List<Friend> data = new ArrayList<Friend>(); public String getIds() { StringBuilder sb = new StringBuilder(); for (Friend f : data) { sb.append(String.format("%d,", f.id)); } return sb.toString(); } @Override public String toString() { return "FacebookFriendsInfo{" + "data=" + data + '}'; } public class Friend { public long id; public String name; @Override public String toString() { return "Friend{" + "id=" + id + ", name='" + name + '\'' + '}'; } } }
-897206 1 Python cgi FieldStorage slow, alternatives? I have a python cgi script that receives files uploaded via a http post. The files can be large (300+ Mb). The thing is, cgi.FieldStorage() is incredibly slow for getting the file (a 300Mb file took 6 minutes to be "received"). Doing the same by just reading the stdin took around 15 seconds. The problem with the latter is, i would have to parse the data myself if there are multiple fields that are posted.
Are there any faster alternatives to FieldStorage()?
-15707074 0 Two dimensional array of objects in as3Is it possible to make array in as3 like this :
countdowns[bodyID][powerupName] = { time: powerup.getTime(), onRemove: onRemove };
I have been trying for hours but no luck.. Thanks
-37994264 0git filter-branch -f --index-filter 'git rm --cached --ignore-unmatch *.sql'
Note: Replace *.sql with your file name or file type. Be very careful because this will go through every commit and rip this file type out.
-3730916 0Your description does not really match with the Memento patttern. The whole point of Memento is that only instances of the class which is to be restored know anything about the representation of the memento. That is, Memento is about hiding state, rather than allowing clients to set arbitrary states.
As Mark Cidade suggests above, there are other more appropriate patterns to use for your problem.
-16485767 0 what is the best way to converge code from different folder in clearcase?I need some suggestions on the following issue.
Currently, I have code in this stream:tll_ltr_nyc@/ttl_pvob mastered at NYC (P_NYC folder of ttl_vob) and I would like to merge those code with latest changes in stream:aaa_ltr_lax@/ttl_pvob mastered at LAX (P_LAX folder of ttl_pvob). what will be the best way to proceed with converging code from one stream to another within same project vob but within two different folders?
Any help will be appreciated !!
Thanks
-15747895 0if "; is expected" maybe before these lines you have forgotten to end your previous line. Otherwise do a recompile. Sometimes, intellisense has to be rebooted (don't know why). Reboot VS if you will see this mistake again.
-1993827 0Upon quick googling, http://www.phpfour.com/blog/2009/02/php-payment-gateway-library-for-paypal-authorizenet-and-2checkout/ looks like it might work.
-28771048 0Turning off "Use Host GPU" for this AVD will fix this.
-39235685 0 var input = { "firstname": "John", "lastname": "Doe", "numbers": [{ "id": 1, "value": "123" }, { "id": 2, "value": "123" }] } for (var key in input) { if (key === "numbers") { for (var i=0; i < input[key].length; i++) { console.log(input[key][i]); } } else { console.log(key + ":" + input[key]) } }
.addMarker
, not .addMarkers
code snippet:
var mgr; var map; function initialize() { var mapOptions = { zoom: 4, center: new google.maps.LatLng(34.6479355684, -0.2292535), mapTypeId: google.maps.MapTypeId.SATELLITE }; map = new google.maps.Map(document.getElementById('resultcnn'), mapOptions); mgr = new MarkerManager(map); var locations = [ ['rabat', 33.906896, -6.263123], ['rabat2', 34.053993, -6.792237], ['agdal', 33.994469, -6.848702], ['casa', 33.587596, -7.657156], ['casa2', 33.531808, -7.674601], ['casa3', 33.58824, -7.673278], ['casa4', 33.542325, -7.578557], ['agadir', 30.433948, -9.600005], ['kech', 31.634676, -8.000164], ['oujda,', 34.689969, -1.912365], ['tanger,', 35.771586, -5.801868], ['JIJEL-ACHOUAT', 36.8, 5.883333333, 1], ['JIJEL-PORT', 36.81666667, 5.883333333, 2], ['SKIKDA', 36.88333333, 6.9, 3], ['ANNABA', 36.83333333, 7.816666667, 4], ['EL-KALA', 36.9, 8.45, 8], ['ALGER-PORT', 36.76666667, 3.1, 9], ['DELLYS', 36.91666667, 3.95, 10.4], ['DAR-EL-BEIDA', 36.68333333, 3.216666667, 12.08571429], ['TIZI-OUZOU', 36.7, 4.05, 13.77142857] ]; google.maps.event.addListener(mgr, 'loaded', function() { for (var i = 0; i < locations.length; i++) { var marker = new google.maps.Marker({ position: new google.maps.LatLng(locations[i][1], locations[i][2]), }); mgr.addMarker(marker, 5); } mgr.refresh(); }); } google.maps.event.addDomListener(window, 'load', initialize);
html, body, #resultcnn { height: 100%; width: 100%; margin: 0px; padding: 0px }
<script src="https://maps.googleapis.com/maps/api/js"></script> <script src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markermanager/src/markermanager.js"></script> <div id="resultcnn"></div>
I have an application that spends about 80% of its time computing the centroid of a large list (10^7) of high dimensional vectors (dim=100) using the Kahan summation algorithm. I have done my best at optimizing the summation, but it is still 20x slower than an equivalent C implementation. Profiling indicates that the culprits are the unsafeRead
and unsafeWrite
functions from Data.Vector.Unboxed.Mutable
. My question is: are these functions really this slow or am I misunderstanding the profiling statistics?
Here are the two implementations. The Haskell one is compiled with ghc-7.0.3 using the llvm backend. The C one is compiled with llvm-gcc.
Kahan summation in Haskell:
{-# LANGUAGE BangPatterns #-} module Test where import Control.Monad ( mapM_ ) import Data.Vector.Unboxed ( Vector, Unbox ) import Data.Vector.Unboxed.Mutable ( MVector ) import qualified Data.Vector.Unboxed as U import qualified Data.Vector.Unboxed.Mutable as UM import Data.Word ( Word ) import Data.Bits ( shiftL, shiftR, xor ) prng :: Word -> Word prng w = w' where !w1 = w `xor` (w `shiftL` 13) !w2 = w1 `xor` (w1 `shiftR` 7) !w' = w2 `xor` (w2 `shiftL` 17) mkVect :: Word -> Vector Double mkVect = U.force . U.map fromIntegral . U.fromList . take 100 . iterate prng foldV :: (Unbox a, Unbox b) => (a -> b -> a) -- componentwise function to fold -> Vector a -- initial accumulator value -> [Vector b] -- data vectors -> Vector a -- final accumulator value foldV fn accum vs = U.modify (\x -> mapM_ (liftV fn x) vs) accum where liftV f acc = fV where fV v = go 0 where n = min (U.length v) (UM.length acc) go i | i < n = step >> go (i + 1) | otherwise = return () where step = {-# SCC "fV_step" #-} do a <- {-# SCC "fV_read" #-} UM.unsafeRead acc i b <- {-# SCC "fV_index" #-} U.unsafeIndexM v i {-# SCC "fV_write" #-} UM.unsafeWrite acc i $! {-# SCC "fV_apply" #-} f a b kahan :: [Vector Double] -> Vector Double kahan [] = U.singleton 0.0 kahan (v:vs) = fst . U.unzip $ foldV kahanStep acc vs where acc = U.map (\z -> (z, 0.0)) v kahanStep :: (Double, Double) -> Double -> (Double, Double) kahanStep (s, c) x = (s', c') where !y = x - c !s' = s + y !c' = (s' - s) - y {-# NOINLINE kahanStep #-} zero :: U.Vector Double zero = U.replicate 100 0.0 myLoop n = kahan $ map mkVect [1..n] main = print $ myLoop 100000
Compiling with ghc-7.0.3 using the llvm backend:
ghc -o Test_hs --make -fforce-recomp -O3 -fllvm -optlo-O3 -msse2 -main-is Test.main Test.hs time ./Test_hs real 0m1.948s user 0m1.936s sys 0m0.008s
Profiling information:
16,710,594,992 bytes allocated in the heap 33,047,064 bytes copied during GC 35,464 bytes maximum residency (1 sample(s)) 23,888 bytes maximum slop 1 MB total memory in use (0 MB lost due to fragmentation) Generation 0: 31907 collections, 0 parallel, 0.28s, 0.27s elapsed Generation 1: 1 collections, 0 parallel, 0.00s, 0.00s elapsed INIT time 0.00s ( 0.00s elapsed) MUT time 24.73s ( 24.74s elapsed) GC time 0.28s ( 0.27s elapsed) RP time 0.00s ( 0.00s elapsed) PROF time 0.00s ( 0.00s elapsed) EXIT time 0.00s ( 0.00s elapsed) Total time 25.01s ( 25.02s elapsed) %GC time 1.1% (1.1% elapsed) Alloc rate 675,607,179 bytes per MUT second Productivity 98.9% of total user, 98.9% of total elapsed Thu Feb 23 02:42 2012 Time and Allocation Profiling Report (Final) Test_hs +RTS -s -p -RTS total time = 24.60 secs (1230 ticks @ 20 ms) total alloc = 8,608,188,392 bytes (excludes profiling overheads) COST CENTRE MODULE %time %alloc fV_write Test 31.1 26.0 fV_read Test 27.2 23.2 mkVect Test 12.3 27.2 fV_step Test 11.7 0.0 foldV Test 5.9 5.7 fV_index Test 5.2 9.3 kahanStep Test 3.3 6.5 prng Test 2.2 1.8 individual inherited COST CENTRE MODULE no. entries %time %alloc %time %alloc MAIN MAIN 1 0 0.0 0.0 100.0 100.0 CAF:main1 Test 339 1 0.0 0.0 0.0 0.0 main Test 346 1 0.0 0.0 0.0 0.0 CAF:main2 Test 338 1 0.0 0.0 100.0 100.0 main Test 347 0 0.0 0.0 100.0 100.0 myLoop Test 348 1 0.2 0.2 100.0 100.0 mkVect Test 350 400000 12.3 27.2 14.5 29.0 prng Test 351 9900000 2.2 1.8 2.2 1.8 kahan Test 349 102 0.0 0.0 85.4 70.7 foldV Test 359 1 5.9 5.7 85.4 70.7 fV_step Test 360 9999900 11.7 0.0 79.5 65.1 fV_write Test 367 19999800 31.1 26.0 35.4 32.5 fV_apply Test 368 9999900 1.0 0.0 4.3 6.5 kahanStep Test 369 9999900 3.3 6.5 3.3 6.5 fV_index Test 366 9999900 5.2 9.3 5.2 9.3 fV_read Test 361 9999900 27.2 23.2 27.2 23.2 CAF:lvl19_r3ei Test 337 1 0.0 0.0 0.0 0.0 kahan Test 358 0 0.0 0.0 0.0 0.0 CAF:poly_$dPrimMonad3_r3eg Test 336 1 0.0 0.0 0.0 0.0 kahan Test 357 0 0.0 0.0 0.0 0.0 CAF:$dMVector2_r3ee Test 335 1 0.0 0.0 0.0 0.0 CAF:$dVector1_r3ec Test 334 1 0.0 0.0 0.0 0.0 CAF:poly_$dMonad_r3ea Test 333 1 0.0 0.0 0.0 0.0 CAF:$dMVector1_r3e2 Test 330 1 0.0 0.0 0.0 0.0 CAF:poly_$dPrimMonad2_r3e0 Test 328 1 0.0 0.0 0.0 0.0 foldV Test 365 0 0.0 0.0 0.0 0.0 CAF:lvl11_r3dM Test 322 1 0.0 0.0 0.0 0.0 kahan Test 354 0 0.0 0.0 0.0 0.0 CAF:lvl10_r3dK Test 321 1 0.0 0.0 0.0 0.0 kahan Test 355 0 0.0 0.0 0.0 0.0 CAF:$dMVector_r3dI Test 320 1 0.0 0.0 0.0 0.0 kahan Test 356 0 0.0 0.0 0.0 0.0 CAF GHC.Float 297 1 0.0 0.0 0.0 0.0 CAF GHC.IO.Handle.FD 256 2 0.0 0.0 0.0 0.0 CAF GHC.IO.Encoding.Iconv 214 2 0.0 0.0 0.0 0.0 CAF GHC.Conc.Signal 211 1 0.0 0.0 0.0 0.0 CAF Data.Vector.Generic 182 1 0.0 0.0 0.0 0.0 CAF Data.Vector.Unboxed 174 2 0.0 0.0 0.0 0.0
The equivalent implementation in C:
#include <stdint.h> #include <stdio.h> #define VDIM 100 #define VNUM 100000 uint64_t prng (uint64_t w) { w ^= w << 13; w ^= w >> 7; w ^= w << 17; return w; }; void kahanStep (double *s, double *c, double x) { double y, t; y = x - *c; t = *s + y; *c = (t - *s) - y; *s = t; } void kahan(double s[], double c[]) { for (int i = 1; i <= VNUM; i++) { uint64_t w = i; for (int j = 0; j < VDIM; j++) { kahanStep(&s[j], &c[j], w); w = prng(w); } } }; int main (int argc, char* argv[]) { double acc[VDIM], err[VDIM]; for (int i = 0; i < VDIM; i++) { acc[i] = err[i] = 0.0; }; kahan(acc, err); printf("[ "); for (int i = 0; i < VDIM; i++) { printf("%g ", acc[i]); }; printf("]\n"); };
Compiled with llvm-gcc:
>llvm-gcc -o Test_c -O3 -msse2 -std=c99 test.c >time ./Test_c real 0m0.096s user 0m0.088s sys 0m0.004s
Update 1: I un-inlined kahanStep
in the C version. It barely made a dent in the performance. I hope that now we can all acknowledge Amdahl's law and move on. As inefficient as kahanStep
might be, unsafeRead
and unsafeWrite
are 9-10x slower. I was hoping someone could shed some light on the possible causes of that fact.
Also, I should say that since I am interacting with a library that uses Data.Vector.Unboxed
, so I am kinda married to it at this point, and parting with it would be very traumatic :-)
Update 2: I guess I was not clear enough in my original question. I am not looking for ways to speed up this microbenchmark. I am looking for an explanation of the counter intuitive profiling stats, so I can decide whether or not to file a bug report against vector
.
I have certain sound files and will like to develop an app which allows to set those sound files as ringtones.
Can someone let me know the way of implementing it? What are the API's that I need to use for this purpose?
Hope to get the reply soon.
Regards
Sunil
-5959446 0Not really anything to do with jQuery, but if you want to trim a pattern from a string, then use a regular expression:
<textarea id="ta0"></textarea> <button onclick=" var ta = document.getElementById('ta0'); var text = 'some<br>text<br />to<br/>replace'; var re = /<br *\/?>/gi; ta.value = text.replace(re, '\n'); ">Add stuff to text area</button>
-9902887 0 yes. but sometimes these two may be a little different when handling set of result by where
-30160539 0 Need GitBlit groovy hook which push changed to other Gitblit server repoNeed a groovy push hook scripts from your Gitblit instance to another Gitblit instance
I have two private linux servers
, Say A
and B
with GitBlit
install on both. All developers do commit and push their changes on server A
, I want B
keep in sync with A
.
There is some Groovy hook
but I am totally new in this, Can any one help to provide it.
PS: If There any push event found on A
some script will fire and it push
changes to B
So what your code is doing is the following:
x = '2', which represents 50 as a decimal value in the ASCII table.
then your are basically saying:
x = x - '0', where zero in the ASCII table is represented as 48 in decimal, which equates to x = 50 - 48 = 2.
Note that 2 != '2' . If you look up 2(decimal) in the ASCII table that will give you a STX (start of text). This is what your code is doing. So keep in mind that the subtraction is taking place on the decimal value of the char.
-31172837 0 "Regular Expression is too large" error in PHPI am working on a relatively complex, and very large regular expression. It is currently 41,127 characters, and may grow somewhat as additional cases may be added. I am starting to get this error in PHP:
preg_match_all(): Compilation failed: regular expression is too large at offset 41123
Is there a way to increase the size limit? The following settings suggested elsewhere did NOT work because these apply to size of data and NOT the regex size:
ini_set("pcre.backtrack_limit", "100000000"); ini_set("pcre.recursion_limit", "100000000");
Alternatively, is there a way to define a "sub-pattern variable" within the regex that could be repeated at various places within the regex? (I am not talking about repetition using *
or +
, or even repeating matched "1")? I am actually using PHP variables containing sub-Patterns that are repeated in few places within the regex, but this leads to expansion of the regex BEFORE it is passed on to PRCE functions.
This is a complex regular expression, and cannot be replaced by simpler keyword-searching using strpos
or similar as suggested at this link.
I would prefer to avoid splitting this into sub-expressions at |
and trying to match the sub-expressions separately, because the reduction in size would be modest (there are only 2 or 3 of top-level |
), and this would complicate further development.
I can tell you right off that bat you are approaching a simple problem with an incredibly complex solution...
I would guess you are looking for the instanceof
keyword, or perhaps an abstract validation class.
If you could be more specific with your intended functionality we could help you come up with a reasonable design pattern.
Directly to your question: Yes, you can generate and load classes in Java on the fly. It involves invoking the defineClass(String, byte[], int, int)
method in the reflection package. As input to this function you have to provide a byte array of the class you are instantiating. This doesn't sound like the appropriate approach to this problem.
In my app, one issue is there. I am downloading the images from the web and these images are stored in the local database. How do I store these images into the local database?
-3067219 0You can just disable/uninstall bzr-svn plugin if you don't need to work with svn servers from bzr.
Or, in the command-line execute following command:
bzr --no-plugins init
It will create bzr branch in your directory, and after that bzr and TortoiseBzr won't try to open svn working copy.
But you probably still will have problems when running bzr commands from subfolders. So, you can add all required files in your svn copy under bzr version control, then commit them:
bzr add bzr commit -m initial
Now you can re-create this state of files in different (empty) directory with
bzr branch path/to/bzr/branch/in/svn/copy new/path
And do all work in new/path
. When you'll be ready to update your svn working copy with latest committed revision from new/path then just push your changes back:
bzr push path/to/bzr/branch/in/svn/copy
-1199625 0 Instead of a hash you can at least use a radix to get started.
For any specific problem, you can do much better than a btree, a hash table, or a patricia trie. Describe the problem a bit better, and we can suggest what might work
-32164663 0 Convert JQuery QR Code to Image using JSI was wondering how it's possible to download the JQuery generated QR code or convert to a downloadable image (png/jpeg) using javascript.
I tried what was here: Capture HTML Canvas as gif/jpg/png/pdf? But no success. I think it's related to the output. There is a table and canvas output, but both do not give the image data...
Here is my code:
<script src="js/jquery-1.3.2.js"></script> <script type="text/javascript" src="js/jquery.qrcode.js"></script> <script type="text/javascript" src="js/qrcode.js"></script> <div id="output"></div> <script> jQuery(function(){ jQuery('#output').qrcode("http://"); }) var canvas = document.getElementById("output"); var img = canvas.toDataURL("image/png"); document.write('<img src="'+img+'"/>'); </script>
Also I was hoping to surround the QR Code with a white background (Adding rows and columns within the div) before converting to image to aid the detection (so that the background is also included in the image).
Any help is appreciated...
-40541157 0 How to test channel with Phoenix.ChannelTest.close/2I have a test that starts up a socket connection and subscribes and joins a topic. I then push a message to the channel which does some work and persist some data. I then use ChannelTest.close/2 on the socket which simulates the client closing the connection. I would then like to modify the manipulated data and create another socket connection to test some behaviour.
My issue is ChannelTest.close/2 causes my test to fail and returns ** (EXIT from #PID<0.558.0>) shutdown: :closed
. How can I prevent this from happening?
Here's some relevant code
defmodule PlexServer.EmpireChannelTest do use PlexServer.ChannelCase alias PlexServer.EmpireChannel alias PlexServer.EmpireTemplate alias PlexServer.EmpireInstance setup do ... {:ok, _, socket} = socket("user_id", %{}) |> subscribe_and_join(EmpireChannel, "empire:#{empire.id}", %{"guardian_token" => jwt}) {:ok, socket: socket, empire: empire, jwt: jwt} end test "research infrastructure", %{socket: socket, empire: empire, jwt: jwt} do ... ref = push socket, "command", request assert_reply ref, :ok, _, 1000 close(socket) #fails here ... end end defmodule PlexServer.UserSocket do use Phoenix.Socket use Guardian.Phoenix.Socket ## Channels # channel "rooms:*", PlexServer.RoomChannel channel "empire:*", PlexServer.EmpireChannel channel "user:*", PlexServer.UserChannel ## Transports transport :websocket, Phoenix.Transports.WebSocket def connect(_params,_) do :error end def id(_socket), do: nil end defmodule PlexServer.EmpireChannel do use PlexServer.Web, :channel use Guardian.Channel alias PlexServer.EmpireInstance alias PlexServer.EmpireServer ... def join("empire:" <> empire_id, %{claims: _claims, resource: user}, socket) do ... #Starts a process through a supervisor here end def join("empire:" <> _, _, _socket) do {:error, data_error(:auth, "not authorized, did you pass your jwt?")} end # Channels can be used in a request/response fashion # by sending replies to requests from the client def handle_in("ping", payload, socket) do {:reply, {:ok, payload}, socket} end def handle_in("show", _, socket) do ... end def handle_in("command", request, socket) do ... end def handle_in("remove", _, socket) do ... end def handle_in("ship_templates", _, socket) do ... end end
Following the answer linked in the comments I added some code:
Process.flag(:trap_exit, true) monitor_ref = Process.monitor(socket.channel_pid) close(socket)
Now I get a different error message: ** (exit) exited in: GenServer.call(PlexServer.EmpireSupervisor, {:terminate_child, :empire4}, :infinity) ** (EXIT) no process
You need to add permission under your manifest file add these
<receiver android:name=".YourBroadCastReceiverName" android:exported="true"></receiver>
-8168935 0 The best way is to create thumbnail of your image once uploaded to a server. Thumbnail should be 159x143 px, but if you need to show images now you can set for div fixed width with css property "overflow: hidden;" and just set height of your image. do not touch width
-22069334 0 In Java, does locking ensure correct order of reads and write to nonvolatile locationsSuppose I have a shared object of class:
class Shared { private int x = 0 ; private int y = 0 ; private Semaphore s = new Semaphore() ; public int readX() { s.p() ; int x0 = x ; s.v() ; return x0 ; } public void writeX(int x0) { s.p() ; x = x0 ; s.v() ; } public int readY() { s.p() ; int y0 = y ; s.v() ; return y0 ; } public void writeY(int y0) { s.p() ; y = y0 ; s.v() ; } }
Here Semaphore is a class that uses synchronized methods to provide mutual exclusion.
Now the following actions happen:
Could thread 0 read from its cache and find that x is 0? Why?
EDIT
Here is the Semaphore class
class Semaphore { private boolean available = true ; public synchronized void v() { available = true ; notifyAll() ; } public synchronized void p() { while( !available ) try{ wait() ; } catch(InterruptedException e){} available = false ; } }
-23573742 0 Store session data on a database server by changing the mode attribute to SqlServer
<sessionState mode="SqlServer" sqlConnectionString="data source=127.0.0.1;user id=sa; password=" cookieless="false" timeout="20" />
then query the session database
select SessionItemShort, SessionItemLong from ASPStateTempSessions
-32318180 0 How does the website "minutesplease.com" close tab in my chrome window? The website "http://minutesplease.com/" does something I thought was impossible - it closes a tab in my chrome (also without my permission!).
How is it possible for a website (not extension) to close a tab in my chrome window? Up to this moment I was conviced the most a website can do is stop to supply me with packets. In which case I will only get a connection error, not a tab termination. Also, not only did it close a tab, it closed a tab that wasn't his own (!). The only connection between this website and the tab is that it was responsible to open it.
-849453 0The only way to achieve what you want is opening several instances of SSMS by right clicking on shortcut and using the 'Run-as' feature.
-7258888 0AsyncTask
enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
AsyncTask
is designed to be a helper class around Thread
and Handler
and does not constitute a generic threading framework. AsyncTask
s should ideally be used for short operations (a few seconds at the most).
WARNING : The AsyncTask has an implicit reference to the enclosing Activity. If a configuration change happens the Activity instance that started the AsyncTask would be destroyed, but not GCd until the AsyncTask finishes. Since Activities are heavy this could lead to memory issues if several AsyncTasks are started. Another issue is that the result of the AsyncTask could be lost, if it's intended to act on the state of the Activity. Replace the AsyncTask by the new AsyncTaskLoader
More information:
Why not just cast the audioPlayer.currentTime
to an integer before you use stringWithFormat
?
[NSString stringWithFormat:@"%d", (int)(audioPlayer.currentTime)];
-12487363 0 Embed ASP.NET website within another ASP.NET website I have an ASP.NET site (site 1) that has some UI that uses jquery to bind the data to controls and CRUD methods that perform database operations.
I would like to embed this ASP.NET site 1 into another ASP.NET site (site 2) such that when a user clicks a button/link on site 2, site 1 is loaded in a modal popup and the user on site 2 can perform all the actions that they would on site 1 within that popup. So site 1 is effectively a black-box for site 2.
I had thought of using an iframe in site 2 to load site 1, but I am not sure how I would pass parameters to site 1. Any help or alternate solutions would be much appreciated.
I am using .NET 3.5
-30401787 0 Display three letters time zone code using jsTimezoneDetect scriptI am using jsTimezoneDetect script to detect user current timezone. Code below display result as America/Chicago
. Is there a way to display CDT
/CST
(depending on today date)?
var timezone = jstz.determine(); timezone.name();
Or is there any other script I can use?
-28771959 0You need to do css: nav{position:relative; z-index:} .pagefull{position:relative; z-index:1}
Actually java has many other editions but normally we did not use that in applications ,
list given below :
JavaSE JavaME JavaEE JavaFX JavaCard JavaDB JavaTV JavaEmbeded
and we can have 4 types of files in java :
Jar (Java archive) War (Wep applications archive) Ear (Enterprise application archive) Rar (Resource adapter archive)
sorry for speling mistakes ,,,,
-22791815 0Update:
GCC chokes on your function stringlength
. Try this:
constexpr size_t stringlength(char const* str, size_t i=0) { return str ? (str[i] ? 1 + stringlength(str, i+1) : 0) : 0; }
To GCC 4.6.3 this seems dubious:
static constexpr int const* c = &a[0]; static constexpr int const* d = &b[0];
Try this:
static constexpr int* c = &a[0]; static constexpr int* d = &b[0];
Old answer:
You code seems to be correct and with GCC 4.6.3 it also compiles.
int main() { const char* a = "hallo"; const char* b = "qallo"; std::cout << is_equal(a,b,5) << std::endl; constexpr const char* c = "hallo"; std::cout << is_equal(a,c,5) << std::endl; }
Be careful, that the strings you are giving to your functions are constants.
See here what is allowed with constexpr
.
Looking at the sources of wreq reveals that the Response
type comes from the http-client library. That is the same library used by the blog post you link to, and so the solution is the same that, presumably, was used in the post: import Network.HTTP.Client.Internal
, which exports the constructor.
static void Main(string[] args) { string t="<html> <head> <link rel='stylesheet' type='text/css' href='http://www.taxmann.com/css/taxmannstyle.css' /> </head> <body ><html><body style='background-color:Black;font-size:30px;color:#fff;'><html>\r\n<head><link href='http://www.taxmann.com/TaxmannWhatsnewService/Styles/style.css' rel='stylesheet' type='text/css' />\r\n<title>Finmin Aims to Halve Net Bad Loans of PSBs</title>\r\n<style type=\"text/css\">\r\nbody{font-family:Arial, Helvetica, sans-serif; font-size:12px; line-height:18px;text-align:justify;}\r\n.w100{width:100%;}\r\n.fl-l{float:left;}\r\n.ffla{font-family:Arial, Helvetica, sans-serif;}\r\n.fs18{font-size:18px;}\r\n.mart10{margin-top:10px;}\r\n.fcred{color:#c81616;}\r\n.tc{text-align:center;}\r\n.tu{text-transform:uppercase;}\r\n.lh18{line-height:18px;}\r\n</style>\r\n</head>\r\n<body>\r\n<div class=\"w100 fl-l\">\r\n<div class=\"w100 fl-l ffla fs18 mart10 fcred ttunderline tc tu\">Finmin Aims to Halve Net Bad Loans of PSBs</div>\r\n\r\n<div class=\"w100 fl-l lh18 mart10\">Concernedover the rising bad loans of the state-run banks, the finance ministry is working out a plan to reduce their net non-performing assets (NPAs) to 1% of net advances by the end of the current financial year.</div>\r\n\r\n</div>\r\n</body>\r\n</html>\r\n</body></html></body></html>" string resultValue = t.Replace("<html><head> <link rel='stylesheet' type='text/css' href='http://www.taxmann.com/css/taxmannstyle.css' /></head> <body ><html>", " <html><head> </head> <body ><html>"); //its not working Console.WriteLine(resultValue); }
This is my code But i m unable replace resultValue
.
I have a page that is run using AJAX. I have a control that is wrapped in a RadAjaxPanel that has multiple child controls in it. The RadAjaxPanel is updated when new items are selected. I also have a 3rd party javascript that needs to refresh during the callback.
Here is my problem.
When the callback happens, I use
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "RecommendationScript", "<script src='3rdparty.js'></script>, false);
This doesn't appear to work after the callback happens since I am not seeing the results. Even if I create a test external script that does a javascript alert, I won't see the alert after the callback. Everything works fine though if I don't use an external script and just put the alert in the RegisterStartupScript. However, that won't work for what I need to do.
Any ideas?
-35085553 0There seems to be a special character between the < and ?. Then it does not recognize it as start of php code.
Maybe your required file has some weird encoding? Which Editor are you using?
-9217078 0 backbone view does not bind after closing-initializing view (zombi view issue)I ran into this situation that is weird, in order to kill the zombie view i did something like this
remove: function() { if (this.onClose){ this.onClose(); } this.unbind(); $(this.el).unbind(); $(this.el).empty(); }, onClose: function() { if(this.model) this.model.unbind("change", this.render()); }
you might ask why both this.unbind and this.el unbind. i did this way because i'm closing my view after model update, and if i remove this.el unbind the POST is going more than once, (zombie issue)
but my problem is, after closing the view, next time when it's initialized it doesnt respond to the events, such as closing the view by clicking cross X
can someone plz help? thanks in advance.
-25876811 0If all you want to do is capture the h.264 stream and stick it into a container, I would utilize FFmpeg. I don't know the exact command line, so this is untested but try something like...
ffmpeg -i - -f mp4 output.mp4
Then, write to it over STDIN. It should detect your stream type after several packets, and begin writing to the MP4 file.
-34978437 0That library doesn't look like it will easily do bidirectional. But, since DMX512 is a simple serial protocol, there's nothing stopping you from writing your own routines that manipulate the UART directly. The library will be a great guide for this.
Now, having said that: what kind of situation do you have where you want a device to both control and receive? The DMX512 protocol is explicitly unidirectional, and at the physical layer it's a daisy-chain network, which prevents multiple masters on the bus (and inherently creates a unidirectional bus). If you are a slave and you are manipulating the bus, you risk clobbering incoming packets from the master. If you are clever about it, and queue the incoming packets, you could then perhaps safely retransmit both the incoming data and your own data, but be aware that this is a decidedly nonstandard (and almost certainly standards-violating) behavior.
-33547623 0 Hashmap returning reference instead of copyI have one model called Person with properties
name image age amount
and I have a singleton hashmap Hashmap<String,Person> globalPersonList
which contains list of person objects.
I am trying to retrieve one single object from my hashmap like
Person existingPerson = globalPersonList.get("key");
I want to create a new Person
instance and initiallize with existingPerson
properties like
Person person = new Person(); person = globalPersonList.get("key");
Now I want to set amount field to this person object. I tried like
newPerson.setAmount(100);
but it shouldn't affect globalPersonList
. I want amount value only in my newPerson object. But right now this is set in globalPersonList
also. after setting amount if I try to
globalPersonList.get("key").getAmount()
it is giving the amount that I set. Is it using the reference to new object? I want a seperate copy of Person object so that it won't affect main hashmap.
-5409418 0 Common Lisp: how to dynamically wrap existing functions, such as for a profiler?I am new at Lisp, and am trying different things out to improve my skills. I want to write a macro that wraps existing functions so that I can set up before and after forms for these functions, kind of like CLOS's auxilliary methods or Elisp's advice package. The trace function's ability to wrap code dynamically has intrigued me, and it seems useful to be able to do this myself.
So, how can I do this? How many ways can I do this? : )
Please note that I am using SBCL, and that, for the purposes of this question, I am not interested so much in the "right" way of doing this as I am in adding to my Lisp trick bag.
-10518782 0 iOS and ARC : How to retain self during asynchronous operations?It's the first time I'm fiddling around with iOS5 and ARC. So far, so good, it works, but I've run into some kind of a problem.
I have a custom UIStoryboardSegue
in which I use Facebook Connect (or other services) to log the user into my app. Simply put, it should do the following :
What happens instead, is that the login starts, but the segue is immediately released by ARC before it has any chance to complete.
I thought of a quick'n'dirty hack to prevent this:
@interface BSLoginSegue() { __strong BSLoginSegue *_retained_self; } @end // Stuff... // Other stuff... - (void) perform { login(); _retained_self = self; } - (void) loginServiceDidSucceed:(BSLoginService *)svc { ... _retained_self = nil; }
The thing is, it really is a hack, so I was wondering if there were any other, and more elegant way I could do the same?
-5782635 0The list class is a linked list, you cannot directly index into it. Also, iterators are not indices, + just doesn't makes any sense.
However, in theory, you should be able to copy an iterator, if you change q = mboxes.begin() + p into q = p it should set q to be an iterator pointing to the same location of p, and that may just solve your problem.
for (list<Box>::iterator p = mBoxes.begin(); p != mBoxes.end(); p++) { for (list<Box>::iterator q = p, q++; q != mBoxes.end(); q++) { if (p->isIntersecting(q)) { p->changeDirection(); q->changeDirection(); } } }
the q++ should simply skip the current element so you don't compare an item against itself.
-40604387 0 Query data with odata filterI have a question about a filter query and a none filter query.
A filter query:
/sap/opu/odata/sap/ZRFC1_SRV/SalesOrderHeaderSet?filter=SoId eq '5000001'
A none filter query:
/sap/opu/odata/sap/ZRFC1_SRV/SalesOrderHeaderSet('5000001')
What is the difference between those two queries?
-38928553 0 PHP : Allow user to comment and rate only once with their ip adressContext : I'm making a website where users can search for internet forfeit and I want to make a 5 star rating system and a comment system for every internet provider... But the users are only allowed to comment and rate only one time for each provider... I have tough about getting the user ip adress, then put it in a database when they comment and rate...
So i'm asking if some people have clue or idea of how i can do that...
You guys can see what i'm talking about here : http://fournisseursquebec.com/Fournisseurs/Fido.php
-9042399 0My experience with LabWindows CVI is that its built-in libraries are more geared to instrumentation (GPIB, analog and digital I/O, motion control, and so forth) and data display (GUI widgets like meters, sliders, switches, LEDs, simple graphs), rather than extensive libraries of numeric, statistical, or analytic routines. The development environment that comes with Labwindows CVI is pretty decent -- they have a drag-and-drop GUI building interface that makes it easy to position controls within windows and wire them up to your C code, if that matters to you.
But for your analytic needs, you might be better served with a product like Matlab or IDL, especially if your work is heavy on the plotting/visualization end of things.
If you want to stick with C, the GNU Scientific Library has a pretty extensive set of statistical and analytic routines.
-15388155 0 + [NSString stringWithContentsOfFile:] performanceI need to load files in iOS, now I use the + [NSString stringWithContentsOfFile:]
. The files are mostly 500kb to 5mb. I load an approx. 4mb large file and Instruments and stopwatch told me it needs 1.5 seconds to load this file. In my opinion its a bit slow, is there a way to get the string faster?
EDIT:
I try some things and notice now, the creation of the NSString is my problem it takes 97% of the time and not the real loading from disk.
-34434064 0each architecture has its own assembly language. and even within architectures there might be extensions which add extra commands (like the SSE extensions). Usually a Compiler can only create code for one architecture, and there might be optional flags which enable optimizations for the extensions. When these flags get enabled the program will usually only run on processors that support these extensions.
For programs and OS it usually means you should only use compiler options that are supported by all processors of the architecture they have to run on. If thats not optimized enough you have to deliver executables/libraries with multiple code paths for he different optimizations, and pick the right one at runtime.
-17632932 0You need to use 4545454545l
or 4545454545L
to qualify it as long
. Be default , 4545454545
is an int
literal and 4545454545
is out of range of int
.
It is recommended to use uppercase alphabet L
to avoid confusion , as l
and 1
looks pretty similar
You can do :
if(Long.valueOf(4545454545l).equals(Long.parseLong(morse)) ){ System.out.println("2"); }
OR
if(Long.parseLong(morse) == 4545454545l){ System.out.println("2"); }
As per JLS 3.10.1:
-20072314 0 How to set vertical text from bottom to top in html?An integer literal is of type long if it is suffixed with an ASCII letter L or l (ell); otherwise it is of type int (§4.2.1).
It is easy to set text from top to bottom
and there are enough resources to do that.
The problem is with bottom to top
vertical alignment.
See the image below-
Simply set the layout!
new Handler().postDelayed(new Runnable() { @Override public void run() { setContentView(R.layout.next); //where <next> is you target activity :) } }, 5000);
-38888441 0 If you will assign to the property of an object, which is not defined,it will create a new property and assign to it the value
possibility['status'] = { name : "lalala", text : "blabla" };
or
possibility.status = { name : "lalala", text : "blabla" };
-35908134 0 Fixed: https://jsfiddle.net/megp2yyx
Only change required was that of the <script src>
.
<head> <script>dojoConfig = {async: true, parseOnLoad: false}</script> <script src='//ajax.googleapis.com/ajax/libs/dojo/1.10.4/dojo/dojo.js'></script> <script> require(["dijit/TitlePane", "dojo/dom", "dojo/domReady!"], function(TitlePane, dom){ var tp = new TitlePane({title:"I'm a TitlePane", content: "Collapse me!"}); dom.byId("holder").appendChild(tp.domNode); tp.startup(); }); </script> </head> <body class="claro"> <div id="holder"></div> </body>
-17241885 0 When I Publish my project in iis log4net doesn't work When I debug it on Visual studio it works perfectly, but When I try to put it on my IIS directory it doesn't:
<?xml version="1.0"?> <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" /> </configSections> <log4net> <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender"> <param name="File" value="C:\\Users\\leandro\\Desktop\\Caderneta.log"/> <lockingModel type="log4net.Appender.FileAppender+MinimalLock" /> <appendToFile value="true" /> <rollingStyle value="Size" /> <maxSizeRollBackups value="3" /> <maximumFileSize value="1MB" /> <staticLogFileName value="true" /> <layout type="log4net.Layout.PatternLayout"> <param name="ConversionPattern" value="%n%n%d [%t] %-5p %c %n %m%n"/> </layout> </appender> <root> <level value="Error" /> <appender-ref ref="LogFileAppender" /> </root> </log4net> <system.web> <compilation debug="true" targetFramework="4.0" /> <webServices> <protocols> <add name="HttpPost"/> <add name="HttpGet"/> </protocols> </webServices> </system.web> </configuration>
First I tried just to put Caderneta.log on param name, but it doesn't looks been created. The path on my server exists for C:\Users\leandro\Desktop\Caderneta.log
, but it still not creating the file Caderneta.
According the msdn documentation from the where generic constraint you have to do it this way:
public interface IGenericRepository<T> where T : class
You must not have the : between the IGenericRepository< T> and the where.
-33179511 0 Moment js timezone off by 1 hourI can't figure out what I am doing wrong here.
Passing in a string to moment
, with the format and calling .toDate().
toDate() ends up returning a time that is off by 1 hour
moment("2015-11-19T18:34:00-07:00", "YYYY-MM-DDTHH:mm:ssZ").toDate() > Thu Nov 19 2015 17:34:00 GMT-0800 (PST)
The time should be 18:34
, not 17:34
. The timezone is showing -08
, when it should be showing -07
initial
is not supported by IE10
why not use auto?
-22859307 0 Where do Google and Twitter source political boundaries of cities, regions and states?I have recently noticed the nice dashes that Google Places puts around cities, regions, states etc. I've been hunting around in the Google Maps API and the Google Places API trying to find out how to access the information thus displayed, without success.
I've discovered that Twitter has a nice API for this and I would be tempted to use that instead of Google's, but I worry that the lines that Google draw and the lines that Twitter draw may not correspond.
Is it safe to assume that both companies are using the same data? If not, where do I find the appropriate API information for the Google implementation?
Alternatively, where do I find the geodata they're both using?
PLEASE NOTE I'm asking about this in the context of Australian geodata. Do Google and Twitter use the same or different resources?
-32953373 0Each then callback is called in order, and the promise will wait when a new promise is returned in the previous callback. The problem with your code is that promises do not wait for css animations. And since it does not wait it goes to the next callback and removes your element right away.
You can create(and return) a new promise in the first then
, and for that promise use a transitionend event listener to resolve/reject that new promise. This will make the promise wait till the transition is done and then execute the next callback
var prom = new Promise(function(res,rej){ var xhttp = new XMLHttpRequest(); xhttp.open("GET", "https://cors-test.appspot.com/test", true); xhttp.onload=function(){ console.log("loaded"); if(xhttp.status==200){ res(xhttp.response) } else{ rej(Error(xhttp.responseText)) } } xhttp.send(); }); prom.then(function(data){ var old = document.querySelector("#content"); return new Promise(function(res,rej){ old.addEventListener("transitionend",function(){ res(data); }); old.classList.add("remove"); }); }).then(function(data){ var parent = document.querySelector("#parent"); var old = document.querySelector("#content"); old.remove(); var div=document.createElement("div"); div.innerHTML="Data retrieved, length: "+data.length; parent.appendChild(div); });
.remove { opacity:0; } #parent div { -o-transition:all 2s; -moz-transition:all 2s; -webkit-transition:all 2s; transition:all 2s; }
<div id="parent"><div id="content">Content</div></div>
What css code should i use to make this transparent png element with a shadow in the png file, float over the upper image to avoid this white stripe?
http://postimg.org/image/ektu4srvn/
http://postimg.org/image/dged2yme3/
-36348763 0 How Do I Call an Async Method from a Non-Async Method?I have the below method:
public string RetrieveHolidayDatesFromSource() { var result = this.RetrieveHolidayDatesFromSourceAsync(); /** Do stuff **/ var returnedResult = this.TransformResults(result.Result); /** Where result gets used **/ return returnedResult; } private async Task<string> RetrieveHolidayDatesFromSourceAsync() { using (var httpClient = new HttpClient()) { var json = await httpClient.GetStringAsync(SourceURI); return json; } }
The above does not work and seems to not return any results properly. I am not sure where I am missing a statement to force the await of a result? I want the RetrieveHolidayDatesFromSource() method to return a string.
The below works fine but it is synchronous and I believe it can be improved upon? Note that the below is synchronous in which I would like to change to Asynchronous but am unable to wrap my head around for some reason.
public string RetrieveHolidayDatesFromSource() { var result = this.RetrieveHolidayDatesFromSourceAsync(); /** Do Stuff **/ var returnedResult = this.TransformResults(result); /** This is where Result is actually used**/ return returnedResult; } private string RetrieveHolidayDatesFromSourceAsync() { using (var httpClient = new HttpClient()) { var json = httpClient.GetStringAsync(SourceURI); return json.Result; } }
Am I missing something?
Note: For some reason, when I breakpoint the above Async Method, when it gets to the line "var json = await httpClient.GetStringAsync(SourceURI)" it just goes out of breakpoint and I can't go back into the method.
-32401250 0That would allow some kind of proxy-copy like this:
NotCopyable a, b; b = a; // Made a copy of a
It is pretty unlikely that you do not want copy construction but copy assignment. Move assignment would be a different deal of course, see e.g. std::unique_ptr
.
Singleton is basically the same. Why allow the self assignment? That just does not make sense.
-13824566 0You can use params to specify start_year
and end_year
of your select. Example:
<div class="field"> <%= f.label "Fecha de nacimiento:" %> <%= f.date_select :fecha_nacimiento, :start_year => 1950, :end_year => (Time.now.year - 10) %> </div>
Look at :end_year
, I used Time.now.year - 10
because I assumed that the minimum age to register is 10 years old.
Boa sorte =]
Reference: http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html#method-i-date_select
-23560149 0 Android adding information to a table when the alarm startedHi stackoverflow users I have the next problem: I have created a program that compare in a countdown timer 2 values( a feedback and a counter ) The counter is the value I set of the temperature for example and the feedback another value I get from outside.
When the countdown timer reach 0 if the counter is not equal with the feedback value the alarm start and I want to add the feedback and the counter to a log.
Example of a small piece of code is below, here I compare the counter with
if(Integer.parseInt(feedback.getText().toString()) != midvalue) { btnbool.setBackgroundColor(Color.RED); btnbool.setText("FALSE"); showup.setText(""+counter); letme = 2; if(alarmapornita == 0) { alarmapornita = 1; handler.post(thread); } alarma = 1; myhandler.post(mythread); healthy = false; Intent i = new Intent(getApplicationContext(), Log.class); i.putExtra("mymidvalue",midvalue); i.putExtra("myfeedback",Integer.parseInt(feedback.getText().toString())); startActivity(i); }
The problem is that with Intent I get only one entry to the table and when I get the alarm on it switch to the other activity. I don't know anything else how to use, is there any option to replace intent ?
-2371938 0You could create a regular expression that would match each format you want to accept. When one of them matches, you will know how to parse that particular string. If you think about it, there probably aren't more than 10 common formats people will use to type out an address 99.9% of the time.
-3071774 0 How can I use CodeIgniter's set_value for a field that's an array?I have a dropdown labeled "amenities[]" and it's an array. When I use CodeIgniter's form_validation, I want to re-populate it properly using set_value, but I'm not able to. Anyone have any input on this?
-34383881 0Turns out that setting .Focusable = False to all the Radio Buttons was the answer :-)
-22900619 0To iterate over the entire array:
for(i = 0; i < test.length; i++) { test[i].length // do something here with the length }
-13218714 0 It breaks the paradigms. Consider this one: Static members are members that every instance has in common, but its not clear how to extend this idea of shared to a class?
What did you expect the static keyword to do?
-22795290 0You're experiencing one-off errors because of the fact that ExcelApp.Cells isn't zero based and you have a header row.
To combat this you can use foreach and separate out your header export to a separate block. It does take a little bit more code but I find it easier to deal with and less error prone
int i = 1; int j = 1; //header row foreach(DataColumn col in dtMainSQLData.Columns) { ExcelApp.Cells[i, j] = col.ColumnName; j++; } i++; //data rows foreach(DataRow row in dtMainSQLData.Rows) { for (int k = 1; k < dtMainSQLData.Columns.Count + 1; k++) { ExcelApp.Cells[i, k] = row[k-1].ToString(); } i++; }
-37678853 0 Node.js module.export vs exports.start = start In the topic I am learning from the author is using the following code:
var http = require("http"); var url = require("url"); function start(route) { function onRequest(request, response) { var pathname = url.parse(request.url).pathname; console.log("Request for " + pathname + " received."); route(pathname); response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello World"); response.end(); } http.createServer(onRequest).listen(8888); console.log("Server has started."); } exports.start = start;
Where he exports it using exports.start = start;
When I was reading another topics about module exports people there used it like:
module.export = moduleName
It's probably pretty simple, but Please can you please clarify it for me?
Is there some difference and what is behind the scenes? :)
-9499384 0 Entity Framwork:Value cannot be null. Parameter name: keyIn my project I use Entity Framework with MySQL. this code:
objectContext.users.Include("posts").Take(2).ToList()
throws an exception: System.ArgumentNullException: Value cannot be null. Parameter name: key
with such stack trace:
[ArgumentNullException: Value cannot be null. Parameter name: key] System.Collections.Generic.Dictionary`2.FindEntry(TKey key) +12670485 MySql.Data.Entity.Scope.GetFragment(String name) +27 MySql.Data.Entity.SelectStatement.AddDefaultColumns(Scope scope) +177 MySql.Data.Entity.SelectStatement.Wrap(Scope scope) +90 MySql.Data.Entity.SelectGenerator.WrapJoinInputIfNecessary(InputFragment fragment, Boolean isRightPart) +251 MySql.Data.Entity.SelectGenerator.HandleJoinExpression(DbExpressionBinding left, DbExpressionBinding right, DbExpressionKind joinType, DbExpression joinCondition) +110 MySql.Data.Entity.SelectGenerator.Visit(DbJoinExpression expression) +33 MySql.Data.Entity.SqlGenerator.VisitInputExpression(DbExpression e, String name, TypeUsage type) +50 MySql.Data.Entity.SelectGenerator.VisitInputExpressionEnsureSelect(DbExpression e, String name, TypeUsage type) +19 MySql.Data.Entity.SelectGenerator.Visit(DbProjectExpression expression) +45 MySql.Data.Entity.SqlGenerator.VisitInputExpression(DbExpression e, String name, TypeUsage type) +50 MySql.Data.Entity.SelectGenerator.VisitInputExpressionEnsureSelect(DbExpression e, String name, TypeUsage type) +19 MySql.Data.Entity.SelectGenerator.Visit(DbSortExpression expression) +61 MySql.Data.Entity.SqlGenerator.VisitInputExpression(DbExpression e, String name, TypeUsage type) +50 MySql.Data.Entity.SelectGenerator.VisitInputExpressionEnsureSelect(DbExpression e, String name, TypeUsage type) +19 MySql.Data.Entity.SelectGenerator.Visit(DbProjectExpression expression) +45 MySql.Data.Entity.SelectGenerator.GenerateSQL(DbCommandTree tree) +73 MySql.Data.MySqlClient.MySqlProviderServices.CreateDbCommandDefinition(DbProviderManifest providerManifest, DbCommandTree commandTree) +401 System.Data.EntityClient.EntityCommandDefinition..ctor(DbProviderFactory storeProviderFactory, DbCommandTree commandTree) +608
It is interesting that objectContext.users.Take(2).ToList()
or objectContext.users.Include("posts").ToList()
works fine.
Anyone encountered this problem?
-34055291 0 Dropdown in parent div with overflow:autoFor a project, i need to create a view where a drop down menu is at the bottom of a parent div. A short fiddle here : http://jsfiddle.net/Gruck/6owhaa63/, where "move to" item opens some more options, as shown on this mockup
<div class="job"> <div class="job-main"> <div class="title"> some content </div> <div class="counters"> some other content </div> </div> <div class="ops"> <ul> <li><a href="#">edit</a></li> <li><a href="#">visualize</a></li> <li><a href="#">move to</a> <ul class="move-to"> <li>folder a</li> <li>folder b</li> </ul> </li> </ul> </div> </div>
And some css
.job { border-style: solid; border-color: #F2F2F2; border-width: 2px; background-color: #FFFFFF; overflow: auto; } .job-main { border-bottom: 1px solid #F2F2F2; overflow: hidden; } .title { width: calc(100% - 390px); height: 100px; float: left; min-width: 300px; padding:10px; background-color: #EE0000; } .counters { width: 362px; height: 80px; padding: 20px 0px 20px 0px; float: right; background-color: #00EE00; }
How to get the options to be displayed on top of the parent div ? is there anyway to do so yet keeping the options inside the div ?
I guess i would have to move the options to outside the parent div and mannualy position them, but i would like to make sure i don't miss a nicer way to do so.
Thanks for any idea you might offer :) Cheers
-2298827 0It doesn't matter, dirname() always return the path in the OS format.
dirname('c:/x'); // returns 'c:\' dirname('c:/Temp/x'); // returns 'c:/Temp' dirname('/x'); // returns '\'
-12500645 0 Reuse Sorting Function from JQuery DataTables I am using the ENUM sorting routine found at http://datatables.net/plug-ins/sorting. I would like to reuse that same function to sort another list outside of the DataTables plug-in (basically sorting a SELECT element on the same page as the DataTable). I want to avoid having to copy-and-paste (and maintain two sets of business rules) the features of the sort function.
For example, if this is the "plug-in" I'm using for DataTables:
jQuery.extend(jQuery.fn.dataTableExt.oSort, { "status-enum-pre": function (a) { switch (a) { case "Assigned": return 1; case "Contacted": return 2; case "Meeting Set": return 3; case "Closed": return 4; default: return 5; } }, "status-enum-asc": function (a, b) { return ((a < b) ? -1 : ((a > b) ? 1 : 0)); }, "status-enum-desc": function (a, b) { return ((a < b) ? 1 : ((a > b) ? -1 : 0)); } });
How can I re-use that function to sort the following select list?
<select> <option value="Contacted">Contacted</option> <option value="Assigned">Assigned</option> <option value="Closed">Closed</option> <option value="Meeting Set">Meeting Set</option> </select>
-37776297 0 Here is how to add new server.
Right Click On Your Project.
Go to Run As - > Run On Server.
Now check radio button indicating "Manually Define A new Server".
Now Select from drop Down "Tomcat V 8.0" and (if needed accordingly change server runtime environments below it ) browse installation directory and here select folder named liked this "Tomcat 8.0". do not open it again just select this and click "Finish".
A new server is added as indicating extra suffix by default as (2). Select this whenever running project.
-8240047 0Since you mention that the items can be sorted by 1, 2 or 3 fields, you can expand on jeroenh's response, and "merge" it with the logic from Orchard:
public interface IRepository<T> { IQueryable<T> All(); IQueryable<T> Sorted(Func<T, object> sort1, Func<T, object> sort2 = null, Func<T, object> sort3 = null); } public class Repository<T> : IRepository<T> { public IQueryable<T> All() { // TODO: Implement real data retrieval return new List<T>().AsQueryable(); } public IQueryable<T> Sorted(Func<T, object> sort1, Func<T, object> sort2 = null, Func<T, object> sort3 = null) { var list = All(); var res = list.OrderBy(sort1); if (sort2 != null) res = res.ThenBy(sort2); if (sort3 != null) res = res.ThenBy(sort3); return res.AsQueryable(); } }
-11408861 0 The height of the status bar and the title bar of your application seems to be about the same as the width of your ImageView
, which is 50px judging from your XML.
So then 50px + 270px = 320px, which is the total height of your screen (including the status and title bar).
-9951356 0You can put the configuration settings for any library in the main web.config. It's easy!
Connection strings are especially easy. Just add your connection string to the connectionstrings
section with the same name it has in the library's app.config, and you're done!
<connectionStrings> <add name="Sitefinity" connectionString="your connection string"/> </connectionStrings>
To add configuration settings, at the top of your web config, find the applicationSettings
section, and add your section's info. Note: be sure to set your library's settings access modifier to "Public". You can do this in the Properties ui.
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <section name="Your.Assembly" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> </sectionGroup>
Then, add the section under applicationSettings
.
<applicationSettings> <Your.Assembly> <setting name="TestSetting" serializeAs="String"> <value>a test value</value> </setting> </Your.Assembly> </applicationSettings>
-23904267 0 HTTP GET Request and content-location with respect to REST I have gone through the specification and I am not sure when to use content-location
vs location
. I am getting following response when I do HTTP GET with my rest server
ResponseEntity <200 OK,{ "store" : { "book" : [ { "category" : "reference", "author" : "Nigel Rees", "title" : "Sayings of the Century", "displayprice" : 8.95 }, { "category" : "fiction", "author" : "Evelyn Waugh", "title" : "Sword of Honour", "displayprice" : 12.99 }, { "category" : "fiction", "author" : "Herman Melville", "title" : "Moby Dick", "isbn" : "0-553-21311-3", "displayprice" : 8.99 }, { "category" : "fiction", "author" : "J. R. R. Tolkien", "title" : "The Lord of the Rings", "isbn" : "0-395-19395-8", "displayprice" : 22.99 } ], "bicycle" : { "color" : "red", "displayprice" : 19.95, "foo:bar" : "fooBar", "dot.notation" : "new", "dash-notation" : "dashes" } } },{Server=[Apache-Coyote/1.1], Content-Location=[http://localhost:25538/my-api/v1/edge/12345], Content-Type=[application/json], Transfer-Encoding=[chunked], Date=[Wed, 28 May 2014 05:19:43 GMT]}
Is my usage of content-Location
correct to show exact URL for the resource.
As an update, you could just set freezesText="true"
http://developer.android.com/reference/android/R.attr.html#freezesText
<TextView android:id="@+id/eltemas" android:layout_width="wrap_content" android:layout_height="wrap_content" android:freezesText="true"/>
Or
This is the simplest example:
TextView yourTextView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); yourTextView = (TextView) findViewById(R.id.your_textview); } @Override protected void onSaveInstanceState(Bundle outState) { outState.putString("YourTextViewTextIdentifier", yourTextView.getText().toString()); super.onSaveInstanceState(outState); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); yourTextView.setText(savedInstanceState.getString("YourTextViewTextIdentifier")); }
But having an inner class that represents your state will be much nicer when you start saving a lot of objects on orientation change.
Using an inner class it would look like this below. You can imagine as you have more and more state to save the inner class makes it much easier (less messy) to handler.
private static class State implements Serializable { private static final String STATE = "com.your.package.classname.STATE"; private String yourTextViewText; public State(String yourTextViewText) { this.yourTextViewText = yourTextViewText; } public String getYourTextViewText() { return yourTextViewText; } } @Override protected void onSaveInstanceState(Bundle outState) { State s = new State(yourTextView.getText().toString()); outState.putSerializable(State.STATE, s); super.onSaveInstanceState(outState); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); State s = (State) savedInstanceState.getSerializable(State.STATE); yourTextView.setText(s.getYourTextViewText()); }
-25215043 0 The formatted phone number displayed in the infoWindow is returned in the placeDetails response, which happens when the marker is clicked, it isn't available in the nearbySearch response, which is used to create the sidebar.
-26632688 0In case anyone is debugging via bluetooth and stumbles upon this thread, write:
adb -s localhost:4444 uninstall example.com.yourappname
-24101344 0 First of all, there's nothing wrong with readable URIs and with users being able to easily explore your API by building URIs by hand. As long as they are not using that to drive the actual API usage, that's not a problem at all, and even encouraged by Roy Fielding himself. Disagreement on that on the basis that URIs must be opaque is a myth. Quoting Fielding himself on that matter:
Maybe I am missing something, but since several people have said that REST implies opaqueness in the URI, my guess is that a legend has somehow begun and I need to put it to rest (no pun intended).
REST does not require that a URI be opaque. The only place where the word opaque occurs in my dissertation is where I complain about the opaqueness of cookies. In fact, RESTful applications are, at all times, encouraged to use human-meaningful, hierarchical identifiers in order to maximize the serendipitous use of the information beyond what is anticipated by the original application.
It is still necessary for the server to construct the URIs and for the client to initially discover those URIs via hypertext responses, either in the normal course of creating the resource or by some form of query that results in a hypertext list. However, once that list is provided, people can and do anticipate the names of other/future resources in that name space, just as I would often directly type URIs into the location bar rather than go through some poorly designed interactive multi-page interface for stock charts.
http://osdir.com/ml/web.services.rest/2003-01/msg00074.html
If you need your client developers to follow the hyperlinks and not build URIs by hand, from my experience I think the best way to do that is to promote it as a cultural change in your work environment. In my case I had a supportive manager, so it was much easier. You should warn them that the URI namespace is under control of the server and the URIs may change anytime. If their clients break because they failed to comply, it's not your responsibility. It also helps a lot to have some sort of workshop or presentation to explain how HATEOAS works and the benefits for everyone. I noticed how a lot of street-REST developers think it's superfluous, until they actually get it.
Now, to address your main question, you shouldn't document the API, you should focus your documentation efforts on your media-type. Quoting Fielding again:
A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state, or in defining extended relation names and/or hypertext-enabled mark-up for existing standard media types. Any effort spent describing what methods to use on what URIs of interest should be entirely defined within the scope of the processing rules for a media type (and, in most cases, already defined by existing media types). [Failure here implies that out-of-band information is driving interaction instead of hypertext.]
http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven
That means, you should have custom media-types for your representations, and instead of documenting API endpoints or URIs, you should document those media-types and the operations for the links available in them. For instance, let's say you have an API for a Q&A site like StackOverflow. Instead of having an API documentation telling them that they should POST to the rel:answers link in the representation of a question in order to answer it with their current user, your questions should have a media-type of application/vnd.yourcompany.question+xml
and on the documentation for that media-type you say that a POST to a rel:answers http link will answer the question.
I don't know of any existing tools for this, but from my experience, any tool that can be used to generate documentation from abstract models can be used for this.
I don't know how your ecosystem of APIs is, but what works for me is to have a generic documentation with a gentle introduction to REST, addressing some of the misconceptions, and detailed general usage to your patterns, that should apply to any API. After that, each individual server should have its own documentation, focused on the media-type.
I don't like the idea of returning documentation in the text/html
representation, because that's supposed to represent the resource itself, but I love the idea of having a rel:doc link pointing to your HTML documentation for that media-type.
I am building a web widget which will be very easy to integrate. Say http://www.bicycleseller.com/
wants to integrate my widget on his web page. All he has to do is copy and paste the following to the head section of his page:
<script src="http://www.widgetprovider.com/widget.js" type="text/javascript"></script> <script> Widget.create("123456accessKeyOfBicycleSeller").render("myWidget"); </script>
and <div id="myWidget"></div>
to anywhere in the body section. The widget will be displayed in that div.
I, as the widget provider, host the widget.js:
var Widget = new function () { this.url = "www.widgetprovider.com/widget.jsp"; this.name = ""; this.parameters = "width=400,height=200,screenX=750,screenY=300,resizable=0"; this.create = function (accessKey) { this.accessKey = accessKey; return this; }; this.render = function (divId) { // make sure the document is fully loaded and place the widget on BicycleSellers page. // when the widget (a jpeg) is clicked, a jsp page I host will popup. window.onload = function () { document.getElementById(divId).innerHTML = '<img src="images/widget-image.jpg" onclick="Widget.display()"/>'; }; return this; }; this.display = function () { // open a popup window that displays a page I host. var popup = window.open(this.url + "?accessKey=" + this.accessKey, this.name, this.parameters); popup.focus(); return this; }; };
So, the BicycleSeller places the widget on his page and when his users click on it, a popup appears that show them content from a page I host. However, each webmaster that wants to embed my widget, has to provide an accessKey
, unique to them, because the popup's content will be dependent on that.
My questions are:
1) In this scenario, anyone who goes to bicycleseller.com
and views the HTML source can see his accessKey
which is hard-coded in the head section. Then they can just navigate to www.widgetprovider.com/widget.jsp?accessKey=123456
. I don't want that to happen. What can be done about this? For instance; I was looking at the source of Facebook and they seem to hide everything very well.
2) Is this a good way to go on building a widget? I was thinking of a lightbox rather than a popup window (which might be blocked by a popup blocker - although in this example it does not). Any comments/suggestions welcome.
3) If I try to place to widgets and write Widget.create("key1").render("div1"); Widget.create("key2").render("div2");
two images are generated. But when clicked, both popups display key1
s information. This is because the Widget
class in widget.js
is singleton. If I don't make it singleton, then I can't place the image's onclick
attribute (Widget.display()
). What do I do for that?
Looking for help on the three questions. Any help will be greatly appreciated. Thanks.
-31258582 0Replace
x = document.getElementById("show").innerHTML = verse;
with
x = document.getElementById("show").innerHTML = document.getElementById("show").innerHTML + verse;
I hope this helps.
Thanks, Charles.
-38070454 0You can use NSNotificationCenter to make calls between the 2 different views. Add the following code in viewDidLoad
method where you have UICollectionView
:
NSNotificationCenter.defaultCenter().addObserver(self, selector: "loadList:", name:"load", object: nil)
and then add this method further down in your UIViewContoller
:
func loadList(notification: NSNotification){ self.collview.reloadData() }
and from other class when you want to reload collection view:
NSNotificationCenter.defaultCenter().postNotificationName("load", object: nil)
-23335583 0 Its server side problem, its nothing to do with android. For this make sure that your sever code capable to handle multiple request at a time.
-8502585 0public IDictionary<string, string> ValidateForDeletion(Account ac) { var account = _accountRepository.GetPkRk(ac.PartitionKey, ac.RowKey); if (account == null) { _errors.Add("", "Account does not exist"); } else if (_productRepository.GetPk("0000" + ac.RowKey).Count() != 0) { _errors.Add("", "Account contains products"); } return _errors; }
This will get rid of your multiple return statements
-1330990 0Are you doing a web application? I believe that for non-web applications, you do not need admin rights.
If this is not a web application, maybe it's just a file system permissions issue?
From:
http://msdn.microsoft.com/en-us/library/ms165100.aspx
"User permission requirements for Visual Studio vary depending on the operating system and the Visual Studio version. On Windows Vista, Visual Studio 2008 does not require administrator permissions to perform most tasks, but Visual Studio 2005 must run under administrator permissions to perform tasks correctly. On Windows Server 2003 and earlier, members of the Users group can perform most activities in the integrated development environment (IDE)."
-16709350 0 Hide all instances of a tag using jQueryI want to "play" with jQuery's hide()
function on a blog that I have and I want to make it so that clicking a button will hide all "cake names" on my page. I don't really know how to do that because I'm a beginner in jQuery. Can somebody help me, please? My code is:
<?php @include APP_PATH . '/view/snippets/header.tpl.php'; ?> <h2>Our cakes</h2> <script> $(document).ready(function(){ $("button").click(function(){ $("h2").hide(); }); }); </script> <?php if ($cakes) : ?> <ol> <?php foreach ($cakes as $cake) : ?> <li> <h3><?php echo $cake->name; ?></h3> <ul> <li><b>Quantity:</b> <?php echo $cake->quantity ?></li> <li><a href="<?php echo APP_URL ?>cake/view/<?php echo $cake->id ?>">View</a></li> </ul> </li> <?php endforeach; ?> </ol> <body> <button>Click me</button> </body> <?php else : ?> <p>Sorry, no sugar for you, babyyy!!</p> <?php endif; ?> <?php @include APP_PATH . '/view/snippets/footer.tpl.php'; ?>
I tried something but it doesn't work.
-25733192 0 Batch File - Creating multiple files with different namesI have a batch file and it contains the following code:
@echo off color 0e :initialize set filemaker=1 echo How many files? echo. set /p uservar= echo Creating... for /l %%x in (1, 1, %uservar%) do echo. 2>%CD%\%filemaker%.txt & set /a filemaker=%filemaker%+1 & timeout /t 1 /nobreak >nul echo %filemaker% pause
And everytime I execute it, the file that are generated (regardless of the value of %uservar%) is ALWAYS name 2, and there is always ony one file! I would like multiple with different names like, file 1 is name 1, file 2 is name 2, and so on.
Any help is appreciated!
-2204702 0The class defining __slots__
(and not __getstate__
) can be either an ancestor class of yours, or a class (or ancestor class) of an attribute or item of yours, directly or indirectly: essentially, the class of any object in the directed graph of references with your object as root, since pickling needs to save the entire graph.
A simple solution to your quandary is to use protocol -1
, which means "the best protocol pickle can use"; the default is an ancient ASCII-based protocol which imposes this limitation about __slots__
vs __getstate__
. Consider:
>>> class sic(object): ... __slots__ = 'a', 'b' ... >>> import pickle >>> pickle.dumps(sic(), -1) '\x80\x02c__main__\nsic\nq\x00)\x81q\x01.' >>> pickle.dumps(sic()) Traceback (most recent call last): [snip snip] raise TypeError("a class that defines __slots__ without " TypeError: a class that defines __slots__ without defining __getstate__ cannot be pickled >>>
As you see, protocol -1
takes the __slots__
in stride, while the default protocol gives the same exception you saw.
The issues with protocol -1
: it produces a binary string/file, rather than an ASCII one like the default protocol; the resulting pickled file would not be loadable by sufficiently ancient versions of Python. Advantages, besides the key one wrt __slots__
, include more compact results, and better performance.
If you're forced to use the default protocol, then you'll need to identify exactly which class is giving you trouble and exactly why. We can discuss strategies if this is the case (but if you can possibly use the -1
protocol, that's so much better that it's not worth discussing;-) and simple code inspection looking for the troublesome class/object is proving too complicated (I have in mind some deepcopy-based tricks to get a usable representation of the whole graph, in case you're wondering).
Answer by Firo is correct. Only change required is the syntax used to set/replaced object in NSMutableArray.
Correct syntax is :
[yourMutableArray replaceObjectAtIndex:i withObject: [[NSString alloc] initWithData:[yourMutableArray objectAtIndex:i] encoding:NSASCIIStringEncoding];
-7520819 0 Backslashes disapearing after my vb.net query to Mysql I'm having some problems, when I do my query from my vb.net program to my mysql DB the data is sent, but its missing some things, let me explain.
My query is pretty simple I'm sending a file path to my DB so that after I can have a php website get the data and make a link with the data from my DB, but when I send my data the results look like this...
\server_pathappsInst_pcLicences_ProceduresDivers estCheck_list.doc
which should look like
\\server_path\apps\Inst_pc\Licences_Procedures\Divers\test\Check_list.doc
I don't know if its my code that's not good or my configurations on my mysql server please help...
Here's my code
'Construct the sql command string cmdString = "INSERT into procedures(Nom, Lien_Nom, Commentaires) VALUES('" & filenameOnly_no_space_no_accent & "', '" & str_Lien_Nom_Procedure & "', '" & str_commentaires_Procedure & "')" ' Create a mysql command Dim cmd As New MySql.Data.MySqlClient.MySqlCommand(cmdString, conn) Try conn.Open() cmd.ExecuteNonQuery() conn.Close() Catch ex As MySqlException MsgBox("Error uppdating invoice: " & ex.Message) Finally conn.Dispose() End Try
Sorry I got a call and could continue my comment so here's the rest :X
Well I guess that would work, but my program never uses the same path since in uploading a file on a server, so this time the document I wanted to upload was this path
\\Fsque01.sguc.ad\apps\Inst_pc\Licences_Procedures\Divers\test\Check_list.doc
but next time its going to be something else so I can't hard code the paths, I was looking more of a SQL query which that I might not know, since I already thought about searching my string and if it finds a backslash it adds another one, but I feel its not a good way to script the whole thing...
Anyway thanks a lot for your help
-38237010 0Add isEqualTo(:)
requirement to JABPanelChangeSubscriber
protocol
public protocol JABPanelChangeSubscriber { func isEqualTo(other: JABPanelChangeSubscriber) -> Bool }
Extension to JABPanelChangeSubscriber
protocol with Self
requirement
extension JABPanelChangeSubscriber where Self: Equatable { func isEqualTo(other: JABPanelChangeSubscriber) -> Bool { guard let other = other as? Self else { return false } return self == other } }
Remember to make objects conform
Equatable
protocol too
class SomeClass: Equatable {} func == (lhs: SomeClass, rhs: SomeClass) -> Bool { //your code here //you could use `===` operand } struct SomeStruct: Equatable {} func == (lhs: SomeStruct, rhs: SomeStruct) -> Bool { //your code here }
Then find the index
func indexOf(object: JABPanelChangeSubscriber) -> Int? { return subcribers.indexOf({ $0.isEqualTo(object) }) }
If you want to check the existence of an object before adding them to the array
func addSubscriber(subscriber: JABPanelChangeSubscriber) { if !subscribers.contains({ $0.isEqualTo(subscriber) }) { subscribers.append(subscriber) } }
-18330933 0 I've found seen screen shaking issues are commonly to do with the order in which you process events, update objects and the camera, before drawing the scene (or the physics engine is causing it :P). With a high framerate you might not notice small imperfections. You might want to add a Sleep/usleep to help expose these issues. For example, if your camera position is based on the camera rotation, but you update the position before processing the mouse events the camera position/rotation can be a frame out of sync.
This is a good reason to process inputs, movement and rendering in very separate stages.
Your lookAt function does look rather complex. lookAt is very useful when you want a camera that looks-at something, but in this case you're after a camera that looks-from a camera position. This is easier to implement by manually constructing the inverse transformations to position the camera object before drawing the sceene. For example, if you want to move left, translate everything else right (thus inverse)...
glLoadIdentity(); glRotatef(camera.rotX, 1.0f, 0.0f, 0.0f); glRotatef(camera.rotY, 0.0f, 1.0f, 0.0f); glRotatef(camera.rotZ, 0.0f, 0.0f, 1.0f); glTranslatef(-camera.posX, -camera.posY, -camera.posZ);
-27208498 0 Here are two examples of ways in which you could align a div in the middle:
Using HTML:
<div class="center" style="margin: 0 auto;"></div>
Styling in a separate CSS file:
.center { margin: 0 auto; }
If you are making three columns and want them to resize according to the window width, you set the value of their width to be 33%. Here is an example:
.center { width: 33%; } .left { width: 33%; } .right { width: 33%; }
-6358610 0 You have to use TransformFilter. Hope this help.
TextView textview = (TextView) findViewById(R.id.mytext); textview .setText("WordToBeLinked"); TransformFilter mentionFilter = new TransformFilter() { public final String transformUrl(final Matcher match, String url) { return new String("http://mydomain.com/something"); } }; Pattern pattern = Pattern.compile("."); String scheme = ""; Linkify.addLinks(textview, pattern, scheme, null, mentionFilter);
Since there is no Pattern and scheme in your case, so they are just place holder.
-18448535 0 sails.js + passport.js : managing sessionsI am trying to implement a facebook connection in sails using passport. Therefore, I've created a passport.js file in my services folder, the code is given below. It looks like the login is done successfully, however the user serialization doesn't seem to work as the console.log that I put in it never appears in the console and I cannot access the user id trhough req.user once the user is supposed to be logged in. Did anyone managed to get passport working with sails?
var passport = require('passport') , FacebookStrategy = require('passport-facebook').Strategy, bcrypt = require('bcrypt'); // helper functions function findById(id, fn) { User.findOne(id).done( function(err, user){ if (err){ return fn(null, null); }else{ return fn(null, user); } }); } function findByUsername(u, fn) { User.findOne({ username: u }).done(function(err, user) { // Error handling if (err) { return fn(null, null); // The User was found successfully! }else{ return fn(null, user); } }); } // Passport session setup. // To support persistent login sessions, Passport needs to be able to // serialize users into and deserialize users out of the session. Typically, // this will be as simple as storing the user ID when serializing, and finding // the user by ID when deserializing. passport.serializeUser(function(user, done) { console.log("utilisateur serilizé!"); done(null, user.uid); }); passport.deserializeUser(function(id, done) { //console.log("coucou"); findById(id, function (err, user) { done(err, user); }); }); // Use the LocalStrategy within Passport. // Strategies in passport require a `verify` function, which accept // credentials (in this case, a username and password), and invoke a callback // with a user object. // using https://gist.github.com/theangryangel/5060446 // as an example passport.use(new FacebookStrategy({ clientID: 'XXX', clientSecret: 'XXX', callbackURL: "http://localhost:1337/callback" }, function(accessToken, refreshToken, profile, done) { User.findOne({uid: profile.id}, function(err, user) { if (err) { return done(err); } if (user) { //console.log('momo'); User.update({uid : user.uid},{token : accessToken},function(){done(null, user);}); } else { console.log(profile); var user_data = { token : accessToken , provider: profile.provider , alias: profile.username , uid: profile.id , created: new Date().getTime() , name: { first: profile.name.givenName , last: profile.name.familyName } , alerts: { email: true , mobile: false , features: true } }; console.log(user_data); User.create(user_data).done(function(err, user) { console.log(err); if(err) { console.log("err");throw err; } done(null, user); }); } }); } ));
-27767148 0 You have to register the Provider in a javax.ws.rs.core.Application. That Application should be registered as a service with a higher service ranking than the default one created by the Amdatu Wink bundle.
The following is a working example.
The Exception Mapper itself:
@Provider public class SecurityExceptionMapper implements ExceptionMapper<SecurityException>{ @Override public Response toResponse(SecurityException arg0) { return Response.status(403).build(); } }
The Application:
import java.util.HashSet; import java.util.Set; import javax.ws.rs.core.Application; import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; public class MyApplication extends Application { @Override public Set<Object> getSingletons() { Set<Object> s = new HashSet<Object>(); s.add(new JacksonJsonProvider()); s.add(new SecurityExceptionMapper()); return s; } }
Activator setting the service ranking property.
public class Activator extends DependencyActivatorBase{ @Override public void destroy(BundleContext arg0, DependencyManager arg1) throws Exception { } @Override public void init(BundleContext arg0, DependencyManager dm) throws Exception { Properties props = new Properties(); props.put(Constants.SERVICE_RANKING, 100); dm.add(createComponent().setInterface(Application.class.getName(), props).setImplementation(MyApplication.class)); } }
-34711110 0 What is causing "The type or namespace name 'UI' does not exist in the namespace" error? I am working on a UWP application and I am trying to do something with the values of a SelectedItem in a GridView. So as I usually do with WPF I went into the XAML and Typed my event name in the XAML and let VS create the event in code for me.
<GridView x:Name="DataGrid1" ItemClick="dg_ItemClick"> <!-- Just --> <!-- Some --> <!-- Normal --> <!-- XAML --> </GridView>
and the VS created event looks like this
private void dg_ItemClick(object sender, Windows.UI.Xaml.Controls.ItemClickEventArgs e) { Biz.Customer cust = e.ClickedItem as Biz.Customer; var messageDialog2 = new MessageDialog(cust.Code, cust.Company); messageDialog2.ShowAsync(); }
Right away I get a red squiggly line under the UI in the Windows.UI.Xaml.Controls part. There is a using at the top of the page to include that and VS wouldn't let add any other UWP references.
I can get the error to go away as I have in other parts of the application by changing the ItemClickEventArgs to RoutedEvenArgs but in this case I really need the ClickedItem as an argument to be passed to the code behind.
I have just talked to someone else getting started with UWP and they said they are having the same issue on other cLick events. So are we both doing something wrong or is there something missing from our application that is needed for the UI to be recognized?
The full error I am getting is this: Error CS0234 The type or namespace name 'UI' does not exist in the namespace 'app name' (are you missing an assembly reference?)
-32996138 0 Different Layout Managers in an ActivityI have two different kinds of data that one of them needs to be displayed in a grid (the red ones) and the other needs to be displayed linear (the blue ones). the whole page scrolls and the data sources may change so the views should update dynamically. How can I implement this in android and probably with RecyclerView
?
I have a Report, which needs to display 4 different sub reports. I have implemented this report by taking a table with 4 rows and placing a sub-report in each row. Now, when I run the report, the reports are not being displayed in the order in which I arranged in the table.
Am I missing any thing?
In async Begin*
is always followed by End*
. See Using an Asynchronous Server Socket. Your accept method should be something like:
try { listener.Bind(localEP); listener.Listen(10); while (true) { allDone.Reset(); Console.WriteLine("Waiting for a connection..."); listener.BeginAccept( new AsyncCallback(SocketListener.acceptCallback), listener ); allDone.WaitOne(); } } catch (Exception e) {
Server, means that an app that listens on specified port/ip. Is usually, always in a listening mode - that's why it is called a server. It can connect and disconnect a client, but is always in listening mode.
This means, when a server disconnects a client - even then - it is in listening mode; meaning it can accept the incoming connections as well.
Though, disconnection request can come from client or can be forcefully applied by server.
The process for a server is:
The process for client is:
There are several ways for server to handle the incoming clients, couple, as follows:
List<TcpClient>
._
private void ListenForClients() { this.tcpListener.Start(); while (true) { //blocks until a client has connected to the server TcpClient client = this.tcpListener.AcceptTcpClient(); //create a thread to handle communication //with connected client Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm)); clientThread.Start(client); } }
select top (1) with ties title, pages from books order by pages desc
-26360140 0 The answer by Howlin is correct, but you shouldn't edit the file in the woocommerce plugin folder. You should copy the specific template file from woocommerce to your own theme directory and edit that file. Removing the link in the copied file will create the same effect as your desired filter.
-22121243 0You should send metadata with your data so the server understands what it needs to do. This means you are defining the protocol to which all clients and servers need to support. For these two different cases (either it is a plain chat message or some command the server needs to execute) you can roll your own protocol. But in software development things always start small and grow large (rapidly).
You might want to look into something like XMPP which is a XML based chat message protocol. http://xmpp.org/xmpp-protocols/
-25444093 0I'd just use standard java java.awt.Point
. Nothing additional needed.
like
Vector<Point> myVec = new Vector<Point>;
you can still use these 2D Points like
int key; int value; Point point = new Point(key, value); myVec.add(point);
and if you want to check the entries for a spec element
for(Point p : myVec) { if(p[0] == searchKey) //...do something }
-25428111 0 I'm calling tableModel.fireTableCellUpdated(tableRowIndex, tableColumnIndex);
That is wrong. You should never invoke the firXXX methods directly. That is the job of the TableModel to invoke the appropriate event when the data is changed.
I will update the corresponding icon in that cell.
All you need to do is invoke model.setValueAt(...) method to change the Icon and the model will notify the table that data has changed so the table can repaint itself.
examTable.repaint(...)
Again you should not need to manually invoke repaint on the table
But problem comes when I drag and drop the columns from one position to another in Table header.
Not sure why you need special code for this if you follow the advice from above. But if for some reason it is still necessary then you need to look at the convertColumnIndex...(...)
methods to make sure you are using the proper index for your column.
What I want to do is take data from a dbf file and insert it in a table. Which I've already done. Since there are many files, a For-Each Container is being used. However, before inserting it into a table, I want to look at the date fields and compare it to a date variable. If the dates match the variable, then move on to the step of the flow. But if any of the dates don't match the variable, then that file and its contents are discarded and the next file is looked at.
How do I accomplish this in SSIS?
-13130013 0 Missing parameter type error by calling toSet?Trying to generate, from a list of chars, a list of unique chars mapped to their frequency - e.g. something like:
List('a','b','a') -> List(('a',2), ('b',1))
So, just mucking around in the console, this works:
val l = List('a', 'b', 'c', 'b', 'c', 'a') val s = l.toSet s.map(i => (i, l.filter(x => x == i).size))
but, shortening by just combining the last 2 lines doesn't?
l.toSet.map(i => (i, l.filter(x => x == i).size))
gives the error "missing parameter type".
Can someone explain why Scala complains about this syntax?
-27111520 0 Jstree JSON objectIn order to populate Jstree with nodes I want to create a JSON object looks like bellow,
[ { "data": "Basics", "state": "closed", "children": [ { "data": "login", "state": "closed", "children": [ "login", { "data": "results", "state": "closed", "attr": { "id": "node-123" } } ] }, { "data": "Basics", "state": "closed", "children": [ "login", "something", { "data": "results", "state": "closed", "attr": { "id": "node-456" } } ] } ] }, { "data": "All", "state": "closed", "children": [ { "data": "AddCustomer", "state": "closed", "children": [ "login", "Add", { "data": "results", "state": "closed", "attr": { "id": "node-789" } } ] } ] } ]
But I am stuck with creating model object related to this JSON object. Is there any common model object that I can generate above JSON object?
-1685921 0 MVP Vs MVVM - whyI was using MVP when I was working with winform. but I moved to MVVM when i started playing with WPF or Silverlight.
The only thing that I noticed is that we don't need to sync with the data between View and ViewModel in MVVM pattern because of powerful binding.
My question are ~
1) Binding (that helps us not to sync View and ViewModel manually) is the only advantage of using MVVM.
2) Is there any other advantage MVVM over MVP? what are the differences?
3) The code below is MVVP pattern or MVVM or both?
interface IView{ void ShowMessage(string message); } class View : IView { public void ShowMessage(string message){ MessageBox.Show(this, message); } } class ViewModel{ private IView view; public ViewModel(IVew view){ this.view = view; } ........ view.ShowMessage("This is a msg"); }
Thanks.
-20082189 0 Error message: [__NSCFType _canScrollX]: unrecognized selectorI’m updating an that app usually, but not always, crashes when I swipe from a UIWebView
to a UIScrollView
. Sometimes it gives the error shown in the title. Most of the time there is no error message. The odd thing is that it does not crash if I use buttons to move to the next screen. The buttons and the swipe gesture recognizer call the same handler.
I’m getting the crash on a first generation iPad running iOS 5.1.1 As far as I know it worked fine on whatever version of iOS 5 that was current when I submitted it in June. I download a copy of the app from the app store and it also crashes on the iPad running iOS 5.1.1.
My workaround is to disable swiping on versions below 6.0.
if ( SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"6.0") ) { UISwipeGestureRecognizer *swipeNext; swipeNext = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeNext)]; [swipeNext setDirection:(UISwipeGestureRecognizerDirectionLeft)]; [self.view addGestureRecognizer:swipeNext]; }
It works fine when I test it in iOS6 and iOS7. I’m not setting _canScrollX
. In fact, I can’t even find that method [edit: It’s probably a property, not a method] in the documentation. I’m only setting two properties on the scrollview.
CGFloat quizHeight = ceilf(.9f * _parentView.bounds.size.height - verticalOffset); CGRect quizBounds = CGRectMake(0, verticalOffset, _parentView.bounds.size.width, quizHeight ); _quizView = [[UIScrollView alloc] initWithFrame:quizBounds]; _quizView.delaysContentTouches = YES; _quizView.maximumZoomScale = 1.0f; // Helps with swiping
I don’t think it is a memory issue, since it usually crashes on the first screen. I checked my code for methods that aren’t supported in iOS5 and there aren’t any. But even if there were, I’d think the app would crash all the time, instead of some of the time, and it would give me an error message about the selector causing the problem.
So I’m stumped. Any thoughts?
[Edit{ I tried running with zombies enabled and don’t have any issues. When I use the on-screen button to move from screen to screen, live bytes fluctuates but returns to around 2.4MB. If I swipe, I get a crash and no indication of why in Instruments.
The only difference between successful movement from screen to screen and a crash is the swipe gesture. The button on the screen and the swipe gesture recognizer both call the same method.
This is the crash log.
Thread 0 name: Dispatch queue: com.apple.main-thread Thread 0 Crashed: 0 libobjc.A.dylib 0x336f0f78 objc_msgSend + 16 1 UIKit 0x332f50e2 -[UIScrollViewPanGestureRecognizer _centroidMovedTo:atTime:] + 298 2 UIKit 0x332f4f50 -[UIPanGestureRecognizer touchesMoved:withEvent:] + 308 3 UIKit 0x332f4d52 -[UIScrollViewPanGestureRecognizer touchesMoved:withEvent:] + 70 4 UIKit 0x331ec484 -[UIWindow _sendGesturesForEvent:] + 356 5 UIKit 0x331ec1ee -[UIWindow sendEvent:] + 82 6 UIKit 0x331d268e -[UIApplication sendEvent:] + 350 7 UIKit 0x331d1f34 _UIApplicationHandleEvent + 5820 8 GraphicsServices 0x337c4224 PurpleEventCallback + 876 9 CoreFoundation 0x35aa651c __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 32 10 CoreFoundation 0x35aa64be __CFRunLoopDoSource1 + 134 11 CoreFoundation 0x35aa530c __CFRunLoopRun + 1364 12 CoreFoundation 0x35a2849e CFRunLoopRunSpecific + 294 13 CoreFoundation 0x35a28366 CFRunLoopRunInMode + 98 14 GraphicsServices 0x337c3432 GSEventRunModal + 130 15 UIKit 0x33200cce UIApplicationMain + 1074 16 Comprehension 0x000623d4 main (main.m:14) 17 Comprehension 0x00062388 start + 32
-13282983 0 It's just syntactic sugar -- the compiler inserts the backing field for you. The effect is the same, except that, of course, there's no way for you to access the backing field from your code.
From the page you linked to:
-26879738 0 How to get word in php which contains colon(:)?When you declare a property as shown in the following example, the compiler creates a private, anonymous backing field that can only be accessed through the property's get and set accessors.
I have a word Hello How are you :chinu i am :good
i want to get the word which contains :
like :chinu
and :good
My code:
<?php //$string='Hello How are you :chinu i am :good'; //echo strtok($string, ':'); $string='Hello How are you :chinu i am :good'; preg_match('/:([:^]*)/', $string, $matches); print_r($matches); ?>
Above code i am getting Array ( [0] => : [1] => )
But not getting the exact text. Please help me.
Thanks Chinu
-29205058 0 creating dropdown from php arrayI have array like this:
Array ( [0] => Array( [attribute_name] => Brand [attribute_value] => Lee ) [1] => Array( [attribute_name] => Brand [attribute_value] => Levis ) [2] => Array( [attribute_name] => Brand [attribute_value] => Raymond ) [3] => Array( [attribute_name] => Fabric [attribute_value] => Cotton ) [4] => Array( [attribute_name] => Fabric [attribute_value] => Linen ) )
I want to create two drop down from this array one is for Brand
which should have three options and another one is for fabric
which should have two option.
I can do simply by checking attribute_name
is brand
or fabric
, but this is not static there can be anything instead of brand
and fabric
.
I've tried so many things but not worked. Please help me in doing this. Thanks in advance.
-38542167 0I don't care what month/year/day is asigned, i only want the time.
That suggests you should be parsing it as a LocalTime
, given that that's what the string actually represents. You can then add any LocalDate
to it to get a LocalDateTime
, if you really want to pretend you've got more information then you have:
import java.time.*; import java.time.format.*; public class Test { public static void main(String args[]) { DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_TIME; LocalTime time = LocalTime.parse("00:00",formatter); LocalDate date = LocalDate.of(2000, 1, 1); LocalDateTime dateTime = date.atTime(time); System.out.println(dateTime); // 2000-01-01T00:00 } }
If you can avoid creating a LocalDateTime
at all and just work with the LocalTime
, that would be even better.
What was said above is right: You can't prevent an auto-implemented property from being serialized by setting an attribute like [NonSerialized]. It just does not work.
But what does work is the [IgnoreDataMember] attribute in case you are working with an WCF [DataContract]. So
[DataContract] public class MyClass { [DataMember] public string ID { get; set; } [IgnoreDataMember] public string MySecret { get; set; } }
will get serialized under WCF.
Although since WCF is an opt-in technology, you can also just omit the [IgnoreDataMember] and it will work as well. So maybe my comment is a little academical ;-)
-20677391 0 JAVA Filling a 2D array from a file with an unknown amount of rowsI am trying to figure out how to make a program that reads data from a text file, and fills a Jtable
with it, I will need to be able to search the table, and do some calculations with the numbers.
A row in the text file would contain:
name, country, gender, age, weight
The number of rows is unknown (I need to count the number of rows). This is what I tried, but it seems to crash. I need to count the # of rows, and then fill the array with the content from the rows.
package Jone; import java.io.*; import java.util.*; public class Jone { public static void main (String [] args)throws IOException{ int rows = 0; Scanner file = new Scanner (new File("data.txt")); while (file.hasNextLine()){rows++;} Object[][] data = new Object[rows][5]; System.out.print(rows); file.nextLine(); for(int i = 0;i<rows;i++) { String str = file.nextLine(); String[] tokens= str.split(","); for (int j = 0;j<5;j++) { data[i][j] = tokens[j]; System.out.print(data[i][j]); System.out.print(" "); } } file.close(); } }
-31452892 0 How many is too many is really a matter of opinion. However, it's worth being aware how SharedPreferences work in order to get a feel for whether using
SharedPreferences` is the way to go.
As far as I know, there is no hard limit on the size of SharedPreferences
, but SharedPreferences
are stored in an XML file and when you first access the SharedPreferences
the whole file is read and stored in memory so this in itself has an impact on the heap space used by your app and could lead to out of memory errors (partly depending on the size of the data, the available memory and what memory usage the rest of your app requires). Therefore, using SharedPreferences for a large amount of data will often mean you're using more memory than necessary. If you're reading the data from SharedPreferences
into another data structure, you'll then have this data in memory twice. Also, XML isn't very efficient in terms of the space used on the filesystem.
I'm not saying it's wrong to use SharedPreferences
but there's often a tradeoff between using something that might be more memory efficient (e.g SQLite DB) and give you extra functionality (searching, transaction support, etc.), compared to the simplicity of using SharedPreferences.
It also partly depends what you're storing - e.g. whether you're storing boolean values or long strings makes a huge difference in terms of memory usage. What you're doing with the data might make a difference as to which is the right way to go too. Do you need it to be scalable (e.g. you're storing 100 to 150 values now, but could that increase?).
If I were you, I'd consider how big my data is (i.e. amount of memory used not just number of key value pairs)? Might I need to store more in future? Would the extra functionality of SQLite be useful?
My gut feel based on the limited information you've provided is that I'd probably use SQLite, but I'm basing that on assumptions that scalability might be important and you're storing strings of more than a few characters, and even then I'm sure some people will disagree because "How much is too much" is subjective in this case.
-8566124 1 Longest substring (for sequences of triplets)I am trying to compare strings of the format: AAA-ABC-LAP-ASZ-ASK; basically, triplets of letters separated by dashes.
I'm trying to find between 2 such sequences of arbitrary length (from 1 to 30 triplets) the longest sequence of common triplets.
For example, AAA-BBB-CCC-AAA-DDD-EEE-BBB and BBB-AAA-DDD-EEE-BBB, you can find a sequence of 5 (BBB-AAA-DDD-EEE-BBB, even if CCC is not present in the 2nd sequence).
The dashes should not be considered for comparison; they only serve to separate the triplets.
I'm using Python but just a general algorithm to achieve this should do :)
-33095149 0You pass JSON like that. ArrayList does not accept key and value pair. Then add your keys
JSON: [ "1", "2", "3", "4" ] @RequestMapping(method = RequestMethod.POST, value = "/read/ids/",headers="Accept=application/json") public ArrayList<String> test(@RequestBody ArrayList<String> ids) throws Exception { return ids; }
-8338371 0 Error running make when installing Ruby 1.8.7-p302 via RVM on Mac OS 10.5.8 Running "rvm install 1.8.7-p302" provides the following feedback:
rich-macbook:~ rich$ rvm install 1.8.7-p302 Installing Ruby from source to: /Users/rich/.rvm/rubies/ruby-1.8.7-p302, this may take a while depending on your cpu(s)... ruby-1.8.7-p302 - #fetching ruby-1.8.7-p302 - #extracted to /Users/rich/.rvm/src/ruby-1.8.7-p302 (already extracted) Applying patch 'stdout-rouge-fix' (located at /Users/rich/.rvm/patches/ruby/1.8.7/stdout-rouge-fix.patch) ERROR: Error running 'patch -F 25 -p1 -N -f <"/Users/rich/.rvm/patches/ruby/1.8.7/stdout-rouge-fix.patch"', please read /Users/rich/.rvm/log/ruby-1.8.7-p302/patch.apply.stdout-rouge-fix.log ruby-1.8.7-p302 - #configuring ruby-1.8.7-p302 - #compiling ERROR: Error running 'make ', please read /Users/rich/.rvm/log/ruby-1.8.7-p302/make.log ERROR: There has been an error while running make. Halting the installation.
This is the second attempt at installing it; the first time the patch installed fine, but Ruby itself failed running make. I have recently installed Ruby 1.9.3-p0 without problem.
Below is the output of the mentioned log files.
patch.apply.stdout-rouge-fix.log
[2011-12-01 08:06:45] patch -F 25 -p1 -N -f <"/Users/rich/.rvm/patches/ruby/1.8.7/stdout-rouge-fix.patch" patching file lib/mkmf.rb Hunk #1 FAILED at 201. 1 out of 1 hunk FAILED -- saving rejects to file lib/mkmf.rb.rej
make.log:
[2011-12-01 08:07:04] make /usr/bin/gcc-4.2 -arch x86_64 -g -Os -pipe -no-cpp-precomp -fno-common -pipe -fno-common -DRUBY_EXPORT -L. -arch x86_64 -bind_at_load main.o dmydln.o libruby-static.a -ldl -lobjc -o miniruby rbconfig.rb unchanged cc -dynamiclib -undefined suppress -flat_namespace -install_name /Users/rich/.rvm/rubies/ruby-1.8.7-p302/lib/libruby.dylib -current_version 1.8.7 -compatibility_version 1.8 array.o bignum.o class.o compar.o dir.o dln.o enum.o enumerator.o error.o eval.o file.o gc.o hash.o inits.o io.o marshal.o math.o numeric.o object.o pack.o parse.o process.o prec.o random.o range.o re.o regex.o ruby.o signal.o sprintf.o st.o string.o struct.o time.o util.o variable.o version.o dmyext.o -o libruby.1.8.7.dylib ld warning: in array.o, file is not of required architecture ld warning: in bignum.o, file is not of required architecture ld warning: in class.o, file is not of required architecture ld warning: in compar.o, file is not of required architecture ld warning: in dir.o, file is not of required architecture ld warning: in dln.o, file is not of required architecture ld warning: in enum.o, file is not of required architecture ld warning: in enumerator.o, file is not of required architecture ld warning: in error.o, file is not of required architecture ld warning: in eval.o, file is not of required architecture ld warning: in file.o, file is not of required architecture ld warning: in gc.o, file is not of required architecture ld warning: in hash.o, file is not of required architecture ld warning: in inits.o, file is not of required architecture ld warning: in io.o, file is not of required architecture ld warning: in marshal.o, file is not of required architecture ld warning: in math.o, file is not of required architecture ld warning: in numeric.o, file is not of required architecture ld warning: in object.o, file is not of required architecture ld warning: in pack.o, file is not of required architecture ld warning: in parse.o, file is not of required architecture ld warning: in process.o, file is not of required architecture ld warning: in prec.o, file is not of required architecture ld warning: in random.o, file is not of required architecture ld warning: in range.o, file is not of required architecture ld warning: in re.o, file is not of required architecture ld warning: in regex.o, file is not of required architecture ld warning: in ruby.o, file is not of required architecture ld warning: in signal.o, file is not of required architecture ld warning: in sprintf.o, file is not of required architecture ld warning: in st.o, file is not of required architecture ld warning: in string.o, file is not of required architecture ld warning: in struct.o, file is not of required architecture ld warning: in time.o, file is not of required architecture ld warning: in util.o, file is not of required architecture ld warning: in variable.o, file is not of required architecture ld warning: in version.o, file is not of required architecture ld warning: in dmyext.o, file is not of required architecture compiling Win32API compiling bigdecimal cc -arch x86_64 -dynamiclib -undefined suppress -flat_namespace -o ../../.ext/i686-darwin9.8.0/bigdecimal.bundle bigdecimal.o -L. -L../.. -L. -arch x86_64 -bind_at_load -lruby -ldl -lobjc ld warning: in ../../libruby.dylib, file is not of required architecture compiling curses cc -arch x86_64 -dynamiclib -undefined suppress -flat_namespace -o ../../.ext/i686-darwin9.8.0/curses.bundle curses.o -L. -L../.. -L. -arch x86_64 -bind_at_load -lruby -lncurses -ltermcap -ldl -lobjc ld warning: in ../../libruby.dylib, file is not of required architecture compiling dbm cc -arch x86_64 -dynamiclib -undefined suppress -flat_namespace -o ../../.ext/i686-darwin9.8.0/dbm.bundle dbm.o -L. -L../.. -L. -arch x86_64 -bind_at_load -lruby -ldl -lobjc ld warning: in ../../libruby.dylib, file is not of required architecture compiling digest cc -arch x86_64 -dynamiclib -undefined suppress -flat_namespace -o ../../.ext/i686-darwin9.8.0/digest.bundle digest.o -L. -L../.. -L. -arch x86_64 -bind_at_load -lruby -ldl -lobjc ld warning: in ../../libruby.dylib, file is not of required architecture cp ../.././ext/digest/digest.h ../../.ext/i686-darwin9.8.0 compiling digest/bubblebabble cc -arch x86_64 -dynamiclib -undefined suppress -flat_namespace -o ../../../.ext/i686-darwin9.8.0/digest/bubblebabble.bundle bubblebabble.o -L. -L../../.. -L. -arch x86_64 -bind_at_load -lruby -ldl -lobjc ld warning: in ../../../libruby.dylib, file is not of required architecture compiling digest/md5 cc -arch x86_64 -dynamiclib -undefined suppress -flat_namespace -o ../../../.ext/i686-darwin9.8.0/digest/md5.bundle md5init.o md5ossl.o -L. -L../../.. -L. -arch x86_64 -bind_at_load -lruby -lcrypto -ldl -lobjc ld warning: in ../../../libruby.dylib, file is not of required architecture compiling digest/rmd160 cc -arch x86_64 -dynamiclib -undefined suppress -flat_namespace -o ../../../.ext/i686-darwin9.8.0/digest/rmd160.bundle rmd160init.o rmd160ossl.o -L. -L../../.. -L. -arch x86_64 -bind_at_load -lruby -lcrypto -ldl -lobjc ld warning: in ../../../libruby.dylib, file is not of required architecture compiling digest/sha1 cc -arch x86_64 -dynamiclib -undefined suppress -flat_namespace -o ../../../.ext/i686-darwin9.8.0/digest/sha1.bundle sha1init.o sha1ossl.o -L. -L../../.. -L. -arch x86_64 -bind_at_load -lruby -lcrypto -ldl -lobjc ld warning: in ../../../libruby.dylib, file is not of required architecture compiling digest/sha2 cc -arch x86_64 -dynamiclib -undefined suppress -flat_namespace -o ../../../.ext/i686-darwin9.8.0/digest/sha2.bundle sha2.o sha2init.o -L. -L../../.. -L. -arch x86_64 -bind_at_load -lruby -ldl -lobjc ld warning: in ../../../libruby.dylib, file is not of required architecture compiling dl cc -arch x86_64 -dynamiclib -undefined suppress -flat_namespace -o ../../.ext/i686-darwin9.8.0/dl.bundle dl.o handle.o ptr.o sym.o -L. -L../.. -L. -arch x86_64 -bind_at_load -lruby -ldl -ldl -lobjc ld warning: in ../../libruby.dylib, file is not of required architecture cp dlconfig.h ../../.ext/i686-darwin9.8.0 cp ../.././ext/dl/dl.h ../../.ext/i686-darwin9.8.0 compiling etc cc -arch x86_64 -dynamiclib -undefined suppress -flat_namespace -o ../../.ext/i686-darwin9.8.0/etc.bundle etc.o -L. -L../.. -L. -arch x86_64 -bind_at_load -lruby -ldl -lobjc ld warning: in ../../libruby.dylib, file is not of required architecture compiling fcntl cc -arch x86_64 -dynamiclib -undefined suppress -flat_namespace -o ../../.ext/i686-darwin9.8.0/fcntl.bundle fcntl.o -L. -L../.. -L. -arch x86_64 -bind_at_load -lruby -ldl -lobjc ld warning: in ../../libruby.dylib, file is not of required architecture compiling gdbm compiling iconv cc -arch x86_64 -dynamiclib -undefined suppress -flat_namespace -o ../../.ext/i686-darwin9.8.0/iconv.bundle iconv.o -L. -L../.. -L. -arch x86_64 -bind_at_load -lruby -liconv -ldl -lobjc ld warning: in ../../libruby.dylib, file is not of required architecture compiling io/wait cc -arch x86_64 -dynamiclib -undefined suppress -flat_namespace -o ../../../.ext/i686-darwin9.8.0/io/wait.bundle wait.o -L. -L../../.. -L. -arch x86_64 -bind_at_load -lruby -ldl -lobjc ld warning: in ../../../libruby.dylib, file is not of required architecture compiling nkf cc -arch x86_64 -dynamiclib -undefined suppress -flat_namespace -o ../../.ext/i686-darwin9.8.0/nkf.bundle nkf.o -L. -L../.. -L. -arch x86_64 -bind_at_load -lruby -ldl -lobjc ld warning: in ../../libruby.dylib, file is not of required architecture compiling openssl cc -arch x86_64 -dynamiclib -undefined suppress -flat_namespace -o ../../.ext/i686-darwin9.8.0/openssl.bundle openssl_missing.o ossl.o ossl_asn1.o ossl_bio.o ossl_bn.o ossl_cipher.o ossl_config.o ossl_digest.o ossl_engine.o ossl_hmac.o ossl_ns_spki.o ossl_ocsp.o ossl_pkcs12.o ossl_pkcs5.o ossl_pkcs7.o ossl_pkey.o ossl_pkey_dh.o ossl_pkey_dsa.o ossl_pkey_ec.o ossl_pkey_rsa.o ossl_rand.o ossl_ssl.o ossl_ssl_session.o ossl_x509.o ossl_x509attr.o ossl_x509cert.o ossl_x509crl.o ossl_x509ext.o ossl_x509name.o ossl_x509req.o ossl_x509revoked.o ossl_x509store.o -L. -L../.. -L. -arch x86_64 -bind_at_load -lruby -lssl -lcrypto -ldl -lobjc ld warning: in ../../libruby.dylib, file is not of required architecture compiling pty cc -arch x86_64 -dynamiclib -undefined suppress -flat_namespace -o ../../.ext/i686-darwin9.8.0/pty.bundle pty.o -L. -L../.. -L. -arch x86_64 -bind_at_load -lruby -lutil -ldl -lobjc ld warning: in ../../libruby.dylib, file is not of required architecture compiling racc/cparse cc -arch x86_64 -dynamiclib -undefined suppress -flat_namespace -o ../../../.ext/i686-darwin9.8.0/racc/cparse.bundle cparse.o -L. -L../../.. -L. -arch x86_64 -bind_at_load -lruby -ldl -lobjc ld warning: in ../../../libruby.dylib, file is not of required architecture compiling readline cc -arch x86_64 -dynamiclib -undefined suppress -flat_namespace -o ../../.ext/i686-darwin9.8.0/readline.bundle readline.o -L. -L../.. -L. -arch x86_64 -bind_at_load -lruby -lreadline -lncurses -ldl -lobjc ld warning: in ../../libruby.dylib, file is not of required architecture compiling sdbm cc -arch x86_64 -dynamiclib -undefined suppress -flat_namespace -o ../../.ext/i686-darwin9.8.0/sdbm.bundle _sdbm.o init.o -L. -L../.. -L. -arch x86_64 -bind_at_load -lruby -ldl -lobjc ld warning: in ../../libruby.dylib, file is not of required architecture compiling socket cc -arch x86_64 -dynamiclib -undefined suppress -flat_namespace -o ../../.ext/i686-darwin9.8.0/socket.bundle socket.o -L. -L../.. -L. -arch x86_64 -bind_at_load -lruby -ldl -lobjc ld warning: in ../../libruby.dylib, file is not of required architecture compiling stringio cc -arch x86_64 -dynamiclib -undefined suppress -flat_namespace -o ../../.ext/i686-darwin9.8.0/stringio.bundle stringio.o -L. -L../.. -L. -arch x86_64 -bind_at_load -lruby -ldl -lobjc ld warning: in ../../libruby.dylib, file is not of required architecture compiling strscan cc -arch x86_64 -dynamiclib -undefined suppress -flat_namespace -o ../../.ext/i686-darwin9.8.0/strscan.bundle strscan.o -L. -L../.. -L. -arch x86_64 -bind_at_load -lruby -ldl -lobjc ld warning: in ../../libruby.dylib, file is not of required architecture compiling syck cc -arch x86_64 -dynamiclib -undefined suppress -flat_namespace -o ../../.ext/i686-darwin9.8.0/syck.bundle bytecode.o emitter.o gram.o handler.o implicit.o node.o rubyext.o syck.o token.o yaml2byte.o -L. -L../.. -L. -arch x86_64 -bind_at_load -lruby -ldl -lobjc ld warning: in ../../libruby.dylib, file is not of required architecture compiling syslog cc -arch x86_64 -dynamiclib -undefined suppress -flat_namespace -o ../../.ext/i686-darwin9.8.0/syslog.bundle syslog.o -L. -L../.. -L. -arch x86_64 -bind_at_load -lruby -ldl -lobjc ld warning: in ../../libruby.dylib, file is not of required architecture compiling thread cc -arch x86_64 -dynamiclib -undefined suppress -flat_namespace -o ../../.ext/i686-darwin9.8.0/thread.bundle thread.o -L. -L../.. -L. -arch x86_64 -bind_at_load -lruby -ldl -lobjc ld warning: in ../../libruby.dylib, file is not of required architecture compiling tk Warning:: cannot find Tk library. tcltklib will not be compiled (tcltklib is disabled on your Ruby == Ruby/Tk will not work). Please check configure options. compiling tk/tkutil compiling win32ole compiling zlib cc -arch x86_64 -dynamiclib -undefined suppress -flat_namespace -o ../../.ext/i686-darwin9.8.0/zlib.bundle zlib.o -L. -L../.. -L. -arch x86_64 -bind_at_load -lruby -lz -ldl -lobjc ld warning: in ../../libruby.dylib, file is not of required architecture making ruby /usr/bin/gcc-4.2 -arch x86_64 -g -Os -pipe -no-cpp-precomp -fno-common -pipe -fno-common -DRUBY_EXPORT -L. -arch x86_64 -bind_at_load main.o -lruby -ldl -lobjc -o ruby ld warning: in ./libruby.dylib, file is not of required architecture Undefined symbols: "_ruby_options", referenced from: _main in main.o "_ruby_run", referenced from: _main in main.o "_ruby_init", referenced from: _main in main.o "_ruby_init_stack", referenced from: _main in main.o ld: symbol(s) not found collect2: ld returned 1 exit status make[1]: *** [ruby] Error 1 make: *** [all] Error 2
If you need any more info, let me know.
EDIT: I performed the following steps after reading this thread: make error when installing `ruby-1.8.7-p334` with `rvm` on Snow Leopard
This successfully installed the patch, indicating it is installed first time so any subsequent errors can be ignored. It did still error when compiling Ruby. As the make log file exceeds this post's character count capacity, you can view the contents of the second makefile here: http://pastebin.com/MTZjXBdF
-33464867 0 Why can't I access this global variable?I of course tried it with out the $GLOBALS
and still no go. Is my syntax correct. My understanding is that $DB_USER
is in the global scope.
<?php $DB_USER = 'foo'; class Database { // this does not work private $DB_USER = $GLOBALS['DB_USER']; private $DB_PASS = 'foob'; private $DB_DRIVER = 'foob_foob'; // ...
-17084600 0 $(document).ready(function() { $("a").click(function() { alert('............'); }); });
-18149350 0 Remove Activities from Stack In Main
, there are buttons to start A
and X
/--> A --> B / Main \ \--> X
There is a button in B
to take it from B --> X
. If that happens, A
and B
should be removed from the activity stack, so that pressing back
in X
returns to Main
You need to set an action Intent Filter .
Something like this
<intent-filter> <action android:name="android.intent.action.SENDTO" /> <action android:name="android.intent.action.SEND" /> </intent-filter>
Check out this link you will get some Idea
It works like this
Intent intent = new Intent(); intent.setAction(Intent.SEND); startActivity(intent);
It will show you list of all the app which can send sms
-9808491 0 PHP IF Statement how can I write it more elegant and effectiveI now have this code based on some of the answers below.
Is this the most elegant, clean, fast and effective code to have?
<?php /** * The default template for displaying Google Analytics * * @package WordPress * @subpackage News_Template * @since News Template 1.0 */ $googleanalyticscode="<script type='text/javascript'> var _gaq = _gaq || []; _gaq.push(['_setAccount', '%s']); _gaq.push(['_setDomainName', '%s']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script>"; $analyticsurlgoogle=array( 'domain-a.com' => 'UA-25133-2', 'domain-b.com' => 'UA-25133', 'domain-c.com' => 'UA-2699-2', 'domain-d.com' => 'UA-3021-2', 'domain-e.com' => 'UA-25537-2', 'domain-f.com' => 'UA-7213-2', 'domain-g.com' => 'UA-7214-2', 'domain-h.com' => 'UA-150-2', 'domain-i.com' => 'UA-150-2' ); // --- /Configuration --- // Get the Domain URL $analyticsurl = get_site_url(); $namegoogle = substr($analyticsurl,7); //create code if (isset($analyticsurlgoogle[$namegoogle])) $code=sprintf($googleanalyticscode,$analyticsurlgoogle[$namegoogle],$namegoogle); else $code=''; echo $code; ?>
------ Previous Code ------
I have written the following if statement in PHP. What would be the most elegant, effective and cleanest way of writing this code?
The purpose of the code is to check the domain name of the site. If the site have google analytics defined it should match the defined "Google Analytics" code for the domain and then print the script to the page.
If the Google Analytics code is not defined it should show nothing!
<?php // Get the Domain URL $analyticsurl = get_site_url(); // Check if domain is defined if ($analyticsurl == 'http://domain-a.com') {$analyticcode = 'UA-25133920-1'; $analyticsurlname = 'domain-a.com';} // domain-a.com if ($analyticsurl == 'http://domain-b.com') {$analyticcode = 'UA-25133920-1'; $analyticsurlname = 'domain-b.com';} // domain-b.com if ($analyticsurl == 'http://domain-c.com') {$analyticcode = 'UA-26990264-1'; $analyticsurlname = 'domain-c.com';} // domain-c.com if ($analyticsurl == 'http://domain-d.com') {$analyticcode = 'UA-30217571-1'; $analyticsurlname = 'domain-d.com';} // domain-d.com if ($analyticsurl == 'http://domain-e.com') {$analyticcode = 'UA-25537388-1'; $analyticsurlname = 'domain-e.com';} // domain-e.com // if domain is defined create Google Analytics Code and insert variables $analyticscode_1 = "<script type='text/javascript'> var _gaq = _gaq || []; _gaq.push(['_setAccount', '".$analyticcode."']); _gaq.push(['_setDomainName', '".$analyticsurlname."']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script>"; // if URL does not match write nothing if ($analyticcode == '') {$analyticscode = '';} // if URL exists set the Google Analytics Code if ($analyticcode != '') {$analyticscode = $analyticscode_1;} ?> <?php // write the Analytics code to the page echo $analyticscode ?>
-11920400 0 There are powerpoint presentaion slides on the following link:
http://aplcenmp.apl.jhu.edu/~davids/605741/handouts/6_SWT_Programming.pdf
Also you may have a look on pdf given on the following link:
http://www.loria.fr/~dutech/DDZ/SWT.pdf
-12757197 0window.status
would be disabled by default in most recent browsers. Consider the scenario where a malicious website could effectively impersonate a trusted entity:
<script> $('#bad-link').mouseover(function() { window.status = 'www.microsoft.com'; }); </script> <a href="http://www.example.com/something-bad" id="bad-link">Click me</a>
Also remember that a lot of browsers by default don't even display the status bar anymore!
-19255396 0You should be able to access and set the title via the $window
abstraction, thus removing the need to put a controller on the html
tag.
using a PHP cron job, how can I output the users who visited the same page over 2 times ?
Here is the mySQL table
id - user - page - timestamp 340 - 1 - page1 - 2009-05-18 22:11:11 339 - 1 - page1 - 2009-05-18 22:10:01 337 - 1 - page1 - 2009-05-18 22:06:00 336 - 2 - page3 - 2009-05-18 22:00:00 335 - 2 - page3 - 2009-05-18 21:56:00
-29061804 0 You make the same mistake several times. I'll use the first instance an example:
$name = param($name);
You get the value of $name
(which you haven't yet defined) and use it to get a param from the HTTP request. Since it isn't defined, you don't get the result you are looking for, so you don't get the submitted data in $name
.
Presumably you intended:
$name = param('name');
Update now you have the form you are using:
print qq!<br><form method="get" action="serverside.pl">!; print qq!<input type="submit" value="Confirm Booking" />\n</form><br />!;
You don't have any <input>
elements except for the submit button (which doesn't have a name
attribute), so there is no data to submit.
I got exact same problem and solved by using following way,
Launch the iOS Simulator
Go and click "iOS Simulator" Menu
Click "Reset content and settings"
Close simulator and rebuild your app.
Above screen shot is showing the way how you can do this...
I think this works for you...!!!
-6041621 0 UITableView grabbing touch events from subviewsI have a UITableView, which loads UIViews into its cells. These UIViews use the -touchesBegan:withEvent: etc methods, which all work fine & let me implement code to move these subviews around in the table. This all works, until I move my finger vertically & start scrolling the table, then the UIViews stop receiving any touch events. If anyone knows how to get around this I'd be very happy! Many thanks.
-7874928 0One of the alternative ways you can do that (if you actually care much about space) is to store the hash in the binary form. Some details of how to do that may be found here; you'd probably want BINARY(32) for a SHA-256 hash.
-14262719 0 Spring mvc 3.2: NoClassDefFoundError: java/util/DequeOn processing get request to my @Controller method i get
2013-01-10 18:16:44,871 INFO [STDOUT] 2013-01-10 18:16:44 [http-0.0.0.0-8080-53] DEBUG org.springframework.web.servlet.DispatcherServlet.processRequest - Could not complete request org.springframework.web.util.NestedServletException: Handler processing failed; nested exception is java.lang.NoClassDefFoundError: java/util/Deque at org.springframework.web.servlet.DispatcherServlet.triggerAfterCompletionWithError(DispatcherServlet.java:1259) ~[spring-webmvc-3.2.0.RELEASE.jar:3.2.0.RELEASE] at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945) ~[spring-webmvc-3.2.0.RELEASE.jar:3.2.0.RELEASE] at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856) ~[spring-webmvc-3.2.0.RELEASE.jar:3.2.0.RELEASE] at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:915) [spring-webmvc-3.2.0.RELEASE.jar:3.2.0.RELEASE] at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:811) [spring-webmvc-3.2.0.RELEASE.jar:3.2.0.RELEASE] at javax.servlet.http.HttpServlet.service(HttpServlet.java:734) [javaee.jar:9.1] at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:796) [spring-webmvc-3.2.0.RELEASE.jar:3.2.0.RELEASE] at javax.servlet.http.HttpServlet.service(HttpServlet.java:847) [javaee.jar:9.1] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.5.0_25] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) ~[na:1.5.0_25]
I use spring 3.2, java 5, jboss 4.2
EDIT Problem was in thymeleaf and not in spring
-24266644 0Use Rectangle class. There's a method called Intersect or Intersection or something like that.
Say you have one object moving. Make a Rectangle to match the object in position(basically an invisible cover for the object).
Do the same things with another object.
When both are to collide, use the intersection method to check on the collision by using the rectangles.
These might help
http://docs.oracle.com/javase/7/docs/api/java/awt/Rectangle.html
Java method to find the rectangle that is the intersection of two rectangles using only left bottom point, width and height?
java.awt.Rectangle. intersection()
I want calculating client bandwidth in asp.net mvc and already I used JavaScript
<script language="javascript" type="text/javascript"> time = new Date(); time1 = time.getTime(); </script> <!-- Dummy Text to measure transfer speed --> <script language="javascript" type="text/javascript"> time = new Date(); time2 = time.getTime(); ttime = time2 - time1; if (ttime == 0) ttime = .1; ttime = ttime / 1000; //thousand mili seconds kbps = 45 / ttime; kbps = kbps * 8; // multiply by 8 to make kiloBITS instead of kiloBYTES kbps = Math.round (kbps); document.getElementById("lblBandwidth").innerHTML=kbps + " kbps"; </script>
you can see this on http://www.whoismaster.ir/Home/BandwidthMeter but this is not accurate
how can used accurate code for this? I like used asp.net mvc with c# for exactly bandwidth
-27031291 0 Making table rows generated via JQuery act as onClick page redirectsSo I am pretty new to JQuery/HTML development of all kinds. Basically I am working on a project where I make an AJAX call that gets a bunch of usernames, dates, etc. regarding Craiglist-like sales that I put into a table format dynamically using JQuery and DOM.
I want to be able to make these elements in the table act as links so that if I click on a certain username, it will take me to their profile. I've tried different suggestions out there but none of them are for tables that are generated with JQuery and I think this is causing problems (but I don't think there is any way around that either). Some snippets of my code are as follows:
function displayCurrentSales(description, seller, date) { var sale = document.createElement("p"); var table = document.getElementById("currentSalesTable"); var row = table.insertRow(-1); var descriptionRow = row.insertCell(0); var userRow = row.insertCell(1); var dateRow = row.insertCell(2); descriptionRow.innerHTML = description; userRow.innerHTML = seller; userRow.onClick = "window.location.href = '../profilePage/index.html?username=' + seller;"; dateRow.innerHTML = date; }
This is my code that I started with except for the userRow.onClick part which I added to try and make it work.
Any help is appreciated, Thanks.
-1353675 0 Standard Property Dialog/Browser for ActiveX - ControlI am looking for a property browser/editor for generic activeX controls.
It must work for controls that just expose an IDispatch interface, no proeprty pages of their own.
Best would be something that comes with the OS (like the "All properties" property page VC6 used). It is only for testing, so comfort is not important, modal property sheet or embedded activeX control. The test application is an MFC project.
I thought there was something like that, but the best I can find right now is OleCreatePropertyFrame
(which is only the dialog, but not the page i'm after)
Thanks!
-12882926 0If you are trying to do the opposite, (provide a single value and find all the rows where the min and max age values bracket the provided value), then try
Select * From table Where @myValue Between min_age And max_age
-7723292 0 In my experience it is not a good practice. assign the null where it needs
-24607245 0 Can we use Asp.Net Membership and Role Provider in MVC 5I'm converting a MVC 3 application to MVC 5. I've been reading on web that MVC 5 comes with Asp.Net Identity for security. My question is that is possible, feasible and good to use old membership and role provider in MVC 5 application. Can anyone give any useful link where I can learn conversion from membership and role provider to Identity.
-34031041 0 VB Downscaling coordinatesI have the need to know when a gdi+ drawn line is clicked on by the mouse.
I have fashioned this function which is used in a loop on all the existing lines and what the function does is:
This works great, there's no misinterpretations, but I'm afraid that there's a tiny delay (not really noticeable) when my form is in full screen (due to the large buffer).
I'm looking for a way to optimize this, and my first thought is to downscale everything. So what I mean by that is make the buffer like 20x20 and then draw the line in a scaled down version using math. Problem is, I suck at math, so I'm basically asking you how to do this and preferably with an explanation for dummies.
This is the function:
Public Function Contains(ByVal e As Point) As Boolean Dim Width As Integer = Container.Size.Width Dim Height As Integer = Container.Size.Height Dim Buffer As Bitmap = New Bitmap(Width, Height) Using G As Graphics = Graphics.FromImage(Buffer) G.Clear(Color.Black) Dim Start As Point = New Point(ParentNode.Location.X + ParentNode.Size.Width / 2, ParentNode.Location.Y + ParentNode.Size.Height / 2) Dim [End] As Point = New Point(ChildNode.Location.X + ChildNode.Size.Width / 2, ChildNode.Location.Y + ChildNode.Size.Height / 2) Dim Control1 As Point Dim Control2 As Point Control1.X = Start.X + GetAngle(ChildNode.Location, ParentNode.Location, ChildNode.Location.X - ParentNode.Location.X, ChildNode.Location.Y - ParentNode.Location.Y) Control1.Y = Start.Y Control2.X = [End].X Control2.Y = Start.Y G.DrawBezier(New Pen(Color.Green, 4), Start, Control1, Control2, [End]) End Using If Buffer.GetPixel(e.X, e.Y).ToArgb() <> Color.Black.ToArgb() Then Return True End If Return False End Function
This is one of my attempts to make the function use the idea above:
Public Function Contains(ByVal e As Point) As Boolean Dim Width As Integer = 20 Dim Height As Integer = 20 Dim Buffer As Bitmap = New Bitmap(Width, Height) Using G As Graphics = Graphics.FromImage(Buffer) G.Clear(Color.Black) Dim Start As Point = New Point(ParentNode.Location.X + ParentNode.Size.Width / 2, ParentNode.Location.Y + ParentNode.Size.Height / 2) Dim [End] As Point = New Point(ChildNode.Location.X + ChildNode.Size.Width / 2, ChildNode.Location.Y + ChildNode.Size.Height / 2) Dim Control1 As Point Dim Control2 As Point Control1.X = Start.X + GetAngle(ChildNode.Location, ParentNode.Location, ChildNode.Location.X - ParentNode.Location.X, ChildNode.Location.Y - ParentNode.Location.Y) Control1.Y = Start.Y Control2.X = [End].X Control2.Y = Start.Y G.DrawBezier(New Pen(Color.Green, 4), New Point(Start.X / Width, Start.Y / Height), New Point(Control1.X / Width, Control1.Height / Height), New Point(Control2.X / Width, Control2.Y / Height), New Point([End].X / Width, [End].Y / Height)) End Using If Buffer.GetPixel(Width, Height).ToArgb() <> Color.Black.ToArgb() Then Return True End If Return False End Function
-3603240 0 i didn't completely understood what you are trying to do... but i think that you want to do is to list all the entities including the date of their last modification.. if that's it, you could use a GROUP BY, and a MAX() function like this
SELECT e.title,e.body,MAX(r.revised) FROM `entities` e JOIN `revisions` r ON r.entity_fk = e.id GROUP BY e.title,e.body
BTW.. i'd change the name of "entity_fk" to "entity_id", its kinda confusing.. at least for me =)
-25438246 0Because of CSS Specificity and because your iPad media query is actually always going to be true (since the screen width on mobiles is always less than 768px). So it will override the rules/selectors you have in your other stylesheets.
You can try reordering you stylesheets the other way around (ie iPad lists first), but i would recommend you specify more explicit media queries to achieve what you want. Have a look at adding a min-device-width
clause to your querys.
You can see an advanced example here: http://css-tricks.com/snippets/css/media-queries-for-standard-devices/
-4203830 0 jQuery accessing form arrayI have a php form and I want to display or hide certain fields dependant on what I select in a drop down. I have code below which works:
$(document).ready(function() { $('div.pupname').hide(); $('div.pupnid').hide(); if ($("#perpetrator").val == "1") { $('div.pupname').hide(); $('div.pupid').show(); else { $('div.pupid').hide(); $('div.pupname').show(); } $("#perpetrator").change(function() { if ($("#perpetrator").val() == "1") { $('div.pupname').hide(); $('div.pupid').show(); else { $('div.pupid').hide(); $('div.pupname').show(); } }); });
I now want to have a multi row block which I am generating using php so I can generate the divs as pupid1, pupid2 etc. and the field $m_perpetrator
as an array. I've tried a few ways of accessing the array but can't get anything to work. I thought he following might be along the correct lines for accessing the elements of the array but it does nothing.
if ($("#m_perpetrator[1]").val == "1") { $('div.pupname1').show(); $('div.pupid1').hide(); } else { $('div.pupid1').show(); $('div.pupname1').hide(); }
Added
Here is a snippet of the HTML
<td><select name="m_perpetrator[1]" id="m_perpetrator[1]"> <option value="1">Current</option> <option value="2" selected>Former</option> <option value="3">Parent/Carer</option> </select> </td> <td>Name</td> <td> <div class="pupname1"> <input type="text" size=60 name="m_pupil_name[1]" value="JOHN SMITH"> </div> <div class="pupid1"> <select name="m_pupil_id[1]" onchange="getXtras(this)"> <option value="">Select .....</option>
So basically this is a multi row form and on each row if Current is selected then I want to display pupil_id if anything else is selected then I want to display pupil name. For processing the input I run round the array m_perpetrator[] using php Jim
-15831253 0Well, your original code made no sense to begin with as half of the declared variables weren't even being used. Furthermore, it is beyond me why you'd want to convert front-end code into server-side code like this, php
is not the right way to do this!
if(boothsizerGlobal == 3){ $cellWidth = '112px'; $cellHeight = '52px'; $innerDivElectricTop = '41px'; $innerDivElectricLeft = '110px'; $backgroundImage = 'url(booth_top_images/5X20TOP.jpg)'; $divCode = '<div style="width: ' . $cellWidth . '; height: ' . $cellHeight . '; "'; return $divCode }
-37977011 0 Can I create a view that needs to calculate its variables using multiple variables from multiple tables? So I am trying to learn how to work with databases and php but I have run into some trouble concerning whether I can make a view for what i need or if i would just need to get all the variables into a php function and calculate it there.
Here is the database structure i have decided for the project. (The premise is setup a database and webpage for a truck rental company if it helps.)
Vehicles(vehicleId, size, gas) Price(size, price) Customer(customerId, firstname, lastname, streetaddress, city, state, zipcode, email, company) Rental(rentId, customerId, vehicleId, startdate, enddate, tank(0=full positive=number of gallons missing from tank), damage(0=none))
So the view in this example i am trying to create would calculate the total cost for each rental for easy display
total cost is price of specific vehicle size * number of days rented (if returned on same day is 1) + (tank * 5) + damage
The view would also contain the rentalId, and customerId to make it simple to search for total amount spent.
can i do this in mysql or would it need to be done in php?
-29585081 0 UITextField action - change SKLabelNodeI am using Objective-C to make an iOS SpriteKit "GameScene" file. I have an SKLabelNode and a UITextField to input a player's name.
How can I make whatever the UITextField value equals to change the SKLabelNode to say "Thanks," + UITextField value?
(my code) :
#import "GameScene.h" @implementation GameScene -(void)didMoveToView:(SKView *)view { // Use Objective-C to declare all SpriteKit Objects // inside the {parameters} of "didMoveToView" method: // SKLabelNodes (SpriteKit Object) display "text". // Objective-C object named *winner = SKLabelNode (SpriteKit Object) SKLabelNode *winner = [SKLabelNode labelNodeWithFontNamed:@"Tahoma"]; winner.text = @"You Win!"; winner.fontSize = 65; winner.fontColor = [SKColor blueColor]; winner.position = CGPointMake(500,500); [self addChild:winner]; // UITextFields (SpriteKit Object) allow "text" input from users. // Objective-C object named *textField = UITextField (SpriteKit Object) UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(self.size.width/2, self.size.height/2+20, 200, 40)]; textField.center = self.view.center; textField.borderStyle = UITextBorderStyleRoundedRect; textField.textColor = [UIColor blackColor]; textField.font = [UIFont systemFontOfSize:17.0]; textField.placeholder = @"Enter your name here"; textField.backgroundColor = [UIColor whiteColor]; textField.autocorrectionType = UITextAutocorrectionTypeYes; textField.keyboardType = UIKeyboardTypeDefault; textField.clearButtonMode = UITextFieldViewModeWhileEditing; [self.view addSubview:textField]; } -(void)update:(CFTimeInterval)currentTime { /* Called before each frame is rendered */ } @end
-32474386 0 How to calculate numbers with dot thousand separator in javascript I've converted numbers using php number format as follows:
number_format($X, 2, ',', '.');
which converts
5000000
into
5.000.000,00
which is exactly what I wanted.
But now my javascript function which is doing some basic math on those numbers are giving wrong result, for example:
5.000.000,00 - 3.500.000,00 = 1.5 instead of 1.500.000,00
So how do you properly calculate those numbers in javascript?
I really appreciate any help i can get :D
Thanks y'all
-25514887 0Expanding parameter packs into varargs is valid.
And there is no harm in forwarding when you want to forward. But taking by const&
also communicates something useful.
The values passed to ...
will experience "default argument promotions". See http://en.cppreference.com/w/cpp/language/variadic_arguments
None of these care about references.
You can improve your code. You can check that the Ts...
are valid types to pass to the printing routine, both by "kind of type" and by actually parsing the formatting string and confirming number (and sometimes type) of arguments. If this fails, you can log an error message instead of crashing.
I'm new to java, so please bare with me...
I'm writing some JAVA assignment I got in school for a few days now, and I ran into something quite weird (well, at least for me it is...).
Since the question has nothing to do with my project in particular, I wrote some code that presents the behaviour I wanted to ask about, so please ignore any problems you might encounter in the following code, that don't relate to this specific issue.
Consider the following class:
package test; import java.util.ArrayList; import java.util.List; public class Car { List<Doors> doors; int numOfDoors; public Car(int numOfDoors) { this.numOfDoors=numOfDoors; } public void prepare() { run(doors); } public void run(List<Doors> listOfDoors) { listOfDoors=new ArrayList<Doors>(numOfDoors); } public List<Doors> getDoors() { return doors; } }
And this:
package test; import java.util.List; public class TestDrive { public static void main(String[] args) { Car car=new Car(5); car.prepare(); List<Doors> listOfDoors=car.getDoors(); if (listOfDoors==null) { System.out.println("This is not the desired behaviour."); } else { System.out.println("This is the desired behaviour."); } } }
I agree, it's kinda stupid and has no point, but again - I wrote it only to satisfy my curiosity.
Now, as you might have guessed, the output is "This is not the desired behaviour.", meaning, the field "doors" holds a null pointer, even though it was assigned with a new object in "run()" method. so my question is why? why is it null?
I mean, I know that creating a local variable - may it be a primitive, an object or a reference to an object - will result in loosing it right when we leave the method's scope, but that is not exactly the case here, since there IS a live reference to that newly created object (doors), then why would JAVA destroy it?
Thanks for anyone who made it through and read the whole post.
hi i live in the philippines and im having a problem using paypal do direct payment using different currency code when i tried my code using USD it works fine but when i changed the currency to PHP for philippines peso it gives an error of 10755 Unsupported Currency. im only using sandbox account.
my question is on what factors can i get an error of unsupported currency code? is it by the type of credit card the user have? is it by where us the merchant registered? or the biling info and country code the user supply?
-32867101 0When monitoring for beacons transmitting Eddystone-UID, regions should be set up like this:
Identifier eddystoneNamespaceId1 = Identifier.parse("0x00000000000000000001"); Identifier eddystoneNamespaceId2 = Identifier.parse("0x00000000000000000002"); Region eddystoneUidRegion1 = new Region("eddystoneUidRegion1", eddystoneNamespaceId1, null, null); Region eddystoneUidRegion2 = new Region("eddystoneUidRegion1", eddystoneNamespaceId2, null, null); beaconManager.setRangeNotifier(this); beaconManager.startMonitoringBeaconsInRegion(eddystoneUidRegion1); beaconManager.startMonitoringBeaconsInRegion(eddystoneUidRegion2);
In this example, two different regions are defined, each with a 10-byte different Eddystone-UID namespace identifier, and a null Eddystone-UID instance identifier so it will match all beacons with those namespace. The last parameter passed to the Region
constructor is also null, because Eddystone-UID beacons only have two identifiers. The code starts monitoring for each of these regions in the last two lines.
The first time any beacon matching the first region is detected (e.g. one with the first namespace identifier), the didEnterRegion
callback will be fired, passing a reference to the eddystoneUidRegion1 object. The equivalent callback will also happen if any beacon matching the second region is detected. You can tell which one is detected by examining the contents of the Region
object passed to the callback. A different callback exists for didExitRegion
when all beacons matching a monitored region disappear.
This is how the Monitoring APIs work. There are also Ranging APIs that give you a callback at approximately 1Hz with a list of all visible beacons that match the Region
. Whether you use the Monitoring APIs or Ranging APIs depends on your use case.
I just found out. It's because size of placeholder image didn't match original image.
My solution was simply remove placeholder or resize your placeholder
-18735798 0 How to wait in Objective-C, maybe better in blocks?I know of:
performSelector:afterDelay:
and these, but I always have to make an extra method for every delay. In Cocos2d-iphone
I use a CCAction
for that CCTimeDelay
, within a CCSequence
. Would be cool if it would also work outside of Cocos2d
.
If I want to wait, lets say 1.3 seconds and don't want to split the method in half because of that, what should I do?
I know when I want to wait and don't change the context, the thread will do nothing. So the performSelector methods are good for that.
How to make it happen, that not the whole app waits, userInput should be accepted while waiting. Let's say I want to create an animation of two steps, in between there should be an time interval of 0.8 seconds. To keep it in one method but use multithreading I use blocks then (any other idea appreciated). How to wait inside the block, so the main thread won't get disturbed?
-19128066 0Thanks to Steve Howard, The problem can be solved by changing SHELL to /bin/bash
-13385693 0 MySQL Select WHERE and removing charactersI have a PHP string that I need to match to a database but in order to match, I first need to make the WHERE part of the statement ignore some characters. For example:
$string = "This is the message. On a few different sentences to make it a bit longer";
Needs to match to
> This is the message. > > On a few different sentences to make it a bit longer
So what I need the WHERE to do is ignore '>','\r\n' and empty lines. I understand I can ignore the first 2 with something like
SELECT * FROM table WHERE REPLACE(REPLACE(fieldtomatch, '>', ''), '\r\n', '') LIKE '%$string%'
But what about the empty lines?
Any help much appreciated!
-15151313 0Instead of [self dismissModalViewControllerAnimated:YES];
use [picker dismissModalViewControllerAnimated:YES];
Okay, so I've figured it out; I made a full MouthConverter : IMultiValueConverter and created the PathGeometry inside the converter, then returned it, link to XAML and C# MultiBind here
-38650734 0 Failure: build failed with an exception a proble m occured configuring root project 'android'I m building a hybrid app using ionic framework. I did installed npm,cordova, ionic and android sdk. also I have set the environment variables. I was able to run following commands
but when I run ionic build android The build fails.
BUILD FAILED
Total time: 29.551 secs FAILURE: Build failed with an exception.
What went wrong: A problem occurred configuring root project 'android'.
java.lang.NullPointerException (no error message)
Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Error: cmd: Command failed with exit code 1 Error output: FAILURE: Build failed with an exception.
What went wrong: A problem occurred configuring root project 'android'.
java.lang.NullPointerException (no error message)
Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
You use JSON Views
class Views { static class PublicView { } static class StreamA extends PublicView { } static class OtherWay extends PublicView { } } public class Value { @JsonView(Views.PublicView.class) public int value; @JsonView(Views.OtherWay.class) public int value2; @JsonView(Views.StreamA.class) public int value3; } String json = new ObjectMapper() .writerWithView(Views.OtherWay.class) .writeValueAsString(valueInstance);
Note that these are inclusive rather than exclusive; you create a view that includes the fields you want.
-33149105 0 How to Change the Style on AvalonEdit CodeCompletion Window?I'm trying to figure out how to change the style of the AvalonEdit CodeCompletion window. However, I can't figure out the right combination of xaml style target/properties to change it. The main thing I'd like to do is get rid of the border, but maybe some additional changes as well.
Here is the xaml I've tried. None of it is affecting the UI.
xmlns:ae="clr-namespace:ICSharpCode.AvalonEdit.CodeCompletion;assembly=ICSharpCode.AvalonEdit" <Style TargetType="{x:Type ae:CompletionWindow}"> <Setter Property="WindowStyle" Value="None" /> </Style> <Style TargetType="{x:Type ae:CompletionWindowBase}"> <Setter Property="WindowStyle" Value="None" /> </Style> <Style TargetType="{x:Type ae:CompletionListBox}"> <Setter Property="Background" Value="Red" /> </Style> <Style TargetType="{x:Type ae:CompletionList}"> <Setter Property="Background" Value="Orange" /> </Style>
-1545081 0 Credit: To Mark. Thanks!
Problem: Display a Progress Indicator when your application is busy doing some work
Approach:
public class Approach extends ListActivity { ProgressDialog myProgressDialog = null; ListView myList = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); myList = getListView(); myProgressDialog = ProgressDialog.show(getParent(), "Please wait...", "Doing extreme calculations...", true); //Do some calculations myProgressDialog.dismiss(); } }
There are a few challenges (like updating some UI elements). You might want to spawn a different thread to do your calculations if needed.
Also, if you are interested in this, you might be interested in Matt's approach too: android-showing-indeterminate-progress-bar-in-tabhost-activity
-21716317 0its simple in Xcode5
select project file from project navigator on the left side
then look at the right side utilities navigator, select file navigator
now 2nd group should be "project document"
HTH
-33484483 0 Slim URLFor in version 3In Slim v2
, i was able to retrieve the routing for an given get, post, ... requests. I since tinkered with Slim v3
, can't figure out to recreate the same logic and the documentation is fairly sparse at the moment.
$app->get('/login/', function ($request, $response, $args) use($app) { })->setName('getLogin'); $app->urlFor('getLogin');
Which will complain, due to the urlFor
method is missing, so how do i recreate this code in Slim v3
? With the error
-31593094 0"Referenced method is not found in subject class".
Try defining a
like this:
char a[10];
Currently you are passing an uninitialized pointer to snprintf, so you get undefined behavior when snprintf writes to it.
-7065705 0 Graphics on Android: path with smooth curves?I want to draw a chart for a function y=x^2 as follows:
but the curve is not smooth as it is a set of connected lines.
how can I make the curve smoother ?
thanks
-32791834 0 Cant get addClass and removeClass to work properly, creating the "15 game"I'm trying to code "the 15 game" using jquery in html, See this page. The game is about to get a table of "boxes" in order from 1-15.
My code:
// Insert numbers from 1 to arraysize function insertElements(myArr, arraysize){ for (var i = 1; i < arraysize; i++ ) { myArr.push(i); } } // Check if the two cells is in range function canMove(col, row, empty_row, empty_col){ if((row == empty_row+1) && (col == empty_col) || (row == empty_row-1) && (col == empty_col) || (row == empty_row) && (col == empty_col+1) || (row == empty_row) && (col == empty_col-1)){ return true; } else return false; } // Swap elements in array function swapElements(myArr, indexA, indexB){ // Check bounds if((indexA > myArr.length) || (indexA < 0) || (indexB > myArr.length) || (indexB < 0)) { alert("Out of bounds"); } else{ var temp = myArr[indexA]; myArr[indexA] = myArr[indexB]; myArr[indexB] = temp; } } // Wait for the page to finish loading $(document).ready(function(){ // Create array var myArr = []; var arraysize = 17; var lastelement = arraysize-1; var empty_row; var empty_col; var empty_cell; var col; var row; var nonempty_cell; // Insert the elements insertElements(myArr, arraysize); // Number of shuffles var shuffleNum = 10000; // Shuffle the array for (var i = 0; i < shuffleNum; i++ ) { var f = Math.floor((Math.random()*16)+0); var s = Math.floor((Math.random()*16)+0); swapElements(myArr, f, s); } //printarray(myArr, myArr.length); i = 0; // For each td in the table $(".maincontainer td").each(function() { // Get the radnom value from the array val = myArr[i]; // If the value is the last element // assign this cell to emptycell and add the class empty if(val == lastelement) { empty_cell = $(this); empty_cell.addClass("empty"); empty_row = this.parentNode.rowIndex; empty_col = this.cellIndex; } // Else, assign the value val to its text and add the class nonempty to it else { $(this).text(val); $(this).addClass("nonempty"); } ++i; }); // If one of the nonempty boxes is clicked $(".nonempty").click(function(){ // assign the cell that has been clicked to nonempty cell nonempty_cell = $(this); row = this.parentNode.rowIndex; col = this.cellIndex; // If the cell is in range of the empty cell if(canMove(col, row, empty_row, empty_col)){ // Swap empty cell and the non emptycell clicked var temp = empty_cell; empty_cell = nonempty_cell; nonempty_cell = temp; // Swap coordinates var temprow = row; row = empty_row; empty_row = temprow; var tempcol = col; col = empty_col; empty_col = tempcol; // Get text from the old empty cell var new_value = $(empty_cell).text(); // Assign the value to the nonempty cell text and change class to nonempty $(nonempty_cell).text(new_value); $(nonempty_cell).removeClass("empty").addClass("nonempty"); // "Erase" the textstring and change class to empty $(empty_cell).removeClass("nonempty").addClass("empty"); $(empty_cell).text(""); } else { alert("Cant move!"); } }); $(".empty").click(function(){ alert("Clicked empty cell!"); }); });
<!DOCTYPE html> <html lang='sv'> <head> <meta charset="UTF-8" > <title>The 15 game</title> <style> .maincontainer { width: 35%; border: 10px solid black; } .maincontainer td { width: 100px; height: 100px; text-align: center; font-size: 100px; border: 3px solid black; } .nonempty { background-color: red; } .empty { background-color: #C0C0C0; } .nonempty:hover { border: 3px solid white; } </style> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <!-- External javascript with the game --> <script type="text/javascript" src="javascript/15game.js"></script> </head> <body> <!-- Table which is the maincontainer of the 16 boxes --> <table class="maincontainer" > <tr> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> </tr> </table> </body> </html>
The code is kind of working correctly. When I click on a cell that is in range of the empty cell, the two cells are being swapped. The only problem is that the cell that first is assigned the class "empty" seems to keep the class "empty" when I try to replace its class to the class "nonempty".
I'm sorry for any typos, english is not my first language. Thanks for any help!
-5362007 0 Admin Page WorriesI will be very direct with my question. I have been developing web applications for a while, but one thing I haven't been able to overcome is this; Where is the most appropriate location to have an admin page. For instance, How are company like Facebook, Google, Yahoo, BOA, etc doing it? am sick and tired of
http://weblink/admin, or http://weblink/administration
Thanks in advance
-33514581 0I also had this same issue before, So you need to create a pipeline in your settings.py to update facebook user data. This code will help you to get facebook user data; http://django-social-auth.readthedocs.org/en/latest/pipeline.html
def update_user_social_data(request, *args, **kwargs): user = kwargs['user'] if not kwargs['is_new']: return user = kwargs['user'] if kwargs['backend'].__class__.__name__ == 'FacebookBackend': fbuid = kwargs['response']['id'] access_token = kwargs['response']['access_token'] url = 'https://graph.facebook.com/{0}/' \ '?fields=email,gender,name' \ '&access_token={1}'.format(fbuid, access_token,) photo_url = "http://graph.facebook.com/%s/picture?type=large" \ % kwargs['response']['id'] request = urllib2.Request(url) response = urllib2.urlopen(request).read() email = json.loads(response).get('email') name = json.loads(response).get('name') gender = json.loads(response).get('gender')
-37293194 0 Sending email using Gradle I have written a task (actually copied from Internet), it sends email to given email. But when I run it, I get java.lang.ClassNotFoundException: javax.mail.internet.MimeMessage
exception. I have included compile group: 'javax.mail', name: 'javax.mail-api', version: '1.5.1'
in dependencies but still getting this. Here is the task
apply plugin: 'com.android.application' class MailSender extends DefaultTask { @TaskAction def sendMail(){ def mailParams = [ mailhost: "smtp.gmail.com", mailport:"465", subject: "Email Recieved", messagemimetype: "text/plain", user: "mallaudinqazi@gmail.com", password:"", enableStartTLS:"true", ssl:"true" ] ant.mail (mailParams) { from (address:'allaudinqazi@gmail.com') to (address:'allaudinqazi@gmail.com') } } } android { compileSdkVersion 23 buildToolsVersion '23.0.1' defaultConfig { applicationId "uk.org.sportscotland.app" minSdkVersion 16 targetSdkVersion 21 versionCode 3 versionName "1.1.1" } dexOptions { javaMaxHeapSize "2g" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:23.2.0' compile files('libs/org.apache.http.legacy.jar') compile fileTree(dir: 'libs', include: 'Parse-1.7.0.jar') compile 'com.koushikdutta.ion:ion:2.+' compile group: 'javax.mail', name: 'javax.mail-api', version: '1.5.1' } ext { fileName = "SSV01" } task copyToDropbox(type: Copy){ from "build/outputs/apk/app-debug.apk" into "F:/Codenterprise Dropbox/Dropbox/Builds/SS" rename { fileName + ".apk" } } task mail(type: MailSender){}
-27123106 0 considered two tables hist and fund. And required query will be:
select * from fund f, hist h where f.FUND_ID=h.FUND_ID and f.fund_id is not null and f.FUND_ID not in (select nvl(REPLACEMENT_FUND_ID,'0') from fund) and h.OLD_STATUS is null and h.NEW_STATUS='I';
-5244983 0 is it possiable apply stylename to I have RichEditableText component , In this component I have created hyper link label based on condition ,but no need inline style(color font-family) . I want to apply style name(CSS) . is it possible can apply style name for hyper link? Give some idea
<s:RichEditableText editable="false" selectable="false" mouseEnabled="{user.isSubscribed}" mouseChildren="{user.isSubscribed}"> <s:content> <s:a click="linkelement1_clickHandler(event)" > <s:span styleName="bodyLinkContent10" >{user.isSubscribed ? "Contact Participant" : "Unavailable"}</s:span></s:a> </s:content> </s:RichEditableText>
style Name Does not apply ? Could you tell me reason for that ?
I tried
<s:RichEditableText editable="false" selectable="false" styleName="{user.isSubscribed ? 'bodyLinkContent10':'bodyContentGrey10'" mouseEnabled="{user.isSubscribed}" mouseChildren="{user.isSubscribed}"> <s:content> <s:a click="linkelement1_clickHandler(event)" fontSize="10"><s:span textDecoration="none" color="{user.isSubscribed ? 0x003399 : 0x666666}">{user.isSubscribed ? "Contact Participant" : "Unavailable"}</s:span></s:a> </s:content> </s:RichEditableText>
It is working fine But requirement is apply the CSS only.So any way for apply ?
-12392797 0We use iText to generate PDF output from our Java applications.
http://www.ibm.com/developerworks/opensource/library/os-javapdf/
-6235707 0You don't need to remove newlines from register or press more then one J
: with the following mapping it will be "apgVJ
:
nnoremap <expr> gV "`[".getregtype(v:register)[0]."`]"
This mapping makes you able to select pasted text just after it was pasted. J
on selected region joins all lines in region (unless region has only one line: here J
acts like J
without a selection, joining current line with next). gV
tip can also be used to do substitution: "apgV:s/{pattern}/{replacement}<CR>
is more convenient then using "ap:let @a=substitute(@a, '{pattern}', '{replacement}', '{flags}')
unless you define some smart mapping.
Another tip is that register a
can be cleared using qaq
normal mode sequence: qa
starts recording a new macro and q
immediately stops it leaving empty string in a
register where macro is recorded to.
You need to loop through all the deleted records using a cursor. Here is an example of a trigger that does this :
CREATE trigger TR_AspNetUsers_AD on dbo.AspNetUsers for delete as begin -- always do this in triggers set nocount on --trigger specific variables declare @AspNetUsersID int declare crDeleted_AspNetUsers Cursor local fast_forward for select d.AspNetUsersID from deleted d --if there was one or more deletes... open crDeleted_AspNetUsers fetch next from crDeleted_AspNetUsers into @AspNetUsersID while @@FETCH_STATUS = 0 begin --do here whatever you need when deletes have occured... fetch next from crDeleted_AspNetUsers into @AspNetUsersID end close crDeleted_AspNetUsers deallocate crDeleted_AspNetUsers end;
All you need to do is adapt it to your needs.
-25938330 0 R: fixed x axis scaling and converting plot() xy arguments to points()I have a data.frame xy
which I am plotting like in the code below.
Is there a way how I could convert my xx
and yy
in the xy plot() to a points()
command so that I could set type='n'
and add points()
after the segments commands in order to control it better?
xy <- data.frame(NAME=c("NAME1","NAME1","NAME1","NAME2","NAME2","NAME2"),ID=c(87,87,87,199,199,199), X_START_YEAR=c(1984,1986,1984,1899,1909,1924),Y_START_VALUE=c(75,25,-90,-8,-55,-10),X_END_YEAR=c(1986,1994,1999,1909,1924,1927), Y_END_VALUE=c(20,50,-15,-70,-80,-100)) xy NAME ID X_START_YEAR Y_START_VALUE X_END_YEAR Y_END_VALUE 1 NAME1 87 1984 75 1986 20 2 NAME1 87 1986 25 1994 50 3 NAME1 87 1984 -90 1999 -15 4 NAME2 199 1899 -8 1909 -70 5 NAME2 199 1909 -55 1924 -80 6 NAME2 199 1924 -10 1927 -100 ind <- split(xy,xy$ID) for (x in ind){ xx = unlist(x[,grep('X_',colnames(x))]) yy = unlist(x[,grep('Y_',colnames(x))]) fname <- paste0(x[1, 'ID'], '.png') png(fname, width=1679, height=1165, res=150) par(mar=c(6,8,6,5)) plot(xx, yy, main=unique(x[,1]), xlab="Time [Years]", ylab="Value [m]") axis(1, at = seq(1000, 2050, 5), cex.axis=1, labels=FALSE, tcl=-0.3) axis(2, at = seq(-100000, 100000, 500), cex.axis=1, labels=FALSE, tcl=-0.3) x <- x[,-1] segments(x[,2],x[,3],x[,4],x[,5],lwd=2) dev.off() }
If it is possible it would be great if the x axis could be at a fixed range (e.g. from 1940 to 2014) and if values before 1940 are present the x axis should be automatic. The range of the y-axis always differs. How could I incorporate that in my code?
-31248134 0 Count query from 2 tablesI have 2 tables like this. For a given attribute (in table doc_attribute) and a given 'word' in file (in document), I want to find the count of distinct doc_id that do not contain that particular attribute but contain that 'word' in file.
For example if the attribute given is camera and 'word' is mobile, then the result should be 2. (ie., 2nd, 3rd and 5th doc_id does not contain camera and among them only 2nd and 3rd contain the 'word' mobile in file)
table doc_attribute +--------+-----------+--------+ | doc_id | attribute | value | +--------+-----------+--------+ | 1 | product | mobile | | 1 | model | lumia | | 1 | camera | 5mp | | 2 | product | mobile | | 2 | model | lumia | | 2 | ram | 1gb | | 3 | product | mobile | | 3 | year | 2014 | | 3 | made-in | china | | 4 | brand | apple | | 4 | model | iphone | | 4 | camera | 5mp | | 5 | product | camera | | 5 | brand | canon | | 5 | price | 20000 | table document +--------+-----------------------------+ | doc_id | file | +--------+-----------------------------+ | 1 | lumia 5mp mobile 1gb 2014 | | 2 | lumia 8mp mobile 1gb 2015 | | 3 | galaxy mobile fullhd 2gb | | 4 | iphone apple 5mp 2013 new | | 5 | canon 20000 new dslr 12mp |
Current query:
select count(doc_id) from document where doc_id not in (select doc_id from doc_attribute where attribute = 'camera') and file REGEXP '[[:<:]]mobile[[:>:]]';
-31344016 0 Regular expression to fetch username= 'testuserMM' from the string I tried this regex to capture username
highs\(\d+\)\[.*?\]\[\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\]\sftid\(\d+\):\s.
It didn't work.
<55>Mar 17 12:02:00 forcesss-off [Father][1x91422234][eee][hote] abcd(QlidcxpOulqsf): highs(23455814)[mothers][192.192.21.12] ftid(64322816): oops authentication failed with (http-commo-auth, username='testuserMM' password='********'congratulation-fakem='login' )
-13997441 0 Try this all the best..
import javax.media.jai.*; public class jai_png_jpg { public static void main(String[] args)throws Exception { String filename="input_png.png"; //Read input PNG as a PlanarImage file PlanarImage inputfile = JAI.create("fileload", filename); //write output in JPG Format JAI.create("filestore",inputfile,"jai_jpg_output.jpg","JPEG"); } }
-27804975 0 I was looking for quite a bit for a complete working example of a custom wx Python control which subclasses wx.Panel
and does custom drawing on itself, and I couldn't find any. Thanks to this (and other) questions, I finally managed to come to a minimal working example - which I'm going to post here, because it does show "drawing to Panel inside of a Frame"; except, unlike the OP, where the Frame does the drawing on the Panel - here the Panel draws on itself (while sitting in the Frame).
The code produces something like this:
... and basically the red rectangle will be redrawn when you resize the window.
Note the code comments, especially about the need to Refresh() in OnSize to avoid corrupt rendering / flicker.
The MWE code:
import wx # tested on wxPython 2.8.11.0, Python 2.7.1+, Ubuntu 11.04 # http://stackoverflow.com/questions/2053268/side-effects-of-handling-evt-paint-event-in-wxpython # http://stackoverflow.com/questions/25756896/drawing-to-panel-inside-of-frame-in-wxpython # http://www.infinity77.net/pycon/tutorial/pyar/wxpython.html # also, see: wx-2.8-gtk2-unicode/wx/lib/agw/buttonpanel.py class MyPanel(wx.Panel): #(wx.PyPanel): #PyPanel also works def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, name="MyPanel"): super(MyPanel, self).__init__(parent, id, pos, size, style, name) self.Bind(wx.EVT_SIZE, self.OnSize) self.Bind(wx.EVT_PAINT, self.OnPaint) def OnSize(self, event): print("OnSize" +str(event)) #self.SetClientRect(event.GetRect()) # no need self.Refresh() # MUST have this, else the rectangle gets rendered corruptly when resizing the window! event.Skip() # seems to reduce the ammount of OnSize and OnPaint events generated when resizing the window def OnPaint(self, event): #~ dc = wx.BufferedPaintDC(self) # works, somewhat dc = wx.PaintDC(self) # works print(dc) rect = self.GetClientRect() # "Set a red brush to draw a rectangle" dc.SetBrush(wx.RED_BRUSH) dc.DrawRectangle(10, 10, rect[2]-20, 50) #self.Refresh() # recurses here! class MyFrame(wx.Frame): def __init__(self, parent): wx.Frame.__init__(self, parent, -1, "Custom Panel Demo") self.SetSize((300, 200)) self.panel = MyPanel(self) #wx.Panel(self) self.panel.SetBackgroundColour(wx.Colour(10,10,10)) self.panel.SetForegroundColour(wx.Colour(50,50,50)) sizer_1 = wx.BoxSizer(wx.HORIZONTAL) sizer_1.Add(self.panel, 1, wx.EXPAND | wx.ALL, 0) self.SetSizer(sizer_1) self.Layout() app = wx.App(0) frame = MyFrame(None) app.SetTopWindow(frame) frame.Show() app.MainLoop()
-5768447 0 Here's what I do.
row.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center_vertical"> <TextView android:id="@+id/left_text" android:layout_width="75dip" android:layout_height="wrap_content" /> <TextView android:id="@+id/right_text" android:layout_width="0dip" android:layout_height="wrap_content" android:layout_weight="1" android:maxLines="2" android:ellipsize="end" /> </LinearLayout>
Main App
public class Main extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); List<Datum> data = new ArrayList<Datum>(); data.add(new Datum("FIRST", "One line of text.")); data.add(new Datum("SECOND", "Two lines of text. Two lines of text. Two lines of text.")); data.add(new Datum("THIRD", "Three or more lines of text. Three or more lines of text. Three or more lines of text. Three or more lines of text. Three or more lines of text. Three or more lines of text.")); data.add(new Datum("FOURTH", "One line of text, again.")); ListView leftList = (ListView) findViewById(R.id.my_list); leftList.setAdapter(new MyAdapter(this, R.layout.row, data)); } } class Datum { String left, right; Datum(String left, String right) { this.left = left; this.right = right; } } class MyAdapter extends ArrayAdapter<Datum> { List<Datum> data; int textViewResourceId; MyAdapter(Context context, int textViewResourceId, List<Datum> data) { super(context, textViewResourceId, data); this.data = data; this.textViewResourceId = textViewResourceId; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(textViewResourceId, null); } Datum datum = data.get(position); if (datum != null) { TextView leftView = (TextView) convertView.findViewById(R.id.left_text); TextView rightView = (TextView) convertView.findViewById(R.id.right_text); if (leftView != null) { leftView.setText(datum.left); } if (rightView != null) { rightView.setText(datum.right); } } return convertView; } }
You can use the following configuration to call a restful service from proxy service
<inSequence> <property name="HTTP_METHOD" value="GET" scope="axis2" type="STRING"/> <send> <endpoint> <address uri="http://10.132.97.131:9763/JerseyJSONExample/rest/jsonServices/print/mahi/" format="pox"/></endpoint> </send> </inSequence>
More information can be find here
-17538023 0I believe if you define user inside UserProfile, then you can access it and will automatically be mapped? It works in my previous projects, I hope it will work with this.
сlass UserProfile { String fio String position String phone String email static belongsTo = [user: User] User userInstance; static constraints = { // some constraints }
Then you can use it
UserProfile.executeQuery("select up.userInstance from UserProfile up")
-10598433 0 1 stupid question... Why do you use this SQL Code to update Data in Progress DB? It come more easier in 4GL (resp. ABL) code... You should make a simple create procedure or service on the appserver. I had same problem with ODBC SQL access from a migration tool (spoon). I must have to give up...
-33518786 0try changing this:
$sql = mysql_query("SELECT id FROM admin WHERE username='$manager' AND password=$password' LIMIT 1");
to this:
$sql = "SELECT id FROM admin WHERE username='$manager' AND password='$password' LIMIT 1"; $result = mysqli_query($conn, $sql);
or this:
$sql = "SELECT id FROM admin WHERE username='$manager' AND password='$password' LIMIT 1"; $result = $conn->query($sql);
($conn is the connection variable change it if it different.) hope this helps out.
also change mysql_fetch_array($sql)
to mysqli_fetch_array($sql)
Hey, I know this is a bit old, but I've found the EditorialReview part of the response contains the product description. I guess the cravet that Tom talks about still applies, but at least its a way to get to the description without reverting to screen scraping (which is never a good thing!) :)
See this page of the Amazon product API: http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/
EditorialReview Response Group
For each item in the response, the EditorialReview response group returns Amazon's review of the item, which, on the Detail page, is labeled the Product Description.
No nasty screen scraping required! :)
Andy.
-5199266 0To return datas from b.php, you have to do an echo
Sorry if my question is too obvious, I´m new in perl.
My code is the following:
open (FILE1, "$ARG[0]") or die @lines1; $i=1; while (<FILE>) { chomp; push (@lines1, $_); my @{columns$1}= split (/\s+/, $lines1[$i]); $i++; }
It gives an error saying
Can´t declare array dereference at the line my @{columns$1}= split (/\s+/, $lines1[$i]);
I wanted to create columns1, columns2, columns3... and each one of them would have the columns of the corresponding line (columns1 of the line 1, columns2 of line 2 and so on...)
Because before I tried to do it this way (below) and every time it was splitting the lines but it was overwriting the @columns1 array so only the last line was saved, at the end I had the values of the 10th line (because it starting counting at 0)
for my $i (0..9) { @columns1 = split (/\s+/, $lines1[$i]); }
-12467856 0 var latitude = results[0].geometry.location.lat(); var longitude = results[0].geometry.location.lng();
ref: Javascript geocoding from address to latitude and longitude numbers not working
-5443102 0EXC_BAD_ACCESS:
He's never instantiating the 'tess' variable. Simply add [self startTesseract];
to the viewDidLoad()
method in OCRDemoViewController and it will work like a charm.
I figured it out.
inputElement.$.input.select()
Would be nice if this were documented somewhere.
-4151763 0PAM - Pluggable Authentication Modules - is a general mechanism which allows you to configure the authentication mechanism used by programs on your system, without requiring recompilation of the relevant programs. So, for example, you can change your system's basic login to use MD5 hashed passwords instead of DES encrypted passwords, without changing (recompiling) the login program.
RADIUS (Remote Authentication Dial-In User Service - but there's a suspicion it is a backronym) is a specific authentication mechanism. There are PAM modules that can authenticate via RADIUS, just as there are other PAM modules that can authenticate with LDAP or Unix password files or ...
-32368237 0 Need an EMFPlus sample fileCurrently all the EMF files which I generated through Aspose engine are in EMF dual mode.
It would be very nice if someone could enlighten me on how to generate an EMFPlus file through Aspose. If you can provide me a sample EMFPlus file, which is not in Dual mode, that will be great.
Or, please let me know from where I can download it from internet.
-32664592 0Try this:
It was initial created.
let string : String = "danial" let characters = Array(string) println(characters) //["d","a","n","i","a","l"]
String conforms to the SequenceType
protocol, and its sequence generator enumerates the characters.
Swift 2, String does no longer conform to SequenceType
, but the characters property provides a sequence of the Unicode characters:
let string = "danial" let characters = Array(string.characters) print(characters) //["d","a","n","i","a","l"]
-18221284 0 The questions has been answered but I wanted to add a comment about why your first try gives an unexpected result. This is a good example of R's vector recycling.
I'm guessing you got
year value 6 2008 4 13 2011 8
Why has R done this? What happens is R recycles the vector c("2008", "2009", "2010", "2011")
like the below.
year value compare 2006 3 2008 2007 4 2009 2007 3 2010 2008 5 2011 2008 4 2008 2008 4 2009 2009 5 2010 2009 9 2011 2010 2 2008 2010 8 2009 2011 3 2010 2011 8 2011 2011 7 2008 2012 3 2009 2013 4 2010 2012 6 2011
Do you see what's about to happen? When you run
df<-df[df$year == c("2008", "2009", "2010", "2011"),]
it will return the rows where the year
column and the compare
column are equal. You didn't get a warning because (by chance) your comparison vector was a divisor of the number of rows, so R thought it was doing the right thing.
You must treat all data coming from the client as suspect. This includes the URL. You should check that this client is indeed authenticated and that he is authorized to perform whatever action is indicated (by the URL, post data, etc). This is true even if you are only displaying data, not changing it.
It is not important if the record id is easily seen or modifiable in the URL. What matters is what can be done with it. Unless the id itself imparts some information (which would be surprising), there is no need hide it or obfuscate it. Just make sure you only respond to authenticated and authorized requests.
-16674682 0 Need Help in fixing the css part of menu'sCan you please help me fix this problem? I tried it out but not fixed yet fully.
Problem Image: http://i.stack.imgur.com/9If8Q.png
Css Style Sheet : http://aaron.wordpresstiger.com/wp-content/themes/custom_theme/style.css
Live site is the index of the style sheet URL.
Please provide me with the direct fix in the code, so that I can implement it straight away.
I look forward to hearing back.
Your help will be highly appreciated.
Thanks, Muzammil!
-1043618 0DELETE FROM table_x a WHERE rowid < ANY ( SELECT rowid FROM table_x b WHERE a.someField = b.someField AND a.someOtherField = b.someOtherField ) WHERE ( a.someField, a.someOtherField ) IN ( SELECT c.someField, c.someOtherField FROM table_x c GROUP BY c.someField, c.someOtherField HAVING count(*) > 1 )
In above query the combination of someField and someOtherField must identify the duplicates distinctively.
-19867138 0 How to run a nohup command present in a variable using ssh?I am new to Linux. I stored a command in a variable say
a="nohup ./startWebLogic.sh &".
I need to run this command on remote server along with few other commands. I have tried as follows...
ssh user@server << EOF few shell commands then eval "$a" EOF
When I run the above script, it doesn't do anything after logging in the remote server, neither it throws me any error, nor it runs the nohup command..my intention is to start the WebLogic on the remote server using nohup...thanks!!
-2281134 0 loop on a function in javascript?Can we run a loop on a function in javascript, so that the function executes several times?
-27505012 0Try this :
$day = mysql_real_escape_string($_POST['day']); $mont= mysql_real_escape_string($_POST['mont']); $year = mysql_real_escape_string($_POST['year']); $shour = mysql_real_escape_string($_POST['shour']); $ehour = mysql_real_escape_string($_POST['ehour']); $user = mysql_real_escape_string($_POST['user']); $sql="INSERT INTO reservations (day, mont, year, shour, ehour, user) VALUES ('$day', '$mont','$year', '$shour','$shour','$user')";
-12882757 0 The evaluation mode is likely triggered for each user on the system. Invoke NDepend manually on your build server with the user identity you use to run your CruiseControl.NET instance, dismiss the evaluation dialog, and then try your build again.
-11240474 0Here is an example to do it somewhat like using pipes, the script is embedded in java in this example.
import java.io.*; class junk { public static void main (String args[]) { try { String line; String script; OutputStream stdin = null; InputStream stderr = null; InputStream stdout = null; Process p = Runtime.getRuntime ().exec ("/bin/bash"); stdin = p.getOutputStream (); stderr = p.getErrorStream (); stdout = p.getInputStream (); script = "a=$(cat <<'@@@'\n" + "ICAgICBfCiAgICB8IHwgX18gX19fICAgX19fXyBfICAgIF9fXyBfXyBfIF8gX18gICAgXyBfXyBfICAg" + "XyBfIF9fCiBfICB8IHwvIF9gIFwgXCAvIC8gX2AgfCAgLyBfXy8gX2AgfCAnXyBcICB8ICdfX3wgfCB8" + "IHwgJ18gXAp8IHxffCB8IChffCB8XCBWIC8gKF98IHwgfCAoX3wgKF98IHwgfCB8IHwgfCB8ICB8IHxf" + "fCB8IHwgfCB8CiBcX19fLyBcX18sX3wgXF8vIFxfXyxffCAgXF9fX1xfXyxffF98IHxffCB8X3wgICBc" + "X18sX3xffCB8X3wKICAgICAgICAgICAgICAgICAgICBfICAgICAgICAgICAgICAgXwogICAgICAgICAg" + "ICAgICAgICAgfCB8X18gICBfXyBfIF9fX3wgfF9fCiAgICAgICAgICAgICAgICAgICB8ICdfIFwgLyBf" + "YCAvIF9ffCAnXyBcCiAgICAgICAgICAgICAgICAgICB8IHxfKSB8IChffCBcX18gXCB8IHwgfAogICAg" + "ICAgICAgICAgICAgICAgfF8uX18vIFxfXyxffF9fXy9ffCB8X3wK" + "\n" + "@@@)\n" + "st=0\n" + "for (( i=0; i<\"${#a}\"; i++ ))\n" + "do\n" + " x=${a:$i:1}\n" + " in=$(($(expr index \\\n" + " 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' \"\\\\$x\")-1))\n" + " if [ $in -ge 0 ]; then case $st in\n" + " 0 ) out=$(($in<<2)); st=3;;\n" + " 1 ) out=$(($out|$in)); \n" + " printf \\\\$(printf '%03o' $(($out&255)) ) ; st=0 ;;\n" + " 2 ) out=$(($out+($in>>2))); \n" + " printf \\\\$(printf '%03o' $(($out&255)) ) ;\n" + " st=0; out=$(($in<<6)); st=1;;\n" + " * ) out=$(($out+($in>>4))); \n" + " printf \\\\$(printf '%03o' $(($out&255)) ) ;\n" + " st=0; out=$(($in<<4)); st=2;;\n" + " esac fi\n" + "done\n"; stdin.write (script.getBytes ()); stdin.close (); BufferedReader br = new BufferedReader (new InputStreamReader (stdout)); while ((line = br.readLine ()) != null) { System.out.println(line); } br.close (); br = new BufferedReader (new InputStreamReader (stderr)); while ((line = br.readLine ()) != null) { System.out.println ("2>" + line); } br.close (); p.waitFor (); System.out.println ("exit code " + p.exitValue ()); } catch (IOException e) { e.printStackTrace (); } catch (java.lang.InterruptedException e) { e.printStackTrace (); } } }
-36565187 0 For this you need to find the constructor and invoke it.
Constructor[] ctors = myClass.getDeclaredConstructors(); Constructor ctor = null; for (int i = 0; i < ctors.length; i++) { if (ctor.getGenericParameterTypes().length == 2) { ctor = ctors[i]; break; } } if (ctor != null) { return ctor.newInstance(view, getActivity()); }
-32333275 0 Something like this? It doesn't use twitter bootstrap or a grid system, its just a couple of simple floats.
.large { float: left; margin-right: 10px; } .small { float: left; } .small img { height: 95px; display: block; } .small img:first-child { margin-bottom: 10px; }
<div class="gallery"> <img src="http://placehold.it/300x200" class="large" /> <div class="small"> <img src="http://placehold.it/300x200" /> <img src="http://placehold.it/300x200" /> </div> </div>
You should disable gravity for the islands' rigidbody, first of all. That way, they will float, but things like inertia will still apply.
If you want your character to pull the islands to himself when grabbing them with a rope, you could use Rigidbody.AddForce(Vector3 vec3)
and pass the vector opposite to the direction the rope is aimed at as a parameter (you should use Vector3.Reflect()
to do that.)
This will get you started, but there are more ways to improve the effect, such as making the islands gradually slow down after pulling them. I'd suggest multiplying the island's velocity by a fraction of 1, in that case, but there are other ways to do it.
-6677926 0 Entity Framework Code First Linq MVC 3 RazorThis is my model;
namespace AtAClick.Models { public class LocalBusiness { public int ID { get; set; } public string Name { get; set; } public int CategoryID { get; set; } public string address { get; set; } public string desc { get; set; } public int phone { get; set; } public int mobile { get; set; } public string URL { get; set; } public string email { get; set; } public string facebook { get; set; } public string twitter { get; set; } public string ImageUrl { get; set; } public virtual Category Category { get; set; } } public class Category { public int CategoryID { get; set; } public string Name { get; set; } public virtual ICollection<LocalBusiness> Businesses { get; set; } } }
I have a view which lists the categories and one which lists the businesses. I want another which list all the business in a certain category My question is, what would my Linq query in my controller look like? Something like..
var companyquery = from c in db.LocalBusiness where c.Category = Category.Name select c;
But obvioulsy this isn't working. I'm new to all this so thanks in advance for the help, and if you need anymore detail just ask. Thanks!!
My controller, is this what you mean?
public ViewResult Browse(int id) { int categoryID = id; var companyquery = from c in db.LocalBusinesses where c.Category.CategoryID == categoryID select c; return View(companyquery); }
-22220605 0 Visual Studio SSDT Data Compare how to compare two tables in a single database Trying to do something simple Data Compare in SSDT but proving a bit hard.
In one database, I have two tables I want to compare.
These tables have the same schema, just different table names. And I just want to see if this tool will give me a nice way to compare the data in both.
I.e.
tblOutput tblOutput_210314
But this picking of two tables to compare against each other in a single database I can't see how to achieve.
Seems like you can only pick a table name which exists in both source and target databases. Since my source and target database is the same, I am basically comparing my table to itself ?
Anyone know of a way to achieve this with Data Compare ?
I am trying to connect client to a server using sockets.
Server code:
ServerSocket server = new ServerSocket(6780); Socket clientSocket = server.accept(); ObjectInputStream fromClient= new ObjectInputStream(clientSocket.getInputStream()); ObjectOutputStream toClient = new ObjectOutputStream(clientSocket.getOutputStream());
Client code:
Socket nodeSocket = new Socket(ServerIP, 6780); ObjectInputStream fromServer = new ObjectInputStream(nodeSocket.getInputStream()); ObjectOutputStream toServer = new ObjectOutputStream(nodeSocket.getOutputStream()); toServer.writeObject(this);
When a client connects, server listens and accepts client connection. But when I try to write my class object to the server, "toServer.writeObject(this);" it throws
java.io.NotSerializableException: Peer at java.io.ObjectOutputStream.writeObject0(Unknown Source) at java.io.ObjectOutputStream.writeObject(Unknown Source) at Peer.requestEntryNode(Peer.java:47) at Peer.main(Peer.java:87)
Peer is my class name.
I tried to find out the cause of this exception, it says that object that needs to be written must be serializable. I also tried to implement Serializable interface from Peer class. But that doesnt help.
Can anyone suggest?
-9136358 0You probably shouldn't be calling glLookAt
at all. You sure don't want every object drawn in the middle of the screen. Do you have a problem with the objects changing the modelview matrix and not putting it back? Use glPushMatrix
and glPopMatrix
instead of repeating the look-at calculation.
The point of lazy init is to defer allocating resources since you don't know when or if you need them.
In your case, this doesn't really make sense: As soon as the image is uploaded, the server will need the thumbnail -- the user wants to see the new image immediately, right? Therefore deferring the creation of the thumbnail has no positive ROI.
-33652536 0 UndefinedMethodException in appDevDebugProjectContainer.php line 1606I'm somewhat lost what I've done here. My app was functioning for a while, and at some point I changed something that caused this error. I've cleared my dev cache. At some point I wonder if I updated my composer and caused something because I wasn't even touching the php side of my app when I broke it.
Here's the full error:
UndefinedMethodException in appDevDebugProjectContainer.php line 1606: Attempted to call an undefined method named "AddAthlete" of class "FOS\RestBundle\Util\FormatNegotiator".
That particular function looks like this:
protected function getFosRest_ExceptionFormatNegotiatorService() { $this->services['fos_rest.exception_format_negotiator'] = $instance = new \FOS\RestBundle\Util\FormatNegotiator(); $instance->AddAthlete($this->get('fos_rest.request_matcher.0dfc4cce134bee15f08405cb5cea4845b13ff7d8c8f779004218432a2c552bd0cd9f9d27'), array('priorities' => array(0 => 'html', 1 => 'json', 2 => 'xml'), 'fallback_format' => NULL, 'prefer_extension' => '2.0', 'methods' => NULL, 'stop' => false)); return $instance; }
I'm not particularly familiar with how this gets generated. Could someone help? If needed, here's a link to my bundle on github
-11708491 0You can think of grids as graphs and search space representations can be shown using graphs:
Block A,B,C,D are nodes of graph and weights between the nodes can represent path distance between nodes.
-39461129 0Change unusedCap() to this?
public double unusedCap() { double fuelLeft=(fuelCapacity - fuelAmount); return fuelLeft; }
-17528653 0 Alert the DATA you are getting in response from your ajax page. Try to print in console.log to check. It will print the Object in console
-37140076 0 HTML anchor in URL not working in ChromeI've been pulling my hair on a tiny thing : https://numa.co/about/#corporate-innovation
This URL doesn't go to the right anchor, only in Chrome and I can't see why... It works on our dev environment, the only difference I can see is that we're behind Cloudflare in prod and it's HTTPS. I can't see how this would make a difference though.
Thanks a lot for any insights :)
-27865268 0Use |
and not OR
for multiple choices, thus making code like:
with ALUop select z <= s_add_sub when "00000" | "00001" | "00010" | "00011", x AND y when "00100", ...
This is similar to the syntax for multiple choices to case
.
I have a main view controller in the main story board. I want this controller to have a state when it is initiated. I need to know where this view controller is initiated so that I can change its constructor to the following custom constructor. Can someone help me out?
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{ self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { self.state= @"login";} return self;}
-7806358 0 I found a solution for this, instead of passing this to the setData method:
intent.setData(Uri.parse(ContactsContract.Contacts.CONTENT_LOOKUP_URI + "/" + androidContactId));
I should be passing this:
Uri lookupUri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookup_key); Uri res = ContactsContract.Contacts.lookupContact(activity.getContentResolver(), lookupUri);
and in the setData() method, I pass the variable res, that is a URI type.
This question helped me a lot!
-26232844 0Given that you're using the system Perl (and, from a comment, it seems you have root) then the easiest approach is probably to install the package that is pre-built for your Linux distribution.
For a Debian/Ubuntu-based system:
$ sudo apt-get install libtext-csv-perl
For a RedHat/Centos/Fedora-based system:
$ sudo yum install perl-Text-CSV
-1712065 0 When Ruby loads the file containing your module B
and reaches the acts_as_taggable
line, it will try to execute the acts_as_taggable
class method of ClassMethods
(which doesn't exist because it is actually a class method of ActiveRecord::Base
).
You can use the included
method to call acts_as_taggable
when your module is included though. included
is passed the class the module is being included in, so the following will work:
module B def self.included(base) base.acts_as_taggable # ... end # ... end
-21037597 0 Since a
is static compiler converts it to TestClass1.a
. For non-static variables it would throw NullPointerException
.
we can not instatiate the interface (since do not have constructor).
-7786216 0What I do on my squeeze boxes to get ruby 1.9 as default:
cd /usr/bin ln -sf ruby1.9.1 ruby ln -sf gem1.9.1 gem ln -sf erb1.9.1 erb ln -sf irb1.9.1 irb ln -sf rake1.9.1 rake ln -sf rdoc1.9.1 rdoc ln -sf testrb1.9.1 testrb
I run a lot of rails production servers this way and all other debian ruby packages are not broken because they relay on /usr/bin/ruby1.8 binary.
This not "true debian way" but for some reason update-alternatives
does not support configuring ruby in squeeze.
In Ubuntu 11.10 you can just run update-alternatives --config ruby
and selected desired version
I also recommend you to update rubygems before you start installing any gems REALLY_GEM_UPDATE_SYSTEM=true gem update --system
The current working directory in ST can be opened in the Finder by right-clicking anywhere in an open file and selecting "Reveal in Finder".
At any rate, the concept of a 'current working directory' is meaningful in ST only in the context of a project which itself is a folder and all the files in it (except the ones filtered out by the project file). That would preclude the possibility of changing the working directory straight away, I should think
-33861175 0Are you using SRFI 69? Look into hash-table-update!
.
It's a bit complicated to make only the first item in the collection required. I suggest you creating a separate property for that and mark it as required:
ViewModel
public class MyViewModel { [Required] public string RequiredName { get; set; } public List<string> SubSiteNames { get; set; } }
View
<label>Name </label> @Html.TextBoxFor(m => m.RequiredName) @Html.ValidationMessageFor(m => m.RequiredName) @for (int i = 1; i <= 3; i++) { <label>Name </label> @Html.TextBoxFor(m => m.SubSiteNames[i - 1]) }
Then just remove the first item from the SubSiteNames
list and set it to the RequiredName
.
You could do this, and you can do it in several ways.
1) (simple) copy the file to your server, and rename it. Point your download links to this copy.
2) (harder) Create a stub php file, called , read the file from the remote server within php, and stream the content to the script output. This will need you to set appropriate headers, etc. as well as setting up your webserver to parse through PHP.
Seriously, I'd go with option 1. (assumes you have a legal right to serve the content, etc.)
-26206315 0Here are some fixes to apply to your program:
.text string: .asciz "Your first program\n" number1in: .asciz "%u" #use different format strings for input and output number2in: .asciz "%d" number1out: .asciz "%u\n" #added "\n" to flush stdout. number2out: .asciz "%d\n" #same .global main main: movq $0, %rax movq $string, %rdi push %rbp #dummy push to satisfy 16-byte alignment requirements call printf call adding call end adding: pushq %rbp #must preserve %rbp before... movq %rsp, %rbp #...%rbp is overwritten here subq $16, %rsp #must subtract 16 from %rsp to satisfy 16-byte alignment leaq -8(%rbp), %rsi movq $number1in, %rdi movq $0, %rax call scanf movq -8(%rbp), %rsi #this line must be edited... movq $number1out, %rdi movq $0, %rax call printf movq $0, %rdi leaq -8(%rbp), %rsi movq $number2in, %rdi movq $0, %rax call scanf movq -8(%rbp), %rsi #as must this... movq $number2out, %rdi movq $0, %rax call printf movq %rbp, %rsp popq %rbp ret end: pushq %rbp #dummy push to satisfy 16-byte alignment movq $0, %rdi call exit
-35705137 0 You can use sub-query also :
select s.student_id, (select IFNULL(is_attend,0) from attend where student_id=s.student_id) as is_attend from student as s
-1662595 0 (void)doneAceSpadeSetupClick:(id)sender {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *string1; NSString *string2; NSString *string3; NSString *path = [documentsDirectory stringByAppendingPathComponent:@"card1.plist"]; NSMutableArray *myArrayToSave = [[NSMutableArray alloc] initWithCapacity: 1]; //48 since you said in the comments that you have 48 of these NSDictionary *myDict = [[NSDictionary alloc] initWithObjectsAndKeys: string1, characterText.text, //I'm assuming your strings are in a C array. string2, actionText.text,// up to you to replace these with the right string3, objectText.text, nil]; //iPhone simulator crashed at this line [myArrayToSave addObject:myDict]; if (![myDict writeToFile:path atomically:YES]) NSLog(@"not successful in saving the unfinished game"); [self dismissModalViewControllerAnimated: YES];
}
I am new to Apache environment. Preferably I do not want .htaccess file, but I think I have not choice. My application runs without problem in my notebook which is windows environment using WAMPSERVER. But when I deploy to hosting server which uses Apache, I face some problems. I am not sure the following structure is correct for CodeIgniter application. Following is the directory structure in hosting server...
httodocs/ /survey /admin /config <-- $route['default_controller'] = "admin"; /controllers /models /views /... /statistic /config <-- $route['default_controller'] = "statistic"; /controllers /models /views /... /mySurvey /config <-- $route['default_controller'] = "mySurvey"; /controllers /models /views /... /css /images /scripts /system /... /index.php <-- $application_folder = 'mySurvey'; /admin.php <-- $application_folder = 'admin'; /Statistic.php <-- $application_folder = 'statistic';
What I did was just duplicate the Application folder and rename to admin, statistic and mySurvey respectively, I set the default controller as stated above.
all application base_url() = 'http://survey.myhost.com'
which is a sub domain under myhost.com
The root index.php is actually CI application environment which allow user to go to mySurvey application by default, when they enter "http://survey.myhost.com".
From the first page on, when I access http://survey.myhost.com/index.php/mySurvey/index/0 I got error:
`The specified CGI application misbehaved by not retruning a complete set of HTTP headers.`
The same message shows when I access http://survey.myhost.com/admin.php/admin/login
or http://survey.myhost.com/statistic.php?statistic/chart/1
(note that I also do use query string for my application)
Obviously, these have to do with the route. I do not have any .htaccess file at the server because WAMP does not need it, Appreciate if anyone can advice where can I put the .htaccess file and what is the correct mod-rewrite for the structure above and is this structure appropriate.
Regards,
KK Gian
-6336271 0you need to first clone the row from the original then add to new view. http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewrow.clone.aspx
-11626536 0 Adding buttons to panel dynamicallyExtJS 4
How to add a button to a panel (dynamically) as if in the buttons property? In ExtJS 3, we have panel.addButton()
but didn't find any such function in ExtJS 4. I tried panel.addDocked()
too but it didn't work.
I came across a very strange problem with Ansible (1.8.2) that boils down to executing this simple command in a shell script:
#!/bin/sh # transform a String into lowercase chars: echo "TeSt" | tr [:upper:] [:lower:]
When I log into the remote Solaris machine, this script seems to work no matter in which shell I am (e.g., /bin/sh
, /bin/bash
):
# ./test.sh test
Also when I execute this script using a remote ssh command, it works:
# ssh root@<remote-host> '/tmp/test.sh' test
However, when I execute the same script with the Ansible command
or shell
modules, I get a "Bad String" error no matter what shell I specify:
- shell: executable=/bin/sh /tmp/test.sh [FATAL stderr: Bad string] - shell: executable=/bin/bash /tmp/test.sh [FATAL stderr: Bad string] - command: /tmp/test.sh [FATAL stderr: Bad string]
It took me ages to figure out that it works with the raw
module:
- raw: executable=/bin/sh /tmp/test.sh [OK]
Does anyone have a clue why the shell
and command
modules produce this error?
Some more info about the remote host on which the script fails:
/bin/sh
, /bin/bash
, /bin/ksh
) are GNU bash, version 4.1.2(1)-release (x86_64-redhat-linux-gnu)The locale differs! When I log in or execute a remote ssh command, the locale looks like this:
LANG= LC_CTYPE="C" LC_NUMERIC="C" LC_TIME="C" LC_COLLATE="C" LC_MONETARY="C" LC_MESSAGES="C" LC_ALL=
However, with Ansible, I get this:
LANG=en_US.UTF-8 LC_CTYPE=en_US.UTF-8 LC_NUMERIC="en_US.UTF-8" LC_TIME="en_US.UTF-8" LC_COLLATE="en_US.UTF-8" LC_MONETARY="en_US.UTF-8" LC_MESSAGES="en_US.UTF-8" LC_ALL=
-16822349 0 Using dp is the right way. It wont be a constant size cuz AOS will scale dps using multiplier according to screen density. (btw dip==dp they are absolutely the same) so dps are density independent. However scaling is not enough usually. So you need to create separate resources for different screens and I might say that supporting multiple screens is a really very big pain in da @$$. Seems like the only one good and proper way is to use OpenGL...
You might found following links helpful:
How to use resource qualifier on layouts to distinguish smartphones like HTC Desire and Samsung Galaxy Nexus
image size (drawable-hdpi/ldpi/mdpi/xhdpi)
Avoid Multiple Drawable Sets (hdpi/mdpi/ldpi)
Widget Layout for 960x540 and 854x480
getDimension()/getDimensionPixelSize() - mutliplier
http://www.findbestopensource.com/product/svg-android
If you have an text/textarea attribute named my_attr you can get it by: product->getMyAttr();
Your ItemsSource
is a simple binding to a collection of [something] that will fill out the combolist, here's a quick sample:
public class MyDataSource { public IEnumerable<string> ComboItems { get { return new string[] { "Test 1", "Test 2" }; } } } <ComboBox Height="23" Name="status" IsReadOnly="False" ItemsSource="{Binding Path=ComboItems}" Width="120"> </ComboBox>
That's not a complete sample, but it gives you the idea.
It's also worth noting that you don't have to use the ItemsSource
property, this is also acceptable:
<ComboBox Height="23" Name="status" IsReadOnly="False" Width="120"> <ComboBox.Items> <ComboBoxItem>Test 1</ComboBoxItem> <ComboBoxItem>Test 2</ComboBoxItem> </ComboBox.Items> </ComboBox>
-7858145 0 undefined reference (templates) I have a namespace that gets built out of a .cpp and .h
lots of classes use this namespace and call the template functions from within it How do I fix all the undefined references during the linking process? Where would I put all the definitions of the template functions? could someone show me an example of a namespace that uses templates and then a class that uses that namespace and can successfully call one of the templated functions without error?
My personal favorite would be to generate a CSV file (using a 4.5 lines script) and load it into your SQL DB using BULK INSERT. This will also allow better customization of the data as sometimes is needed (e.g. when writing tests).
-24820584 0You can simplify this a little bit.
function searchBox(inputVal) { var regExp = new RegExp(inputVal, 'i'); $('#boxdata').find('tr').removeClass('red').filter(function() { return $(this).find('td').filter(function() { return regExp.test( $(this).text() ); }).length && $.trim(inputVal).length; }).addClass('red'); }
So remove the red
class from all <tr>
's first, then filter them, test the text of each <td>
, if it matches, return the <tr>
and then add the class red
again.
As for changing from a table
to div
, the jQuery would depend on how you structure your markup, but the principle would remain the same.
Try this:
(^id-.*)([^bitcoin])
Tested using
http://www.regexplanet.com/advanced/java/index.html
-38511760 0 Facebook Messenger Bot Persistent MenuI am generating my first bot working with node.js and heroku but finding some difficulties to understand the persistent menu functionalities.
Question 1) How do can I attach event as callbacks?
function persistentMenu(sender){ request({ url: 'https://graph.facebook.com/v2.6/me/thread_settings', qs: {access_token:token}, method: 'POST', json:{ setting_type : "call_to_actions", thread_state : "existing_thread", call_to_actions:[ { type:"postback", title:"FAQ", payload:"DEVELOPER_DEFINED_PAYLOAD_FOR_HELP" }, { type:"postback", title:"I Prodotti in offerta", payload:"DEVELOPER_DEFINED_PAYLOAD_FOR_HELP" }, { type:"web_url", title:"View Website", url:"https://google.com/" } ] } }, function(error, response, body) { console.log(response) if (error) { console.log('Error sending messages: ', error) } else if (response.body.error) { console.log('Error: ', response.body.error) } })
}
Question 2) The only way I have found for empty the persistent menu and generating a new one is with a delete request via terminal ("as Facebook documented")m is there a possibily to clear inserting a refresh function on my app.js file?
curl -X DELETE -H "Content-Type: application/json" -d '{"setting_type":"call_to_actions","thread_state":"existing_thread"}' "https://graph.facebook.com/v2.6/me/thread_settingsaccess_token=PAGE_ACCESS_TOKEN"
-32141404 0 Here is a solution i found with your markup.
Used CSS to beautify it.
Jquery:
What did you do?
when .menu_link
is hovered i find what index it has.
The index finds if its the first child or second etc.
When we have this magic index number var nthNumber
we can use it to find its corresponding .submenu_panel
(I'm guessing here since i cant see all your code) and hide or show this panel
Eg. when we hover the first .menu_link
,
we will show the first .submenu_panel
And we do the same for the second and third etc.
$(".menu_link, .submenu_panel").hover(function() { //Hover inn function var nthNumber = $(this).index() + 1; $("[id$=Submenu]").show(); $("[id$=Submenu] .submenu_panel:nth-of-type(" + nthNumber + ")").show(); }, function() { //Hover out function $("[id$=Submenu]").hide(); var nthNumber = $(this).index() + 1; $("[id$=Submenu] .submenu_panel:nth-of-type(" + nthNumber + ")").hide(); });
#menu [id$=Menu] { border: 2px solid #2980b9; border-radius: 5px; background-color: #3498db; } #menu [id$=Menu] .menu_link { padding: 10px 10px; display: inline-block; font-size: 1.2em; } #menu [id$=Menu] .menu_link:hover { background-color: #45a9ec; //border: 2px solid #2980b9; border-radius: 2px; cursor: pointer; //Visual only (REMOVE)! } #menu [id$=Submenu] { display: none; } #menu [id$=Submenu] .submenu_panel { display: none; background-color: #45a9ec; border: 2px solid #2980b9; border-top: none; border-bottom-right-radius: 2px; border-bottom-left-radius: 2px; } #menu [id$=Submenu] .submenu_panel .submenu_link { position: relative; display: block; text-indent: 15px; font-size: 1.1em; padding: 4px 0px; border-bottom: 1px solid #2980b9; } #menu [id$=Submenu] .submenu_panel .submenu_link:hover { background-color: #56bafd; cursor: pointer; //ONLY FOR VISUAL(REMOVE)! } #menu [id$=Submenu] .submenu_panel .submenu_link:first-child { border-top: 1px solid #2980b9; margin-top: -5px; padding-top: 5px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <nav id="menu"> <div id="pn1Menu"> <a class="menu_link">Lorem</a> <a class="menu_link">Ipsum</a> <a class="menu_link">Dollar</a> <a class="menu_link">Si</a> <a class="menu_link">Amet</a> </div> <div id="pn1Submenu"> <div class="submenu_panel"> <a class="submenu_link">100</a> <a class="submenu_link">200</a> <a class="submenu_link">300</a> <a class="submenu_link">400</a> <a class="submenu_link">500</a> <a class="submenu_link">600</a> </div> <div class="submenu_panel"> <a class="submenu_link">010</a> <a class="submenu_link">020</a> <a class="submenu_link">030</a> <a class="submenu_link">040</a> <a class="submenu_link">050</a> <a class="submenu_link">060</a> </div> <div class="submenu_panel"> <a class="submenu_link">1001</a> <a class="submenu_link">2002</a> <a class="submenu_link">3003</a> <a class="submenu_link">4004</a> <a class="submenu_link">5005</a> <a class="submenu_link">6006</a> </div> </div> </nav>
I know it isn't very practical to load bitmaps from the device storage synchronously, but I really have to do it. I haven't figured out any way to do this.
-36056345 0 create an DAO Access file in Excel VBAI am unable to create a file using following commands, could anyone help me in this regard. The error it says is invalid argument. I got office 2010.
My ref is :MS office 14.0 ACCESS DATABASE OBJECT LIBRARY
Sub DBcreate() Dim DB As DAO.Database Dim RS As DAO.Recordset Set DB = DAO.Workspaces(0).CreateDatabase("D:\tblImport11.accdb", DB_LANG_GENERAL) DB.Close 'Set RS = Nothing Set DB = Nothing End Sub
i also tried:
Set DB = DBEngine.CreateDatabase("D:\tblImport11.accdb", DB_LANG_GENERAL)
This also gives same error
-10087787 0 Using Django's Paginator class with a MongoDB cursorIs there a known method of extending the MongoDB cursor object to make it compatible with Django's django.core.paginator.Paginator
class?
Or, maybe, extend Django's class?
-40465128 0i had this problem i fix it with add inside to $http the line header
exapmle : headers: {'Content-Type': 'application/json'}
$http({ method:"GET", url:"http://example.com", headers: {'Content-Type': 'application/json'} })then(function(res){ console.log(res); });
-487413 0 One possible check you could make to determine if there was enough space, would be to check how much area the current set of rectangels are taking up. If the amount of area left over is less than the area of the new rectangle then you can immediately give up and bail out. I don't know what information you have available to you, or whether the rectangles are being laid down in a regular pattern but if so you may be able to vary the check to see if there is obviously not enough space available.
This may not be the most appropriate method for you, but it was the first thing that popped into my head!
-6823559 0This approach seems a little smelly in that you have deployment concerns leaking into your service contracts and implementation. Given that REST does not expose metadata anyway I don't see a lot of benefit in the different interfaces.
I would have thought a behavior or ServiceAuthorizationManager, which examined the message version and disallowed access for REST requests would be a cleaner solution. That way you could have a single service implementation for a single contract and push protocol issues back to where they belong: deployment and configuration.
-40638392 0guest.TABLE2.keyfield belongs to the updated table which does not exists in this query
This is a query with the same logic as the update.
For each record of T2 you are going to get the value for update based on T1.
select guest.TABLE2.* ,(SELECT count(T1.key_field) FROM ThisDB..TABLE1 T1 WHERE T1.key_field = guest.TABLE2.keyfield AND T1.date_field between (DATEADD(DAY, -7, guest.TABLE2.other_date)) and guest.TABLE2.other_date) from guest.TABLE2
-7050629 0 The observer is notified when an observed key path changes it's value. The ´change` dictionary contains information related to how the observed key path has changed. This dictionary is only filled with the values according to the options that you provide when setting
NSKeyValueObservingOptionNew
- Specifies that you want to have access to the new value that the key path changed into. NSKeyValueObservingOptionOld
- Specifies that you want to have access to the old value that the key path changed from.If specified to be sent these old and/or new values are accessible from the change
dictionary using these keys:
NSKeyValueChangeNewKey
- To access the new value.NSKeyValueChangeOldKey
- To access the old/previous value.I have 3 links styled as a list in html, I used this code in CSS to bring them beside each other:
li { float:left; margin-right:15px; margin-top:40px; }
But when I click one of them the other link on the right moves towards the one I clicked. I don't know the reason why this happening. but how to make them fixed?
The code:: HTML:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title> WebMD - Better information. Better Health. </title> <link rel="stylesheet" href="mainMd.css"/> <img src="logo_trans.png" class="logo"/> </head> <body> <header> <ul class="categories"> <li class="links1" id="symp"><a href="">Symptoms</a></li> <li class="links1" id="doc"><a href="">Doctors</a></li> <li class="links1" id="health"><a href="">Health Care Reform</a></li> </ul> </header> <section> </section> <aside> </aside> <footer> </footer> </body> </html>
CSS:
html { background-image:linear-gradient(to top, white, #F5F9FA); height:100%; } .logo { padding-left:176px; padding-top:4px; float:left; } li { float:left; margin-right:15px; margin-top:40px; font-family:Candara; font-size:12px; color:#5895D4; } #symp { list-style-image:url(walking.png); margin-left:55px; } #doc { list-style-image:url(doc.png); } #health { list-style-image:url(umb.png); } li a { color:#5895D4; text-decoration:none; } li a:hover { text-decoration:underline; } li a:active { } li a:visited { }
-30609278 1 XPATH - Extract content between two positions with different indent (python) I'm trying to get some data from an HTML file via url. Here's an example:
<html> ... <div class="start"> <!-- Everything from here.. --> <p></p> <p><a href=''></a> <span></span <br> <!-- ..to here --> <div class="end"> ... </div> ... ... </div> ... </html>
I'm trying to the the data that is directly under div class="start"
, but I don't know how, since the div contains almost the whole page. What I do know, is that div class="end"
comes right after the data I want. Keep in mind that I don't want only the text in between, but the different elements, which in this case i <p> & <span> & <a>
. Also note that the element types may vary from what is showing in the HTML above.
Google gave me different types of this (without any luck): '//*[preceding-sibling::div[@class="start"] and following-sibling::div[@class="end"]]'
I could not find a way to scroll through the length of my output so what I did is a loop that is gradually increasing by increments of 0.1 the value of ${maxnoise} (with a condition on the number of line output) because this variable is actually the one conditioning how big is the output. It works fine this way so I consider my question answered.
-5778273 0Your program can't know that because it simply doesn't know when it's not running. And when it IS running, it simply uses 100% of the CPU. In this case, precentages make sense only as relative measurements, but you haven't specified relative to WHAT.
-27614310 0OK. I found solution for my problem I think my problem about passing Multiple value parameter to Query. So I don't pass it to Query but I retrieve all Rows then Use Tablix Filters for filter rows
I follow this Article SQL Server Reporting Service using Multi-value Parameters
and this suggestion by Rockit Here
-38415962 0 webgl - how do i declare a float variablesuper simple question: how do i properly declare a float variable in webgl?
Background:
I'm playing with this codepen: http://codepen.io/jlfwong/pen/Wxjkxv
the point of this codepen is to allow you set the color of each pixel in a shader based on a render function.
I get the basics and I got things working pretty well, but then I tried to get "fancy".
I'm focussing on this section:
var fragmentShader = compileShader(' \n\ void main(){ \n\ gl_FragColor = vec4(step(25.0, mod(gl_FragCoord.x, 50.0)), \n\ step(25.0, mod(gl_FragCoord.x, 50.0)), \n\ step(25.0, mod(gl_FragCoord.x, 50.0)), \n\ 1.0); \n\ } \n\ ', context.FRAGMENT_SHADER);
All I want to do is save step(25.0, mod(gl_FragCoord.x, 50.0))
off to a variable so i tried this:
var fragmentShader = compileShader(' \n\ void main(){ \n\ float x_thing = step(25.0, mod(gl_FragCoord.x, 50.0)); \n\ \n\ gl_FragColor = vec4(x_thing, x_thing, x_thing, 1.0); \n\ } \n\ ', context.FRAGMENT_SHADER);
This doesn't work because it seems to be missing a precision declaration for float. here is the error:
uncaught exception: Shader compile failed with: ERROR: 0:3: '' : No precision specified for (float)
I have tried a few things to remedy this:
precision float x_thing = step(25.0, mod(gl_FragCoord.x, 50.0));
precision highp float x_thing = step(25.0, mod(gl_FragCoord.x, 50.0));
precision highp float; float x_thing = step(25.0, mod(gl_FragCoord.x, 50.0));
Also i've been googling and fiddling with this for a while and I'm just annoyed with having issues declaring a variable :P
TL;DR
how do i properly declare a float variable in webgl? / what am i doing wrong?
-39633307 1 unable to find the error in this python codeUnable to find the error indicated in driver.find_element_by_css_selector(button).click()
trying to run in python 2.7
from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as ec from selenium.webdriver.common.by import By import time chrome_path=r"C:\Users\Bhanwar\Desktop\New folder (2)\chromedriver.exe" driver =webdriver.Chrome(chrome_path) driver.get("https://priceraja.com/mobile/pricelist/samsung-mobile-price-list-in-india") driver.implicitly_wait(10) i=0 time = 5 by = By.ID hook = "product-itmes-" # The id of one item, they seems to be this plus # the number item that they are button = '.loadmore' while i<4: element_number = 25*i # It looks like there are 25 items added each time, and starts at 25 WebDriverWait(driver, time). until(ec.presence_of_element_located(by, hook+str(element_number)) driver.find_element_by_css_selector(button).click() time.sleep(1) # Makes the page wait for the element to change i+=1
-1657076 0 If you want do do it in ajax, you should put your form inside an iframe, so when you upload the image, only a small part of the page (the form) is sent to your server.
After that, you can use upload.php response to get the name and path of uploaded image, and then you can just change the src of the img tag.
-35775062 0The text rendering code is probably disabling the depth test and your cube drawing code doesn't (re-)enable it.
The line
gloo.set_state(clear_color=(0.30, 0.30, 0.35, 1.00), depth_test=True)
does enable depth testing, but its set only in the constructor. Here's an important rule (speak with me): There is no "initialization" in OpenGL. There's just state, which must be set when needed, right before it's needed to what it is needed to be. Add this
right before the cube triangle drawing code, i.e.
def on_draw(self, event): gloo.clear(color=True, depth=True) self.testText.draw(self.tr_sys) #draw text
gloo.set_state(depth_test=True) self.program.draw('triangles', self.indices) #draw the cube
-28399643 0 You could construct sqlite
database tables and query them for the results you want.
import sqlite3, operator reference = [[1, 0, 0], [2, 0, 10], [3, 0, 20], [4, 0, 30], [5, 0, 40]] temperature = [[0, 0, 100], [0, 10, 110], [0, 20, 120], [0, 30, 130], [0, 40, 140]]
A couple of helpers - I like using these because it makes subsequent code readable.
reference_coord = operator.itemgetter(1,2) ref = operator.itemgetter(0) temperature_coord = operator.itemgetter(0,1) temp = operator.itemgetter(2)
Create a database (in memory)
con = sqlite3.connect(":memory:")
Two ways to approach this, preserve all the information in separate tables or create a single table with only the data you want
One table for each list
con.execute("create table reference(coordinate TEXT PRIMARY KEY, reference INTEGER)") con.execute("create table temperature(coordinate TEXT PRIMARY KEY, temperature INTEGER)") # fill the tables parameters = [(str(reference_coord(item)), ref(item)) for item in reference] con.executemany("INSERT INTO reference(coordinate, reference) VALUES (?, ?)", parameters) parameters = [(str(temperature_coord(item)), temp(item)) for item in temperature] con.executemany("INSERT INTO temperature(coordinate, temperature) VALUES (?, ?)", parameters )
Query the two tables for the data you need
cursor = con.execute('SELECT reference.reference, temperature.temperature FROM reference, temperature WHERE reference.coordinate = temperature.coordinate') print(cursor.fetchall())
Table that combines the data in the two lists
con.execute("create table data(coordinate TEXT PRIMARY KEY, reference INTEGER, temperature INTEGER)")
Build the table with only the data you care about
parameters = [(str(reference_coord(item)), ref(item)) for item in reference] con.executemany("INSERT INTO data(coordinate, reference) VALUES (?, ?)", parameters) parameters = [(temp(item), str(temperature_coord(item))) for item in temperature] con.executemany("UPDATE data SET temperature=? WHERE coordinate=?", parameters)
Simple query because the table only has what you want
cursor2 = con.execute('SELECT reference, temperature FROM data') print(cursor2.fetchall()) con.close()
Result:
>>> [(1, 100), (2, 110), (3, 120), (4, 130), (5, 140)] [(1, 100), (2, 110), (3, 120), (4, 130), (5, 140)] >>>
Once you get your data into a database it is fairly easy to extract information from it, and the database can be persisted if a file db is used instead of a db in memory.
If an external library is acceptable, pandas has similar functionality and is an awesome package.
-10086312 0 Launch home screen chooserI have defined my app as home screen but I have to change the home screen during my app execution. I know it is not possible to change the home screen, it is only possible to launch the home screen selector. How could I launch the home screen selector when I need to do it?
I'm using:
PackageManager pm = getPackageManager(); pm.clearPackagePreferredActivities("com.dm.prado");
I have two problems:
The selector is only showed when I press home button, I want to show it when I want.
The selector is never showed again when I Selecthome screen first time
-39414088 0 Is stack memory only for pointers and heap for objects?Firstly, I'm currently working in C# and I've been reading up on memory management. So far, I've read through some great answers on stack overflow explaining the difference between stack memory and the managed heap memory. The majority of the answers state that by declaring:
int x = 5
, you're allocating enough memory for the type of x
within the stack memory.
I understand how this works as well as the scope of it, however when I read the explanation of heap memory, it confused me.
If you're saying int x = 5
, since int
is an alias of System.Int32
, wouldn't x
technically be a pointer to a new instance of the System.Int32
struct? And if so, wouldn't it then be stored in the heap memory since that's used for instance objects.
In this tutorial, it states (for the line class1 cls1 = new class1()
):
... creates a pointer on the stack and the actual object is stored in a different type of memory location called ‘Heap’.
System.String
, System.Int64
, System.Boolean
, System.Decimal
etc.Like this.
CmdString = "insert into Team_table (name1, name2, result1, result2)" + "(select t1.name,t2.name,NULL,NULL from teams t2 cross join teams t1)";
-9266902 0 Without seeing your stack trace, I'm only guessing, but:
From the line you say is the error, it means that div
is null, which would indicate that the previous line is the culprit, which would mean that your doc
has no Element with an Id of eventTTL
.
Try ensuring that your doc
is valid, and the it actually has a eventTTL
.
i am trying to use cshtml with Durandal
i followed instructions on http://bartwullems.blogspot.com/2014/03/durandaljs-enable-razor-views.html
main.js is called properly but when it goes looking for the view i get the error.
View Not Found. Searched for "views/shell" via path "text!views/shell.cshtml".
and in the console window i can see a 404 error
http:// local /App/views/shell.cshtml 404 (Not Found)
route is configured and i copied the web.config from View to App/views and the DurandalViewController is also in place. my main.js looks like one in the example just the last line is
app.setRoot('viewmodels/shell');
__________________________________
Structure has
Do this:
$cats = get_the_category(); if(count($cats)){ $cat = $cats[0]; $cat = sprintf('<a href="%s" id="cat-%s">%s</a>',get_category_link($cat->cat_ID), $cat->cat_ID, $cat->cat_name ); }
-31721470 0 Try Like this :
userAccountApp.controller('getCtrl', function($scope,dataSer) { dataSer.Users.query(function(data){ console.log(data) }) })
Write your logic inside callback function.
-6892968 0 Insert data from custom PHP function into MySQL databaseI'm having problems inserting a particular line of code into my MySQL database. It inserts three rows just fine, but the "html_href" row isn't going in for whatever reason. Here is my code:
function html_path() { $title = strtolower($_POST['title']); // convert title to lower case $filename = str_replace(" ", "-", $title); // replace spaces with dashes $html_href = $filename . ".html"; // add the extension }
And my MySQL query code:
$query = "INSERT INTO work (title, logline, html_href, synopsis) VALUES"; $query .= "('".mysql_real_escape_string($_POST['title'])."',"; $query .= "'".mysql_real_escape_string($_POST['logline'])."',"; $query .= "'".html_path()."',"; $query .= "'".mysql_real_escape_string($_POST['synopsis'])."')"; $result = mysql_query($query);
The title, logline, and synopsis values go in just fine, but the html_href()
function inserts a blank row.
I use this function on all field assignments that may contain '
Function EscapeQuote(ByVal msData As Object) As String Return (Replace(msData, "'", "''")) End Function e.g. values ('" & EscapeQuote(TextBox1.Text) & "')"
-6990135 0 What other hidden variables (pre-defined using macros) do I have access to in g++? note: I am using g++ version 4.3.4
So I was learning about assert statements and came across a homebrew assert macro that uses that variables __LINE__
and __FILE__
which (cleverly) give the line number and the file name from where they were called -- in this case, from where the assertation failed. These are epic pieces of information to have!
I was able to infer that the variable __FUNCTION__
will give you the function name that you are inside of... amazing!! However, when assert.h is at work, you also get the arguments to the function (i.e. function: int main(int, char**)
and all I can do currently is get the function name...
Generally speaking, where can I learn more about these wonderful hidden variables and get a complete list of all of them?
p.s. I guess I understand now why you aren't supposed to use variable names starting with __
The library itself compiles without any problem, but when I try and compile a binary and link it against it I get the following error
What's the link command line?
You're probably believe that you're passing in the library too early so the linker has already processed it before it gets around to needing that definition.
-8458877 0That's because artist.picture
returns an XMLList object. Try the following code :
var artist:XML = new XML(event.result); artistPic.source = String(artist.picture[0]); lblArtistName.text = artist.name; // This one is probably transtyped automagically by Flex.
-32225971 0 in my case I enter submodule directory without doing
git submodule init
git submodule update
So git was linked to the parent folder that indeed missed that branch.
-8434601 0If you start a process, then you'll be its parent.
Maybe you could try to start your process from cmd.exe instead, so cmd.exe will be the parent.
Process proc = Process.Start(new ProcessStartInfo { Arguments = "/C explorer", FileName = "cmd", WindowStyle = ProcessWindowStyle.Hidden });
-2547979 0 jQuery Validation plugin results in empty AJAX POST I have tried to solve this issue for at couple of days with no luck. I have a form, where I use the validation plugin, and when I try to submit it, it submits empty vars. Now, if I remove the validation, everything works fine. Here is my implementation:
$(document).ready(function(){ $("#myForm").validate({ rules: { field1: { required: true, minlength: 5 }, field2: { required: true, minlength: 10 } }, messages: { field1: "this is required", field2: "this is required", }, errorLabelContainer: $("#validate_msg"), invalidHandler: function(e, validator) { var errors = validator.numberOfInvalids(); if (errors) { $("#validate_div").show(); } }, onkeyup: false, success: false, submitHandler: function(form) { doAjaxPost(form); } }); }); function doAjaxPost(form) { // do some stuff $(form).ajaxSubmit(); return false; }
As I wrote this does not work when I have my validation, BUT if I remove that, and just add an
onsubmit="doAjaxPost(this.form); return false";
to my HTML form, it works - any clue???
-24122159 0I found the solution!
it was simpler than it seems! just use comma (,) as seprator!
https://itunes.apple.com/lookup?id=1st_APP_ID,2nd_APP_ID,3rd_APP_ID
-8325747 0 Rather than compressing images, you'd better compress video streams. This is how video codec achieve high compression : by exploiting similarities into consecutives images in the stream.
If you compress your images one by one, you loose this performance advantage, and it makes a huge difference in bandwidth.
-33437271 0 How to make a linked component peerDepdencies use the equivalent node_modules of the script being linked to?peerDependencies
behave in version 3).webpack-dev-server
to run "game" app.react
and react-dom
are dependencies of game
app and peerDependencies
of the player
component.I would like to link player
component to game
app.
I have done:
cd /player npm link cd /game npm link player
When I run webpack-dev-server
program, I get the following error message:
Hash: 09968e7401389f50049f Version: webpack 1.12.2 Time: 339ms chunk {0} app.js, 0.14192ce06d8b6f8abb91.hot-update.js, app.css (app) 2.32 MB + 576 hidden modules ERROR in ../player/index.js Module not found: Error: Cannot resolve module 'react' in /player @ ../player/index.js 21:13-29
How do I make player
component to use game
./node_modules
for the peerDependences
?
I have a table containing huge amount of data I decided to do the partitioning on that table But I am getting some sort of issues please clarify them.
I have an identity column as a primary key ID (int type).
I have done the partitioning by the date column making it also primary key with the combination of ID + date
.
Problem is that I am not able to insert the records in partitioning tables because the partitioning view is not able to insert the data due to the identity constraint. Please help Me.
-8711742 0I work for InMobi. It's really easy to do this in PHP. First up, our tutorials are at http://developer.inmobi.com/wiki/index.php?title=PHP
To display your own code when InMobi doesn't return an advert is simple.
// Use the MkhojAd.php file supplied require_once("MkhojAd.php"); // Use your unique Site ID $base = new MkhojAd("12345678901234567890"); $base->set_num_of_ads(1); if($base->request_ads()) { // The top ad echo $base->fetch_ad(); } else // No Advert Returned { // Your Alternative Advert Here }
-19172950 0 how to send HTTP Post request using jersey with a complex parameter I need to send a HTTP Post to a REST API with the following complex type as parameters. I looked at the documentation of jersey and it helps only to send a key value pair. How can i send a HTTP Post request with the below parameters using jersey.
{ "key": "example key", "message": { "html": "<p>Example HTML content</p>", "text": "Example text content", "subject": "example subject", "from_email": "message.from_email@example.com", "from_name": "Example Name", "to": [ { "email": "recipient.email@example.com", "name": "Recipient Name" } ], "headers": { "Reply-To": "message.reply@example.com" }, "important": false, "track_opens": null, "track_clicks": null, "auto_text": null, "auto_html": null, "inline_css": null, "url_strip_qs": null, "preserve_recipients": null, "view_content_link": null, "bcc_address": "message.bcc_address@example.com", "tracking_domain": null, "signing_domain": null, "return_path_domain": null, "merge": true, "global_merge_vars": [ { "name": "merge1", "content": "merge1 content" } ], "merge_vars": [ { "rcpt": "recipient.email@example.com", "vars": [ { "name": "merge2", "content": "merge2 content" } ] } ], "tags": [ "password-resets" ], "subaccount": "customer-123", "google_analytics_domains": [ "example.com" ], "google_analytics_campaign": "message.from_email@example.com", "metadata": { "website": "www.example.com" }, "recipient_metadata": [ { "rcpt": "recipient.email@example.com", "values": { "user_id": 123456 } } ], "attachments": [ { "type": "text/plain", "name": "myfile.txt", "content": "ZXhhbXBsZSBmaWxl" } ], "images": [ { "type": "image/png", "name": "IMAGECID", "content": "ZXhhbXBsZSBmaWxl" } ] }, "async": false, "ip_pool": "Main Pool", "send_at": "example send_at" }
I looked at the other questions of sending HTTP Post using Jersey and all I could find was a way to only send a key\value
pairs as parameters and not complex string types like above.
I am new to AngularJS 2 (and Javascript for that matter). I've written an AngularJS 2 service which returns an array of users. The data is retrieved from an HTTP call which returns the data in JSON format. When logging the JSON data returned from the HTTP call, I can see that this call is successful and the correct data is returned. I have a component which calls the service to get the users and an HTML page which displays the users. I cannot get the data from the service to the component. I suspect I am using the Observable incorrectly. Maybe I'm using subscribe incorrectly as well. If I comment out the getUsers call in the ngInit function and uncomment the getUsersMock call, everything works fine and I see the data displayed in the listbox in the HTML page. I'd like to convert the JSON data to an array or list of Users in the service, rather then returning JSON from the service and having the component convert it.
Data returned from HTTP call to get users:
[ { "firstName": "Jane", "lastName": "Doe" }, { "firstName": "John", "lastName": "Doe" } ]
user.ts
export class User { firstName: string; lastName: string; }
user-service.ts
... @Injectable export class UserService { private USERS: User[] = [ { firstName: 'Jane', lastName: 'Doe' }, { firstName: 'John', lastName: 'Doe' } ]; constructor (private http: Http) {} getUsersMock(): User[] { return this.USERS; } getUsers(): Observable<User[]> { return Observable.create(observer => { this.http.get('http://users.org').map(response => response.json(); }) } ...
user.component.ts
... export class UserComponent implements OnInit { users: User[] = {}; constructor(private userService: UserService) {} ngOnInit(): void { this.getUsers(); //this.getUsersMock(); } getUsers(): void { var userObservable = this.userService.getUsers(); this.userObservable.subscribe(users => { this.users = users }); } getUsersMock(): void { this.users = this.userService.getUsersMock(); } } ...
user.component.html
... <select disabled="disabled" name="Users" size="20"> <option *ngFor="let user of users"> {{user.firstName}}, {{user.lastName}} </option> </select> ...
!!! UPDATE !!!
I had been reading the "heroes" tutorial, but wasn't working for me so I went off and tried other things. I've re-implemented my code the way the heroes tutorial describes. However, when I log the value of this.users, it reports undefined.
Here is my revised user-service.ts
... @Injectable export class UserService { private USERS: User[] = [ { firstName: 'Jane', lastName: 'Doe' }, { firstName: 'John', lastName: 'Doe' } ]; constructor (private http: Http) {} getUsersMock(): User[] { return this.USERS; } getUsers(): Promise<User[]> { return this.http.get('http://users.org') .toPromise() .then(response => response.json().data as User[]) .catch(this.handleError); } ...
Here is my revised user.component.ts
... export class UserComponent implements OnInit { users: User[] = {}; constructor(private userService: UserService) {} ngOnInit(): void { this.getUsers(); //this.getUsersMock(); } getUsers(): void { this.userService.getUsers() .then(users => this.users = users); console.log('this.users=' + this.users); // logs undefined } getUsersMock(): void { this.users = this.userService.getUsersMock(); } } ...
!!!!!!!!!! FINAL WORKING SOLUTION !!!!!!!!!! This is all the files for the final working solution:
user.ts
export class User { public firstName: string; }
user.service.ts
import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/catch'; import 'rxjs/add/operator/map'; import { User } from './user'; @Injectable() export class UserService { // Returns this JSON data: // [{"firstName":"Jane"},{"firstName":"John"}] private URL = 'http://users.org'; constructor (private http: Http) {} getUsers(): Observable<User[]> { return this.http.get(this.URL) .map((response:Response) => response.json()) .catch((error:any) => Observable.throw(error.json().error || 'Server error')); } }
user.component.ts
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { User } from './user'; import { UserService } from './user.service'; @Component({ moduleId: module.id, selector: 'users-list', template: ` <select size="5"> <option *ngFor="let user of users">{{user.firstName}}</option> </select> ` }) export class UserComponent implements OnInit{ users: User[]; title = 'List Users'; constructor(private userService: UserService) {} getUsers(): void { this.userService.getUsers() .subscribe( users => { this.users = users; console.log('this.users=' + this.users); console.log('this.users.length=' + this.users.length); console.log('this.users[0].firstName=' + this.users[0].firstName); }, //Bind to view err => { // Log errors if any console.log(err); }) } ngOnInit(): void { this.getUsers(); } }
-6697738 0 The #{...} are markers for spel interpreter in xml context.
I don't undestand : ${#code}/${#value}
. Good is #{code/value}
, as I understand things, if code and value are id.
So, if you want a spel expression without interpret it, put string code/value
in xml.
When you change your submit to this it won't submit if RequiredFields returns false
.
<input type="submit" value="Login" onsubmit="return RequiredFields();"/>
-10392488 0 You need an instance of an object that implements Runnable
to pass to the Thread constructor; the call new HelloRunnable()
gives that to you.
You need a Thread object to run; the call to new Thread()
gives that to you.
You call start()
on that new Thread
instance; it calls the run()
method on the Runnable
instance you gave to its constructor.
There is a class chart for Qt 4.3 here:
http://doc.qt.digia.com/extras/qt43-class-chart.pdf
I'm not aware of any class charts for more recent versions than that.
-2391478 0 Can't read the value of a button click from a userformI hope this is a relatively easy problem although I have spent hours websearching and using T&E to no avail. Hopefully someone can help ;o)
I have an excel module that shows a UserForm to get some input data before doing a lot of processing. At the bottom of the userform are a couple of command buttons labeled "OK" and Cancel". I need to be able to have the user change option buttons then click on OK or Cancel to exit, where my module will continue the process based on whether or not "Cancel" was pressed. I just can't seem to find a way to read a Boolean result from pressing the Cancel button on the form. I'm 99% sure it's some kind of Public / Private referencing error, but I haven't earned enough experience to figure it out yet. Here is the code snippets:
(From Module1)
Sub ModuleName() Dim State as Boolean ' Display Parameter box UserForm2.Show If UserForm2.ButtonCancel Then State = True Else State = False End If End Sub
Based on the True or False from the Cancel, I can drive the rest of the procedure.
(UserForm2 Code)
Private Sub ButtonCancel_Click() BtnCancel = True Unload Me End Sub Private Sub ButtonOK_Click() BtnCancel = False Unload Me End Sub Private Sub ButtonReset_Click() 'Set the Default Settings NEAlias.Value = "True" NoteIgnore.Value = "True" ABIgnore.Value = "True" LinkIgnore.Value = "True" End Sub Private Sub UserForm_Initialize() Dim BtnCancel As Boolean 'Add the Text to the options NEIgnore.Caption = "Ignore" NoteIgnore.Caption = "Ignore" ABIgnore.Caption = "Ignore" LinkIgnore.Caption = "Ignore" NEAlias.Caption = "Alias Only" NoteAlias.Caption = "Alias Only" ABAlias.Caption = "Alias Only" LinkAlias.Caption = "Alias Only" NEMove.Caption = "Move and Alias" NoteMove.Caption = "Move and Alias" ABMove.Caption = "Move and Alias" LinkMove.Caption = "Move and Alias" 'Set the Default Settings NEAlias.Value = "True" NoteIgnore.Value = "True" ABIgnore.Value = "True" LinkIgnore.Value = "True" End Sub
That's it. It looks like it should be simple but I'm stumped. TIA for any help!
-2180370 0There appear to be a number of ways to achieve this but many seem a bit out of date or overly complicated. As of Feb 1 2010 all I did to get PHP and Apache2 working on Gentoo was to install Apache and PHP like this:
bash$ emerge apache
bash$ echo "dev-lang/php apache2" >> /etc/portage/package.use
bash$ echo "dev-lang/php mysql" >> /etc/portage/package.use
bash$ emerge dev-lang/php
and restart Apache with the /etc/init.d/apache2 script. PHP should now be available.You can look into the stats here. Have anyone experienced some API to get the Pageview Stats? Furthermore, I have also looked into the available Raw Data but could not find the solution to extract the Pageview Count.
-3014262 0 Sharepoint DeploymentI am creating an .STP for a site. But here I have a DLL file in BIN , a XAP file in 12 Hive Folder and few more custom entries in teh Web.Config. How do I include there in the .STP File? When I say IncludeContent when I create a .STP file for the Site , then also the above said things are not getting included.
-21537588 0No, you can't forcefully close a connection in a clear way from the peripheral side. There is no API for it.
You can break the connection abruptly by not responding to a request, which results in disconnection at most after 30 seconds. This is the standard behavior defined by the Bluetooth specification Vol.3 Part F 3.3.3
-5417391 0 How to integrate Admeris Payment Systems in joomla?A transaction not completed within 30 seconds shall time out. Such a transaction shall be considered to have failed and the local higher layers shall be informed of this failure. No more attribute protocol requests, commands, indica- tions or notifications shall be sent to the target device on this ATT Bearer.
How to integrate Admeris Payment Systems in joomla?
-18877453 0Why not extend the helper?
Create a class in app/View/Helper/myTimeHelper.php
. In there add the reference to the old class you'll be extended like:
App::uses('TimeHelper', 'View/Helper'); class myTimeHelper extends TimeHelper { public function niceShort(<whatever input the original is getting>) { // your new logic for the things you want to change // and/or a return TimeHelper::niceShort(<whatever>) for the cases that are //fine as they are. If you don't need that then you can remove App::uses. }
Finally you can have your helper imported as myTime
with
public $helpers = array('myTime');
or even change the default Time
to call myTime
so you don't need to change anything else in your already written code:
public $helpers = array('Time' => array('className' => 'myTime'));
-27719093 0 When this occurred to me, the reason for the error was that there was a corrupt index in the terrier folder, that was created because I ran indexing without running setup first.
Delete all files from the var/index subfolder in Terrier home directory.
Then it may work normally.
-13974721 0I developed a set of configurable utility functions for Riak mapreduce in Erlang. As I wanted to be able to specify sets of critera, I decided to allow the user to pass configuration in as a JSON document as this works well for all client types, although other text representations should also work. Examples of how these functions are used from curl are available in the README.markdown file.
You can pass an argument to each individual map or reduce phase function through the 'arg' parameter. Whatever you specify here will be passed on as the final parameter to the map or reduce phase, see the example below:
"query":[{"map":{"language":"erlang","module":"riak_mapreduce_utils", "function":"map_link","keep":false, "arg":"{\"bucket\":\"master\"}"}},
-41064624 0 Open href in link only after certain events have executed I have a link to the Tumblr share widget, and need to append some query string params to it before it opens (triggered by clicking on the link). However, the link opens before these params are appended, I think because it takes a few seconds-- I'm sending an image on the page to be hosted on imgur and returning that URL.
Is there any way to delay the new link from being opened until AFTER my new image url is returned??? I've tried using e.preventDefault();
and return false;
but haven't had any luck.
My HTML is:
<button id='tumblrshare'>tumblr</button $('body').on('click','#tumblrshare',function(e){ var svg = $("#svg")[0]; svg.toDataURL("image/png", { callback: function(img) { var img = img.replace("data:image/png;base64,", ""); var imgurTitle = $("meta[property='og:title']").attr("content"); $.ajax({ url: 'https://api.imgur.com/3/image', headers: {'Authorization': 'Client-ID **********'}, type: 'POST', data: {'image': img, 'type': 'base64', 'title': imgurTitle}, success: function(result) { imageURL = result.data.link; window.location = 'https://www.tumblr.com/widgets/share/tool?canonicalUrl=http://www.example.com&caption=mycaption&posttype=photo&content=' + imageURL; }, error: function(){ console.log('error'); } }); //ajax }//callback });//svg }); //tumblrshare
Please help!!
-26117708 0There is no PRINT
command. Use raise notice
instead.
create function f() returns void as $$ begin FOR i IN 1..10 LOOP raise notice '%', i; -- i will take on the values 1,2,3,4,5,6,7,8,9,10 within the loop END LOOP; end; $$ language plpgsql;
http://www.postgresql.org/docs/current/static/plpgsql.html
-4506330 0 How to Install Ruby on Rails on a Fresh Ubuntu 10.10 System?There are a lot of tutorials on how to install Ruby on Rails on Ubuntu 10.10. But even following the steps, there will be some errors and dependencies that you will encounter. The system varies on the developer's setup. To make it uniform, installation must be on a fresh Ubuntu 10.10 system.
Is there a step-by-step guide on how to install RoR on a Fresh Ubuntu 10.10 machine? Like the first thing I need to do after booting up the system and starting the terminal?
Cheers, Ben
-24917822 0when you select the view and click on the attributes inspector see that background color property change the color you want.And also the attributes inspector click on the view show at the left side may be this hide so you can't see anything in the inspector area.
-10712101 0You reference the host control with the outerDocument
property... so you would call outerDocument.DP_PRAT_INIT
if you want to access that array. BUT, that array is private, so you have to make it public. Or, you can make a public function that you can call on outerDocument
but ... yuck.
If I am understanding your code properly, you should access the data
property of the GridItemRenderer
which is the same as outerDocument.DP_PRAT_INIT[ddlTuVous.selectedIndex]
except that it is better because you don't have possible index mismatches...
So, what you really want is:
data.prTuVous = ddlTuVous.selectedItem;
-4088990 0 I would place lightweight proxy in front of media server like nginx. This would allow you to do load balancing AND any restrictions you need (you may only allow certain IPs on certain URLs).
-20617002 0It's a bitwise Or, if you have binary values it or's each of them together
00010110 10110000 --------- 10110110
For each bit, the output will have a 0
, if both of the corresponding input's bits have a 0
. If either or both input's bits have a 1
, it will output 1
in that slot.
It's kinda like an ||
, except it checks on each individual bit, instead of the whole number.
In your case
The way your particular example what you're doing is encoding 2 conditions into a single value, has to do with masking.
Suppose InputType.TYPE_CLASS_TEXT
was equal to 8
or 00001000
And suppose InputType.TYPE_TEXT_VARIATION_PASSWORD
was equal to 32
or 00100000
InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD
would be equal to 00101000
or 40
.
When you want to read them, you use bitwise anding. It's the exact opposite of oring. IT returns true only if both values are 1.
00010110 10110000 --------- 00010000
To check if your value contains a result, you simply and
it to the type
00101000 - 40 - Your result 00001000 - 8 - InputType.TYPE_CLASS_TEXT -------- 00001000 - 8 - this means that your result contains `InputType.TYPE_CLASS_TEXT`
in code, the check might look like this.
if(myInputType & InputType.TYPE_CLASS_TEXT != 0) //myinput type cointains TYPE_CLASS_TEXT
-37496393 0 <android.support.v4.widget.NestedScrollView android:id="@+id/nested_scrollbar" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="fill_vertical" app:layout_behavior="@string/appbar_scrolling_view_behavior" android:scrollbars="none" > <LinearLayout android:id="@+id/nested_scrollbar_linear" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" > <android.support.v7.widget.CardView android:id="@+id/flexible.example.cardview" android:layout_width="match_parent" android:layout_height="wrap_content"> </android.support.v7.widget.CardView> <android.support.v7.widget.RecyclerView android:id="@+id/list_view" android:layout_width="match_parent" android:layout_height="wrap_content" app:layout_behavior="@string/appbar_scrolling_view_behavior" /> </LinearLayout> </android.support.v4.widget.NestedScrollView>
and apply .setNestedScrollingEnabled
to recyclerview
and set it to false
P.s: for Api lower 21 :
ViewCompat.setNestedScrollingEnabled(recyclerView, false);
You were almost there
^([1-9]|1[0-5])$
is what you need
The only change i made in your regex [9]{1,1}
to [1-9]
..no need of {1,1}
since its already matching 1 time in [9]
The triangle can be generated by the following syntax:
<b class="caret dropdown-toggle"></b>
-40100910 0 What is the impact of async action method on IIS? I need help in understanding how async action method can improve performance of IIS (and eventually my application).
First I tried to create Server Unavailable (503) with following code and setup
Sent 20 requests with SOAP UI and when tried from the browser, the browser showed 503, which is what I expected.
Then I made following changes in code
Sent 20 requests again with SOAP UI and when tried from the browser, the browser again showed 503, which I wasnt expecting.
Wouldn't the async and await release the thread to accept new connections?
Is my understanding correct on following
I don't know why my block isn't showing up. It's not showing up on any page, and I cleared the cache. Can someone help me figure out what I missed? However, the var_dump('test')
shows up!
app/design/frontend/default/default/template/justin/head.phtml
testing this block
Justin/Bieber/Block/Sings.php
class Justin_Bieber_Block_Sings extends Mage_Core_Block_Template { protected function _construct() { parent::_construct(); var_dump("test"); } }
config.xml
<frontend> ... <layout> <updates> <bieber> <file>justin.xml</file> </bieber> </updates> </layout> </frontend> <global> <blocks> <bieber> <class>Justin_Bieber_Block</class> </bieber> </blocks> ... </global>
app/design/frontend/default/default/layout/justin.xml
<?xml version="1.0"?> <layout version="0.1.0"> <default> <reference name="head"> <block type="bieber/bieber" name="justin_bieber"> <action method="setTemplate"> <template>justin/head.phtml</template> </action> </block> </reference> </default> </layout>
-17102270 0 How to solve the exception of type 'System.Net.WebException' occurred while running app? I want to connect windows phone with remote server.
I trying to connect that time the below error occurred. How to solve it.
An exception of type 'System.Net.WebException' occurred in System.Windows.ni.dll and wasn't handled before a managed/native boundary
Here mycode
C# code
ProgressIndicator prog;
private void btnLogin_Click(System.Object sender, System.Windows.RoutedEventArgs e) { try { string url = "http://192.168.2.112/check_login/check.php"; //string url = "http://localhost/sam.php"; Uri uri = new Uri(url, UriKind.Absolute); StringBuilder postData = new StringBuilder(); postData.AppendFormat("{0}={1}", "sUsername", HttpUtility.UrlEncode(this.txtUsername.Text)); postData.AppendFormat("&{0}={1}", "sPassword", HttpUtility.UrlEncode(this.txtPassword.Password.ToString())); WebClient client = default(WebClient); client = new WebClient(); client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded"; client.Headers[HttpRequestHeader.ContentLength] = postData.Length.ToString(); client.UploadStringCompleted += client_UploadStringCompleted; client.UploadProgressChanged += client_UploadProgressChanged; client.UploadStringAsync(uri, "POST", postData.ToString()); } catch (Exception ex) { MessageBox.Show(ex.Message); } prog = new ProgressIndicator(); prog.IsIndeterminate = true; prog.IsVisible = true; prog.Text = "Loading...."; SystemTray.SetProgressIndicator(this, prog); } private void client_UploadProgressChanged(object sender, UploadProgressChangedEventArgs e) { //Me.txtResult.Text = "Uploading.... " & e.ProgressPercentage & "%" } private void client_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e) { if (e.Cancelled == false & e.Error == null) { prog.IsVisible = false; MessageBox.Show(e.Result.ToString()); } }
PHP code
<?php $hostname_localhost ="localhost"; $database_localhost ="androidlogin"; $username_localhost ="root"; $password_localhost =""; $localhost=mysql_connect($hostname_localhost,$username_localhost,$password_localhost) or trigger_error(mysql_error(),E_USER_ERROR); mysql_select_db($database_localhost, $localhost); $username = $_POST['username']; $password = $_POST['password']; $query_search = "select * from user where username = '".$username."' AND password = '".$password. "'"; $query_exec = mysql_query($query_search) or die(mysql_error()); $rows = mysql_num_rows($query_exec); //echo $rows; if($rows == 0) { echo "No Such User Found"; } else { echo "User Found"; } ?>
Please help me. Thanks in advance.
-7837479 0Just override the newView Method:
public class MyCursorAdapter extends CursorAdapter { private final LayoutInflater inflater; private ContentType type; public MyCursorAdapter (Context context, Cursor c) { super(context, c); inflater = LayoutInflater.from(context); } @Override public void bindView(View view, Context context, Cursor cursor) { if( cursor.getString(cursor.getColumnIndex("type")).equals("type1") ) { // get elements for type1 } else { // get elements for type1 } } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { if( cursor.getString(cursor.getColumnIndex("type")).equals("type1") ) { final View view = inflater.inflate(R.layout.item_type1, parent, false); } else { final View view = inflater.inflate(R.layout.item_type2, parent, false); } return view; }
-36558086 0 You could loop through the AOT using the TreeNode class and select elements where the label property is blank. Then you can send the information out to the infolog or whatever you wish.
There are numerous code examples out there of how to do that, such as this one looping over forms selecting on the HTMLHelpTopic property.
-31969451 0You missed last }
braces for loop. You put key
as string it need to concadinate with +
symbol like the below code.
var data = { Name : "name", Price : 50 }; var modalId ='hai'; for(var key in data){ if (data.hasOwnProperty(key)) { console.log($('#'+modalId).find('input[name='+key+']')); console.log($('#'+modalId).find('textarea[name='+key+']')); console.log($('#'+modalId).find('select[name='+key+']')); } }
-8471060 0 want to pass value using ref in c# but its not working like I think it should Maybe what I want to do is just the wrong way of going about it. But i am trying to write a game debug printer thing. It is to write values to the screen in a sprite font for various things i tell the debugger to care about. My debugger class is simple , but it seems that in c# things are getting passed by value not reference. So I turn to the ref keyword, which seems to work okay if I pass in the right data type. The issue is that I have this method signature:
Dictionary<String, object> debugStrings = new Dictionary<String, object>(); ... ... public void addVariable(String index, ref object obj) //i think it needs to be a reference, not so sure though. { debugStrings.Add(index, obj); }
This adds to the dictionary a variable to ultimately print to the screen along with a key for it to be known as.
The problem though arises when I try to use the above method:
debugPrinter.addVariable("myrotationvalue", ref this.Rotation);
as per the link in the comment I changed the code above to:
this.Rotation = 4; object c = (object)this.Rotation; this.Rotation = 20; level.dbgd.addVariable("playerrot", ref c); //always prints 4 out, i guess it still is not passing by reference?
So it doesn't give an error but always prints out 4. Not sure how I will ever get the reference to work.
Again on another edit took the references out:
this.Rotation = 20; level.dbgd.addVariable("playerrot", this.Rotation); this.Rotation = 4; //should draw to screen 4, doesn't draws 20
I apparently this is harder than I thought it would be a simple little fun class to work up before I hit the hay, ha ha ha... this is not boding well for the monday to come.
Full class:
namespace GameGridTest.GameGridClasses.helpers { public class DebugDrawer : DrawableGameComponent { Dictionary<String, object> debugStrings = new Dictionary<String, object>(); int currentX; int currentY; VictoryGame _game; private SpriteBatch spriteBatch; private SpriteFont spriteFont; public DebugDrawer(VictoryGame game) : base(game) { _game = game; currentX = _game.Window.ClientBounds.Width - 400; //draw the debug stuff on right side of screen currentY = 5; } protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); spriteFont = _game.Content.Load<SpriteFont>("fonts\\helpers\\fpsFont"); } public void addVariable<T>(String index, AbstractDebugHandler<T> obj) //i think it needs to be a reference, not so sure though. { debugStrings.Add(index, obj); } public void removeVariable(String index) { debugStrings.Remove(index); } protected override void UnloadContent() { _game.Content.Unload(); } public override void Update(GameTime gameTime) { } public override void Draw(GameTime gameTime) { spriteBatch.Begin(); foreach (object obj in debugStrings) //draw all the values { spriteBatch.DrawString(spriteFont, obj.ToString(), new Vector2(currentX, currentY), Color.White); currentY += 30; } currentY = 5; spriteBatch.End(); } } public abstract class AbstractDebugHandler<T> { public AbstractDebugHandler(T obj) { InnerObject = obj; } public T InnerObject { get; private set; } public abstract string GetDebugString(); } public class ThisDebugHandler: AbstractDebugHandler<object>{ public ThisDebugHandler(object innerObject) : base(innerObject){ } public override GetDebugString(){ return InnerObject.Rotation; //?? } } }
-5640101 0 Edit
I just found this jQuery plugin - http://markdalgleish.com/projects/tmpload/ Does exactly what you want, and can be coupled with $.tmpl
I have built a lightweight template manager that loads templates via Ajax, which allows you to separate the templates into more manageable modules. It also performs simple, in-memory caching to prevent unnecessary HTTP requests. (I have used jQuery.ajax here for brevity)
var TEMPLATES = {}; var Template = { load: function(url, fn) { if(!TEMPLATES.hasOwnProperty(url)) { $.ajax({ url: url, success: function(data) { TEMPLATES[url] = data; fn(data); } }); } else { fn(TEMPLATES[url]); } }, render: function(tmpl, context) { // Apply context to template string here // using library such as underscore.js or mustache.js } };
You would then use this code as follows, handling the template data via callback:
Template.load('/path/to/template/file', function(tmpl) { var output = Template.render(tmpl, { 'myVar': 'some value' }); });
-6798214 0 yes, I tried with hex capable ones...but I m still getting an empty window.Is there any best editor u may suggest though?
It sounds like the files may really be empty apart from that \000
character; i.e. you've completely trashed them. You can confirm this by looking at the file sizes as reported by the operating system.
If you have trashed the files, and it is unlikely that NetBeans can get the old contents back. You will need to restore latest versions the files from version control (SVN, GIT, whatever you are using) or from a file system backup. If that doesn't work you might be able to recover them with a file recovery tool, but I doubt it.
The lessons is to make sure your source files are safely in version control or backed up before you use some code generator to update them.
-39460320 0I just had a problem where it was showing markers but not the lines. I ended up solving it by wrapping the expression in a CInt() to convert it to an integer.
-16504716 0I don't think that is due to memory leak. It has happened to me too when I tried to copy only the compiled executable but not depend libraries. So just check whether all depend libraries are available in other systems too.
-276242 0If the problem domain is hard (and AI problems can often be hard), then I'd choose a language which is expressive or suited to the domain first, and then worry about speeding it up second. For example, Ruby has meta-programming primitives (ability to easily examine and modify the running program) which can make it very easy/interesting to implement certain types of algorithms.
If you implement it in that way and then later need to speed it up, then you can use benchmarking/profiling to locate the bottleneck and either link to a compiled language for that, or optimise the algorithm. In my experience, the biggest performance gain is from tweaking the algorithm, not from using a different implementation language.
-3811678 0 Add two variables using jqueryvar a = 1; var b = 2; var c = a+b;
c will show as 12
; but I need 3
How do I do it using jQuery?
-33556341 0You are looking for consecutive values. Here is one way, using a difference of row numbers to identify a group:
with t as (<your query here>) select min(term_start), max(term_end), block, quantity from (select t.*, (row_number() over (partition by block order by position) - row_number() over (partition by quantity, block order by position) ) as grp from t ) t group by quantity, grp, block;
-27828373 0 Prevent jQuery .load() if hash is visited I am loading pages within a content div
with .load()
function and using window.onhashchange
event to detect if the user is navigated.
window.onhashchange = function() { hash(window.location.hash.replace('#', '')) }
and
function hash(s) { $('.panel-body').fadeOut(100).load(s+'.php').fadeIn(100) }
Some of the pages takes long to load everytime. I don't want them to be reloaded (bypass .load()
function) if the state is already cached. Any workaround?
There is no built-in NSString method available to do what you want. You need to write your own method. Objective-C does let you "extend" classes with new methods to cover cases like this.
This is how I would do it:
@interface NSString(Extend) -(NSInteger)proximity:(NSString*)otherString; @end @implementation NSString(Extend) -(NSInteger)proximity:(NSString*)otherString { NSUInteger length = [otherString length]; if(length != [self length]) return -1; NSUInteger k; NSUInteger differences = 0; for(k=0;k<length;++k) { unichar c1 = [self characterAtIndex:k]; unichar c2 = [otherString characterAtIndex:k]; if(c1!=c2) { ++differences; } } return differences; } @end
Then in my code at the place I wanted to check I would say something like
-11551794 0 multiply two decimalsIm trying to add a tax field. I have this working for whole numbers but i need to be able to enter ".5" I have no clue haw to solve this problem maybe its because of the isNAN but i thought this would be ok here.
http://jsfiddle.net/thetylercox/eeMva/3/
My current code
$(document).ready(function() { calculateSum(); $(".txt").keyup(function() { $(".txt").each(function() { calculateSum(); }); }); }); $("#tax").keyup(function() { $('#total1').val(parseInt($(this).val()) * parseInt($('#subtotal').val())); ); function calculateSum() { var sum = 0; $("#sum").val(sum.toFixed(2)); //iterate through each textboxes and add the values $(".txt").each(function() { //add only if the value is number if (!isNaN(this.value) && this.value.length != 0) { sum += parseFloat(this.value); } }); $("#sum").html(sum.toFixed(2)); var subtotal = document.getElementById("subtotal").value == ""; var subtotal = document.getElementById("subtotal").value = sum; function getTax(tax) { var taxFloat = parseFloat(tax) if (isNaN(taxFloat)) { return 1; } else { return taxFloat; } } var total = getTax($('#tax').val()) * sum; var total1 = document.getElementById("total1").value = total; }
Thanks
-1777429 0select a.articleid, count(c.*) as commentcount from articles a left join articlecomments c on a.articleid = c.articleid where a.categoryid = @categoryid group by a.articleid
-35040251 0 Facebook API Lead Ad webhook lead retrieval I have setup a webhook for Facebook Lead Ads
It is receiving data like this:
{"object":"page","entry":[{"id":"718196074978224","time":1453818316,"changes":[{"field":"leadgen","value":{"ad_id":"399579767903","adgroup_id":"971076277715","created_time":1453789516,"form_id":"930912320812","leadgen_id":"151977133461","page_id":"718196074978224"}}]}]}
The next step is to retrieve the details.
The docs say https://graph.facebook.com/v2.5/ but if I use the leadgen_id (151977133461) this returns "singular published story API is deprecated for versions v2.4 and higher"
I've also read that _ might work, but that returns a different error.
-13274720 0 Handle Trailing slashes at the end of URLThere is clear cut advantage of using consistent URL structure for wordpress website.
I want all of my URL's to end with / (the homepage and internal page URL's). Let me give an example website which is handling it very efficiently so that the URL's without ending with slash or ending with multiple slashes are 301 redirected to URL with single slash.
http://viralpatel.net/blogs
301 redirect to viralpatel.net/blogs/
http://viralpatel.net/blogs//
301 redirect to viralpatel.net/blogs/
http://viralpatel.net/blogs/
200 OK
http://viralpatel.net/blogs/check-string-is-valid-date-java
301 redirect to http://viralpatel.net/blogs/check-string-is-valid-date-java/
http://viralpatel.net/blogs/check-string-is-valid-date-java//
301 redirect to http://viralpatel.net/blogs/check-string-is-valid-date-java/
http://viralpatel.net/blogs/check-string-is-valid-date-java/
200 OK
Any idea what .htaccess rules can help achieve this. My current .htaccess looks like:
RewriteEngine On RewriteCond %{HTTP_HOST} ^javaexperience.com [NC] RewriteRule ^(.*)$ http://www.javaexperience.com/$1 [R=301,L] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L]
-19631331 0 Subtracting dates I have the following code:
SELECT t2.Owner, a.accNumber, a.Rest, dateadd(day,1,MIN(a.Date)), MIN(b.Date) FROM t1 a LEFT JOIN t1 b ON a.accNumber=b.accNumber LEFT JOIN t1 ON a.accountId = t2.accountId WHERE a.Date<b.Date AND a.Rest<>0 AND a.accNumber=b.accNumber GROUP BY a.accNumber, a.Rest, t2.Owner ORDER BY t2.Owner
I want to subtract dates in 5 and 4th column (MIN(b.Date) - dateadd(day,1,MIN(a.Date)))
and put it as 6th column, but simple DATEDIFF(day, dateadd(day,1,MIN(a.Date)), MIN(b.Date))
doesn't work because of LEFT JOINs.
This is how it should look like. with current code, I can see only first 5 columns, I want to see 6th column either
This is how it looks like when I add DATEDIFF(day, 4, 5)
to Select statement
I have a service which has a method that's called when a certain controller method is triggered.
My service returns a custom result object PlacementResult in which I want to communicate errors that may have happened (validation) back to the controller method.
Should PlacementResult have a ModelState or a ModelStateDictionary to communicate errors back to the controller (and finally view)? How would I string this together?
Finally, how do I get the ModelState/ModelStateDictionary (whichever you tell me I should choose) back into the view (highlighting the appropriate text box, show the error message etc.)?
Thank you !
-22182198 0While for this example it might be overkill here is a way to extend the TListView class with a SelectedItem property that is enumerable with a for-in loop.
In cases where the condition inside the loop might be more complex than just checking a property or by actually providing a filter delegate this can be very powerful.
type TSelectedListItemsEnumerator = class(TListItemsEnumerator) public function MoveNext: Boolean; end; TSelectedListItemsEnumerable = record private FListItems: TListItems; public constructor Create(AListItems: TListItems); function GetEnumerator: TSelectedListItemsEnumerator; end; TListViewHelper = class helper for TListView private function GetSelectedItems: TSelectedListItemsEnumerable; public property SelectedItems: TSelectedListItemsEnumerable read GetSelectedItems; end; { TSelectedListItemsEnumerator } function TSelectedListItemsEnumerator.MoveNext: Boolean; begin repeat Result := inherited; until not Result or Current.Selected; end; { TSelectedListItemsEnumerable } constructor TSelectedListItemsEnumerable.Create(AListItems: TListItems); begin FListItems := AListItems; end; function TSelectedListItemsEnumerable.GetEnumerator: TSelectedListItemsEnumerator; begin Result := TSelectedListItemsEnumerator.Create(fListItems); end; { TListViewHelper } function TListViewHelper.GetSelectedItems: TSelectedListItemsEnumerable; begin Result := TSelectedListItemsEnumerable.Create(Items); end;
You can then use it like this:
procedure TForm1.Button1Click(Sender: TObject); var item: TListItem; begin for item in ListView1.SelectedItems do begin ShowMessage(item.Caption); end; end;
-18683913 0 Solved it, there is a method in the CCDrawNode class, with which you can paint a dot:
CCDrawNode *oneRedPixelA = [[CCDrawNode alloc] init]; CGPoint positionA = CGPointMake(aLabel.contentSize.width * aLabel.anchorPoint.x, aLabel.contentSize.height * aLabel.anchorPoint.y); [oneRedPixelA drawDot:positionA radius:3.0f color:ccc4f(1.0f, 0.0f, 0.0f, 0.5f)]; [aLabel addChild:oneRedPixelA z:500];
-14426030 0 If you get this error message when you run your graphics program: BGI Error: Graphics not initialized (use 'initgraph')
Just you need to copy the \tc\bgi\EGAVGA.BGI file to your local folder where you are running the application.
-673569 0WPF supports two different flavors of focus:
The FocusedElement
property gets or sets logical focus within a focus scope. I suspect your TextBox
does have logical focus, but its containing focus scope is not the active focus scope. Ergo, it does not have keyboard focus.
So the question is, do you have multiple focus scopes in your visual tree?
-11426706 0I can't reproduce your problem here with Bash 4.2.29.
However, did you know that read
will join lines with \
newline continuations by default?
read rule < <(cpp -P -w -undef -nostdinc -C -M file.cc) echo "${rule##*:}"
Or, in a more sh
-compatible way (I think),
cpp -P -w -undef -nostdinc -C -M file.cc | { read rule echo "${rule##*:}" }
-10822559 0 Check out WSGen or you can add ?WSDL to the end of your JAX-WS endpoint to get the generated WSDL. This way all you have to do is create your JAX-WS annotated classes similar to your JAX-RS ones and the WSDL is generated and it should be able to handle your XJC generated objects with no problems.
http://metro.java.net/guide/ch02.html#create-a-metro-web-services-endpoint
-793569 0 Loading user profile from a serviceIn a service, I try to use the following code to launch a program :
HANDLE hPipe; HANDLE hToken; PROFILEINFO stProfileInfo; char szUserName[64]; DWORD dwUserNameSize = 64; // Take the identity of the client ImpersonateNamedPipeClient(hPipe); // Retrieve the user name (DOMAIN\USER) GetUserNameEx(NameSamCompatible,szUserName,&dwUserNameSize); // Get the impersonation token OpenThreadToken(GetCurrentThread(),TOKEN_ALL_ACCESS,TRUE,&hToken); // Load the user's profile ZeroMemory(&stProfileInfo,sizeof(PROFILEINFO)); stProfileInfo.dwSize = sizeof(PROFILEINFO); stProfileInfo.dwFlags = PI_NOUI; stProfileInfo.lpUserName = szUserName; LoadUserProfile(hToken,&stProfileInfo);
Unfortunately, the call to LoadUserProfile
fail with GetLastError=5 (access denied)
. In userenv.log, I can find this :
USERENV LoadUserProfile: Yes, we can impersonate the user. Running as self USERENV LoadUserProfile: Entering, hToken = <0xc8>, lpProfileInfo = 0xb30aa4 USERENV LoadUserProfile: lpProfileInfo->dwFlags = <0x1> USERENV LoadUserProfile: lpProfileInfo->lpUserName = <MYDOMAIN\USERNAME> USERENV LoadUserProfile: NULL central profile path USERENV LoadUserProfile: NULL default profile path USERENV LoadUserProfile: NULL server name USERENV LoadUserProfile: Failed to enable the restore privilege. error = c0000022 USERENV LoadUserProfile: Returning FALSE. Error = 5
Of course, I checked that my service (running as SYSTEM) has the SE_RESTORE_NAME
(and SE_BACKUP_NAME
) privileges enabled.
Any help would be greatly appreciated !
-8132413 0 C# incrementing static variables upon instantiationI have a bankAccount object I'd like to increment using the constructor. The objective is to have it increment with every new object the class instantiates.
Note: I've overriden the ToString() to display the accountType and accountNumber;
Here is my code:
public class SavingsAccount { private static int accountNumber = 1000; private bool active; private decimal balance; public SavingsAccount(bool active, decimal balance, string accountType) { accountNumber++; this.active = active; this.balance = balance; this.accountType = accountType; } }
Why is it that when I plug this in main like so:
class Program { static void Main(string[] args) { SavingsAccount potato = new SavingsAccount(true, 100.0m, "Savings"); SavingsAccount magician = new SavingsAccount(true, 200.0m, "Savings"); Console.WriteLine(potato.ToString()); Console.WriteLine(magician.ToString()); } }
The output I get does not increment it individually i.e.
savings 1001 savings 1002
but instead I get:
savings 1002 savings 1002
How do I make it to be the former and not the latter?
-12913892 0 Play! framework: no data receivedthis is a route I defined:
GET /user/:id controllers.Users.show(id: Long)
this is the handler (in Users
class) for this GET requset:
public static Result show(long id) { return ok("hello " + id); }
I get this error:
No data received Unable to load the webpage because the server sent no data. Here are some suggestions: Reload this webpage later. Error 324 (net::ERR_EMPTY_RESPONSE): The server closed the connection without sending any data.
this is weird because it's the only page with this problem and everything seems to be normal.
so why is it happening?
I'm trying to modify an element in jQuery programmatically, i.e. a number in docID increments up to a maximum number. I'm replacing text on a series of images on a page from Download to View. If I use #ctl00_cphMainContent_dlProductList_ct100_ctl00_lnkProofDownload
instead of docID
in the $(docID).text(...)
part of the code, the text gets replaced correctly. When I use the docID
variable in its place, it doesn't work.
What am I doing wrong here?
Thanks.
var max = 10; var count = 100; var s1 = "#ctl00_cphMainContent_dlProductList_ct"; var s2 = "_ctl00_lnkProofDownload"; var docID = ""; for (i = 1; i <= max; i++) { docID = s1.concat (count++, s2); $(document).ready(function() { $(docID).text(function(i, oldText) { return oldText === 'Download' ? 'View' : oldText; }); }); }
This is the HTML code that is being modified. The word Download is replaced by View.
<a id="ctl00_cphMainContent_dlProductList_ctl00_ctl00_lnkProofDownload" href="../../../Controls/StaticDocProof.ashx?qs=op/5WlcUxeg849UT973Mwf0ZnNcMLfe3JYAe7EnJORsdyETYV1vcKaj0ROc2VrN5fXfYjO2MM6BUYXzX2UKmog==" >Download</a>
-5952731 0 Or add border-collapse: collapse;
to the table's CSSs.
Have a look at this post to see some suggested tips for dealing with memory leaks under windows. Have a scroll down, don't just look at the first answer. In particular it may be worth considering the DEBUG_NEW macro-based solution discussed by the second answer. Given that boost asio is largely header-only, this should help you even if the offending allocations come from the boost library.
-15955179 0If the other suggestions don't work, it may be a problem with your terminal. My gnome-terminal on Ubuntu was scrolling much slower than PuTTY with the same file.
If you're using Ubuntu's default gnome-terminal, you might want try another terminal program. urxvt both worked for me (terminator had similar problems):
$ sudo apt-get install rxvt-unicode $ urxvt
The major downside is that it doesn't look very good. You can try the advice here to make it look a bit better
References:
Edit: It seems that the real solution for me may be to stop full-screening my terminal when using vim.
-35149839 0 fe_sendauth: no password supplied on pgadmin IIII am getting the above error when I am creating a DB using pgadminIII
.
As per the answers related to the previous answers, what I should do is in my pg_hba.conf
, update the peer
section to trust
for user postgres
, but in my pg_hba.conf
there are 3 users with name postgres
.
# Allow replication connections from localhost, by a user with the # replication privilege. #local replication postgres peer #host replication postgres 127.0.0.1/32 md5 #host replication postgres ::1/128 md5
Which one I should update?
-5335850 0When user launch the application you could show a splash screen for 1 or 2 second after that you could show the progress (status) of your application using text msg.
for example "Initialization of Synchronization Service" ,"Storing to data base", "Loading map" .
The above text msg. is just a reference,you could have more descriptive text to show on screen along with progress bar.
-13957112 0 Use Two Different columns to compare to another worksheetI have two columns that are different from each other. One containing numbers and the other containing text. Trying to compare (match) both to another separate worksheet.
Of course, I can VLookup each one separatedly but that doesn't give me the answer I'm looking for. I want to know if the first two columns correlate with the other worksheet.
I also tried an IF(VLookup but probably did it wrong.
To sum it up. If Column A and Column B are both on the other worksheet, then True or False.
-39440144 0'x'
does not interpolate the x
variable into the string. You need to do something like this:
xpathName = "/html/body/div[2]/table/tbody/tr[%d]/td[4]//text()" % (x,) xpathTime = "/html/body/div[2]/table/tbody/tr[%d]/td[9]//text()" % (x,)
Also, as @grael mentioned, you need to terminate your loop somewhere.
-14329898 0 what happens when converting char to string? (Java)Possible Duplicate:
How do I compare strings in Java?
I'm using String.valueOf to convert char to string. But the return value seems not exactly same as a string of the same letter. Codes below:
String myString = "s"; char myChar = 's';//both string and char are assigned as letter 's' String stringFromChar = String.valueOf(myChar); if (myString == stringFromChar) { out.println("equal"); } else { out.println("not equal"); }
Every time it prints not equal. Please help, thanks! :)
-22340661 0You forgot to mention the "columns" attribute in the Class Meta. Please follow the mechanism currently used by Horizon to render the "Instances" data table. You can find the detailed step by step tutorial to create and render a data table here: http://docs.openstack.org/developer/horizon/topics/tutorial.html
Hope it helps
-29427271 0 GPU related issues in SDL gameWe've been trying to get a port of mkxp to android. It uses SDL 2 and opengl es 2. The game works perfectly on Mali GPUs, but doesn't work as expected on PowerVR and is completely broken on Adreno. Is there any work around? Is it, for example, possible to completely bypass hardware acceleration and use software rendering, because some parts (eg the backgrounds etc.) work on all devices. I'm a beginner, so please don't mind any foolish question :)
-25067540 0You could use a counter
System.out.println("Who do you want to remove?");
String name = input.nextLine(); int remove_index = -1; for(int i=0; i<contacts.length; i++){ Contact c = contacts[i]; if(c.getName().equals(name)){ remove_index =i; } }
-31145840 0 Ok, funny, as Ganesh R. rightly pointed out: It does not work with Visual Studio 2013 anymore.
So I switched to Mingw and,...perfect!
-18930830 0load() function loads only the html part of the file. So if you want datas from database just echo it
-35867140 0The Go Programming Language Specification
The empty statement does nothing.
EmptyStmt = .
The syntax is specified using Extended Backus-Naur Form (EBNF):
Production = production_name "=" [ Expression ] "." . Expression = Alternative { "|" Alternative } . Alternative = Term { Term } . Term = production_name | token [ "…" token ] | Group | Option | Repetition . Group = "(" Expression ")" . Option = "[" Expression "]" . Repetition = "{" Expression "}" .
Productions are expressions constructed from terms and the following operators, in increasing precedence:
| alternation () grouping [] option (0 or 1 times) {} repetition (0 to n times)
Lower-case production names are used to identify lexical tokens. Non-terminals are in CamelCase. Lexical tokens are enclosed in double quotes "" or back quotes ``.
The form a … b represents the set of characters from a through b as alternatives. The horizontal ellipsis … is also used elsewhere in the spec to informally denote various enumerations or code snippets that are not further specified. The character … (as opposed to the three characters ...) is not a token of the Go language.
The empty statement is empty. In EBNF (Extended Backus–Naur Form) form: EmptyStmt = .
or an empty string.
For example,
for { } var no if true { } else { no = true }
-9020390 0 If you're happy to take javascript's word for it that the level has been completed then just set a cookie from javascript.
an operation that can't be simulated by the user
Sorry - but if it's javascript which dtermines when they've completed the level then there's nothing to stop the user falsifying the results.
-3380939 0The problem is that server side redirection is only redirecting your inner app frame instead of redirecting the whole page, and Facebook doesn't like displaying their system dialogs inside frames.
You would need some client side redirection, probably something along those lines:
<script> <?php if($doRedirect) { echo 'top.location="http://redirect_url";'; } ?> </script>
-15252672 0 How to set a custom route value so that only members with the Admin role can access my elmah.axd page in MVC3 I need to set a custom route value so that you are forced to go to
site/admin/elmah.axd
In my web.config I have:
<location path="elmah.axd"> <system.web> <authorization> <allow roles="Admin" /> <deny users="*" /> </authorization> </system.web> </location>
Plus all the other pertinent elmah settings. If I remove that section I can just type:
site/elmah.axd
But I only want Admin's to be able to access this page.
I have an admin page that you login and if you are in the Admin Role then you should be redirected to elmah.axd
public AdminController(IRepository<User> userRepository) { _userRepository = userRepository; } // // GET: /Admin/ public ActionResult Index() { return View(Constants.Admin); } public ActionResult AdminLogin(string SSN) { var user = _userRepository.FindBy(x => x.UserName == SSN).SingleOrDefault(); if (UserIsAnAdmin(user)) { return RedirectToRoute("/elmah.axd"); } return View(Constants.DeniedAccess); }
I have a route value in my Global.asax file that I need help with.
routes.MapRoute( "mocklogin", "{controller}/{action}", // URL with parameters new { controller = "MockLogin", action = "Index" } // Parameter defaults ); routes.MapRoute( "elmah.axd", "{controller}/{action}", // URL with parameters ); routes.MapRoute( "Default", // Route name "{controller}/{action}", // URL with parameters //need something here redirecting to the elmah.axd page );
Is there a way to redirect the page to the /elmah.axd page on my site.
In the end I want to go to the Admin page of my site and when I click submit if the User is an admin I want to redirect to the elmah.axd page. Otherwise I go to my custom error page. I need to somehow get the ssn on the controller call the conditional and if true redirect to elmah.axd. How do I redirect to elmah.axd in MVC?
-28418617 0 copydb - How to create index in background?I'm doing a lot of stuff with big databases in MongoDB
and sometimes there's a need in making a copy of database where copydb
command fits perfectly, however it does add global lock for whole mongod
instance at the end of process for creating index.
I know that there's an argument to create index in background "background:true", but I didn't find such argument for copydb
command (or copydatabase
).
Is there way to avoid global lock and force background index creation for Copy Database?
-163599 0 How to sell the benefits of "good code" to management?I work for a very small company (~70 total w/ 10 actual programmers) with a relatively large (1M LOC in C++) application that is in need of some serious TLC. Because of the size of the company we are driven primarily by what we can sell to customers with literally no time given for maintenance of the code other than fixing the bugs that cause things to fail, and not always fixing them well. Apparently this is how the company has worked for the past 10 years!
How do I convince management that what they are doing is actually costing them money/time/productivity? What kinds of active maintenance strategies exist? Which are good for small companies with scarce resources?
-6609627 0I depends on your style, but one advantage of returning: you could call populate(o).doSomethingElse();
, i.e. you can chain method calls.
Have a look at how StringBuilder
does that for example, which allows things like this new StringBuilder().append("a").append("b")....
I believe gmch's answer should solve the original question. However, not all pthread implementations include pthread_barrier_t
and the related functions (as they are an optional part of the POSIX threads specs), so here is the custom barrier implementation I mentioned in a comment to the original question.
(Note that there are other ways to suspend/resume threads asynchronously, during normal operation, and without co-operation from the threads themselves. One way to implement that is to use one or two realtime signals, and a signal handler that blocks in sigsuspend()
, waiting for the complementary "continue" signal. The controlling thread will have to use pthread_kill()
or pthread_sigqueue()
to send the pausing and continuing signals to each thread involved. The threads are minimally affected; aside from possible EINTR
errors from blocking syscalls (as signal delivery interrupts blocking syscalls), the threads just don't do any progress -- just as if they weren't scheduled for a while. Because of that, there should not be any issues with respect to the threads getting paused and continued at slightly different times. If you are interested in this method, leave a comment, and I could try and show an example implementation of that, too.)
Perhaps this will be of use to someone else needing a pause-able custom barrier implementation, or perhaps as a basis of their own custom barrier.
Edited to add DRAINING
mode, when threads are expected to quit. In your worker loop, use do { ... } while (!barrier_wait(&barrier));
barrier.h:
#ifndef BARRIER_H #define BARRIER_H #include <pthread.h> #include <errno.h> typedef enum { INVALID = -1, RUNNING = 0, PAUSED = 1, DRAINING = 2 } barrier_state; typedef struct { pthread_mutex_t mutex; pthread_cond_t cond; barrier_state state; int threads; /* Number of participants */ int waiting; /* Number of participants waiting */ } barrier; /** barrier_drain() - Mark barrier so that threads will know to exit * @b: pointer to barrier * @ids: pthread_t's for the threads to wait on, or NULL * @retvals: return values from the threads, or NULL * This function marks the barrier such that all threads arriving * at it will return ETIMEDOUT. * If @ids is specified, the threads will be joined. * Returns 0 if successful, errno error code otherwise. */ static int barrier_drain(barrier *const b, pthread_t *const ids, void **const retvals) { int result, threads; void *retval; if (!b || b->threads < 0) return errno = EINVAL; result = pthread_mutex_lock(&b->mutex); if (result) return errno = result; b->state = DRAINING; pthread_cond_broadcast(&b->cond); threads = b->threads; b->threads = 0; pthread_mutex_unlock(&b->mutex); while (threads-->0) { result = pthread_join(ids[threads], &retval); if (result) return errno = result; if (retvals) retvals[threads] = retval; } return errno = 0; } /** barrier_pause() - Mark barrier to pause threads in the barrier * @b: pointer to barrier * This function marks the barrier such that all threads arriving * in it will wait in the barrier, until barrier_continue() is * called on it. If barrier_continue() is called before all threads * have arrived on the barrier, the barrier will operate normally; * i.e. the threads will continue only when all threads have arrived * at the barrier. * Returns 0 if successful, errno error code otherwise. */ static int barrier_pause(barrier *const b) { int result; if (!b || b->threads < 1) return errno = EINVAL; result = pthread_mutex_lock(&b->mutex); if (result) return errno = result; if (b->state != PAUSED && b->state != RUNNING) { pthread_mutex_unlock(&b->mutex); return errno = EPERM; } b->state = PAUSED; pthread_mutex_unlock(&b->mutex); return errno = 0; } /** barrier_continue() - Unpause barrier * @b: Pointer to barrier * This function lets the barrier operate normally. * If all threads are already waiting in the barrier, * it lets them proceed immediately. Otherwise, the * threads will continue when all threads have arrived * at the barrier. * Returns 0 if success, errno error code otherwise. */ static int barrier_continue(barrier *const b) { int result; if (!b || b->threads < 0) return errno = EINVAL; result = pthread_mutex_lock(&b->mutex); if (result) return errno = result; if (b->state != PAUSED) { pthread_mutex_unlock(&b->mutex); return errno = EPERM; } b->state = RUNNING; if (b->waiting >= b->threads) pthread_cond_broadcast(&b->cond); pthread_mutex_unlock(&b->mutex); return errno = 0; } /** barrier_wait() - Wait on the barrier * @b: Pointer to barrier * Each thread participating in the barrier * must call this function. * Callers will block (wait) in this function, * until all threads have arrived. * If the barrier is paused, the threads will * wait until barrier_continue() is called on * the barrier, otherwise they will continue * when the final thread arrives to the barrier. * Returns 0 if success, errno error code otherwise. * Returns ETIMEDOUT if the thread should exit. */ static int barrier_wait(barrier *const b) { int result; if (!b || b->threads < 0) return errno = EINVAL; result = pthread_mutex_lock(&b->mutex); if (result) return errno =result; if (b->state == INVALID) { pthread_mutex_unlock(&b->mutex); return errno = EPERM; } else if (b->state == DRAINING) { pthread_mutex_unlock(&b->mutex); return errno = ETIMEDOUT; } b->waiting++; if (b->state == RUNNING && b->waiting >= b->threads) pthread_cond_broadcast(&b->cond); else pthread_cond_wait(&b->cond, &b->mutex); b->waiting--; pthread_mutex_unlock(&b->mutex); return errno = 0; } /** barrier_destroy() - Destroy a previously initialized barrier * @b: Pointer to barrier * Returns zero if success, errno error code otherwise. */ static int barrier_destroy(barrier *const b) { int result; if (!b || b->threads < 0) return errno = EINVAL; b->state = INVALID; b->threads = -1; b->waiting = -1; result = pthread_cond_destroy(&b->cond); if (result) return errno = result; result = pthread_mutex_destroy(&b->mutex); if (result) return errno = result; return errno = 0; } /** barrier_init() - Initialize a barrier * @b: Pointer to barrier * @threads: Number of threads to participate in barrier * Returns 0 if success, errno error code otherwise. */ static int barrier_init(barrier *const b, const int threads) { int result; if (!b || threads < 1) return errno = EINVAL; result = pthread_mutex_init(&b->mutex, NULL); if (result) return errno = result; result = pthread_cond_init(&b->cond, NULL); if (result) return errno = result; b->state = RUNNING; b->threads = threads; b->waiting = 0; return errno = 0; } #endif /* BARRIER_H */
The logic is quite simple. All threads waiting in the barrier wait on the cond
condition variable. If the barrier operates normally (state==RUNNING
), the final thread arriving at the barrier will broadcast on the condition variable instead of waiting on it, thus waking up all other threads.
If the barrier is paused (state==PAUSED
), even the final thread arriving at the barrier will wait on the condition variable.
When barrier_pause()
is called, the barrier state is changed to paused. There may be zero or more threads waiting on the condition variable, and that is okay: only the final thread arriving at the barrier has a special role, and that thread cannot have yet arrived. (If it had, it'd have emptied the barrier already.)
When barrier_continue()
is called, the barrier state is changed to normal (state==RUNNING
). If all threads are waiting on the condition variable, they are released by broadcasting on the condition variable. Otherwise, the final thread arriving at the barrier will broadcast on the condition variable and release the waiting threads normally.
Note that barrier_pause()
and barrier_continue()
do not wait for the barrier to become full or to drain. It only blocks on the mutex, and the functions only hold it for very short periods at a time. (In other words, they may block for a short time, but will not wait for the barrier to reach any specific situation.)
If the barrier is draining (state==DRAINING
), threads arriving at the barrier return immediately with errno==ETIMEDOUT
. For simplicity, all the barrier functions now unconditionally set errno (to 0 if success, errno code if error, ETIMEDOUT
if draining).
The mutex
protects the barrier fields so that only one thread may access the fields at once. In particular, only one thread can arrive at the barrier at the same time, due to the mutex.
One complicated situation exists: the loop body the barrier is used in might be so short, or there might be so many threads, that threads start arriving at the next iteration of the barrier even before all threads from the previous iteration have left it.
According to POSIX.1-2004, pthread_cond_broadcast()
"shall unblock all threads currently blocking on the specified condition variable". Even though their wakeups will be sequential -- as each one will acquire the mutex in turn --, only those threads that were blocked on it when pthread_cond_broadcast()
was called will be woken up.
So, if the implementation follows POSIX semantics with respect to condition variables, woken threads can (even immediately!) re-wait on the condition variable, waiting for the next broadcast or signal: the "old" and "new" waiters are separate sets. This use case is actually quite typical, and all POSIX implementations I've heard of do allow that -- they do not wake up threads that started waiting on the condition variable after the last pthread_cond_broadcast()
.
If we can rely on POSIX condition variable wakeup semantics, it means the above barrier implementation should work reliably, including in the case where threads arrive at the barrier (for the next iteration), even before all threads (from the previous iteration) have left the barrier.
(Note that the known "spurious wakeups" issue only affects pthread_cond_signal()
; i.e. when calling pthread_cond_signal()
more than one thread may be woken up. Here, we wake up all threads using pthread_cond_broadcast()
. We rely on it only waking current waiters, and not any future waiters.)
Here is a POSIX.1-2001 implementation for suspending and resuming threads asynchronously, without any co-operation from the target thread(s).
This uses two signals, one for suspending a thread, and another for resuming it. For maximum compatibility, I did not use GNU C extensions or POSIX.1b realtime signals. Both signals save and restore errno
, so that the impact to the suspended threads would be minimal.
Note, however, that the functions listed in man 7 signal, "Interruption of system calls and library functions by signal handlers" section, after the "The following interfaces are never restarted after being interrupted by a signal handler" paragraph, will return errno==EINTR
when suspended/resumed. This means you will have to use the traditional do { result = FUNCTION(...); } while (result == -1 && errno == EINTR);
loop, instead of just result = FUNCTION(...);
.
The suspend_threads()
and resume_threads()
calls are not synchronous. The threads will be suspended/resumed either before, or sometime after, the function calls return. Also, suspend and resume signals sent from outside the process itself may affect the threads; it depends on if the kernel uses one of the target threads to deliver such signals. (This approach cannot ignore signals sent by other processes.)
Testing indicates that in practice, this suspend/resume functionality is quite reliable, assuming no outside interference (by sending signals caught by the target threads from another process). However, it is not very robust, and there are very few guarantees on its operation, but it might suffice for some implementations.
suspend-resume.h:
#ifndef SUSPEND_RESUME_H #define SUSPEND_RESUME_H #if !defined(_POSIX_C_SOURCE) && !defined(POSIX_SOURCE) #error This requires POSIX support (define _POSIX_C_SOURCE). #endif #include <signal.h> #include <errno.h> #include <pthread.h> #define SUSPEND_SIGNAL SIGUSR1 #define RESUME_SIGNAL SIGUSR2 /* Resume signal handler. */ static void resume_handler(int signum, siginfo_t *info, void *context) { /* The delivery of the resume signal is the key point. * The actual signal handler does nothing. */ return; } /* Suspend signal handler. */ static void suspend_handler(int signum, siginfo_t *info, void *context) { sigset_t resumeset; int saved_errno; if (!info || info->si_signo != SUSPEND_SIGNAL) return; /* Save errno to keep it unchanged in the interrupted thread. */ saved_errno = errno; /* Block until suspend or resume signal received. */ sigfillset(&resumeset); sigdelset(&resumeset, SUSPEND_SIGNAL); sigdelset(&resumeset, RESUME_SIGNAL); sigsuspend(&resumeset); /* Restore errno. */ errno = saved_errno; } /* Install signal handlers. */ static int init_suspend_resume(void) { struct sigaction act; sigemptyset(&act.sa_mask); sigaddset(&act.sa_mask, SUSPEND_SIGNAL); sigaddset(&act.sa_mask, RESUME_SIGNAL); act.sa_flags = SA_RESTART | SA_SIGINFO; act.sa_sigaction = resume_handler; if (sigaction(RESUME_SIGNAL, &act, NULL)) return errno; act.sa_sigaction = suspend_handler; if (sigaction(SUSPEND_SIGNAL, &act, NULL)) return errno; return 0; } /* Suspend one or more threads. */ static int suspend_threads(const pthread_t *const identifier, const int count) { int i, result, retval = 0; if (!identifier || count < 1) return errno = EINVAL; for (i = 0; i < count; i++) { result = pthread_kill(identifier[i], SUSPEND_SIGNAL); if (result && !retval) retval = result; } return errno = retval; } /* Resume one or more threads. */ static int resume_threads(const pthread_t *const identifier, const int count) { int i, result, retval = 0; if (!identifier || count < 1) return errno = EINVAL; for (i = 0; i < count; i++) { result = pthread_kill(identifier[i], RESUME_SIGNAL); if (result && !retval) retval = result; } return errno = retval; } #endif /* SUSPEND_RESUME_H */
Questions?
-29159976 0I would recommend posting to the Register method and based on the value of the selected option, redirect to the relevant view to complete the details. The users table could have a (say) IsRegistrationComplete
field which is marked as true
only when the 2nd form has been saved.
To do this in one view, you will need a view model with properties for the Register
model, Owner
model, ServiceCompany
model and selected option.
View model
public class RegistrationVM { public RegisterVM Register { get; set; } public OwnerVM Owner { get; set; } public ServiceCompanyVM ServiceCompany { get; set; } [Required] public string CompanyType { get; set; } }
Controller
public ActionResult Register() { RegistrationVM model = new RegistrationVM(); model.Register = new RegisterVM(); return View(model); } public ActionResult Register(RegistrationVM model) { // Either Owner or ServiceCompany properties will be populated } public PartialViewResult CreateOwner() { var model = new RegistrationVM(); model.Owner = new OwnerVM(); return PartialView(model); } public PartialViewResult CreateServiceCompany() { var model = new RegistrationVM(); model.ServiceCompany = new ServiceCompany(); return PartialView(model); }
Notes: The partial views should not contain a <form>
element (it will be inserted inside the <form>
tag of the main view). The model in the partial views needs to be RegistrationVM
so the controls are correctly prefixed and can be bound on post back (e.g. <input name="Owner.SomeProperty" ../>
etc)
View
@model RegistrationVM @using(Html.BeginForm()) { <section> // render controls for the register model <section> <section> @Html.RadioButtonFor(m => m.CompanyType, "owner",new { id = "owner" }) <label for="owner">Owner</label> @Html.RadioButtonFor(m => m.CompanyType, "service",new { id = "service" }) <label for="service">Service Company</label> @Html.ValidationMessageFor(m => m.CompanyType) <button id="next" type="button">Next</button> <section> <section id="step2"></section> <input id="submit" type="submit" /> // style this as hidden }
Then add a script to handle the Next
button which validates the existing controls, gets the value of the selected service, uses ajax to load the relevant form, re-parses the validator and displays the submit button
var form = $('form'); $('#next').click(function() { // Validate what been entered so far form.validate(); if (!form.valid()) { return; // correct errors before proceeding } // Get selected type and update DOM var type = $('input[name="CompanyType"]:checked').val(); if (type == "owner") { $('#step2').load('@Url.Action("CreateOwner")'); } else { $('#step2').load('@Url.Action("CreateServiceCompany")'); } // Re-parse validator so client side validation can be applied to the new controls form.data('validator', null); $.validator.unobtrusive.parse(form); // Show submit button $('#submit').show(); });
-2917207 0 In your view code for the 'new' action use FormHelper tags that reference the same model as your create action eg.
<%= text_field :user, :login %>
Then in your create action, use a model instance with the same name:
@user = User.new # detect error, redirect to 'new'
The FormHelper will use the value of this instance if it is available.
-21518370 0Since Bootstrap is a library, they realize that some people will not want to use classes from Bootstrap, but will want to use the mixins. By keeping the separation, a user can import mixins.less
and apply .clearfix()
into their own code under their own class name(s), without it actually creating an output of a .clearfix
class itself. At the same time, if one wants to use the whole Bootstrap library, they want to provide an actual class by the name .clearfix
for users of the whole library.
The enctype
should be on the <form>
element
<form method="POST" enctype="multipart/form-data"> <input type="file" name="uploaded" style="margin-bottom: 10px"> </form>
PHP:
<?php echo $_FILES['uploaded']['type'] ?>
-7712897 0 What is the best way to implement dynamic CSS & SVG values (PHP)? I'm working a rudimentary system for holding pages on a number of domains. I intend to populate values in a DB and use these values to produce a page.
The values I'd use would include colour values which I'd like to then inject in to the CSS file and an SVG file.
Currently I'm thinking of using .htaccess to process .css/.svg as PHP and drop the values in from there, but is there a more efficient/elegant way without having to process these file formats as PHP?
All advice appreciated.
Many thanks.
-18877882 0 draw rectangle in JpanelI am trying to get my hands on GUI programming in java and wanted to draw a rectangle in Jpanel. Code does not give any error but I cannot get rectangle in the GUI. Can somebody please tell me what I am missing in the following code. I am sure it is pretty simple so please be gentle.
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class HelloWorldGUI2 { private static class ButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { System.exit(0); } } private static class RectDraw extends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g); g.drawRect(230,80,10,10); g.setColor(Color.RED); g.fillRect(230,80,10,10); } } public static void main(String[] args) { JPanel content = new JPanel(); RectDraw newrect= new RectDraw(); JButton okButton= new JButton("OK"); JButton clearButton= new JButton("Clear"); ButtonHandler listener= new ButtonHandler(); okButton.addActionListener(listener); clearButton.addActionListener(listener); content.add(okButton); content.add(clearButton); content.add(newrect); JFrame window = new JFrame("GUI Test"); window.setContentPane(content); window.setSize(250,100); window.setLocation(100,100); window.setVisible(true); } }
-32105327 0 Right answer would be declaring a common base class or interface but you said "I tried polymorphism, but". I do not know what (or how) did you try but assuming,
ToModel()
methodYou can do
var type = _projectService.GetTaskTypeById(id); dynamic task; switch (type) { case "MS": task = _projectService.GetMSTaskById(id); break; case "TL": task = _projectService.GetTLTaskById(id); break; case "ET": task = _projectService.GetETTaskById(id); break; default: throw new NotSupportedException("Unsupported Task Type: " + type); } task.ToModel();
-33727775 0 I would recommend to just do it in code for full control and additional possibilities later on.
Simply set the background color of the concerned tableview. In your case that would be something like this:
self.navigationController.view.backgroundColor = [UIColor whiteColor];
-958228 0 OrderBy returns a new IEnumerable, so you need to do something like:
IEnumerable<Data> results = query.OrderBy(item => item.GetType().GetProperty(sortExpressions[i].Name));
-15963402 0 Bulktransfer returns -1 First let me state that I am brand new to Android Development so maybe USB is a bit complex for a first app but it is my only reason for wanting to write an app in the first place.
I would like to communicate to a Garmin GPS over USB. I have done so in the past with success from the PC but it was via a driver supplied by Garmin.
As far as I am aware there is no such driver for Android so I need to write directly to the USB.
Garmin publishes this documentation:
http://www8.garmin.com/support/pdf/USBAddendum.pdf
Basically it says you must transmit on bulk out: 00 00 00 00 05 00 00 00 00 00 00 00
to tell the device to prepare for a transfer. When I do so, my bulktransfer fails with -1. If I have a 0 for the timeout then bulktransfer never returns. I assume becuase there is no response from the gps.
I have included my code below. The code detects the GPS and opens it. But the first bulktransfer never completes. I am certain I am sending to the bulk out endpoint. Can anyone get me started?
public class MainActivity extends Activity { private static final String TAG = "TestGarmin"; private UsbManager mUsbManager; private UsbDevice mDevice; private UsbDeviceConnection mConnection; private UsbEndpoint mEndpointIntr; private UsbEndpoint mEndpointBulkOut; private UsbEndpoint mEndpointBulkIn; private static int TIMEOUT = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mUsbManager = (UsbManager)getSystemService(Context.USB_SERVICE); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } public void onResume() { super.onResume(); Intent intent = getIntent(); Log.d(TAG, "intent: " + intent); String action = intent.getAction(); String s = UsbManager.ACTION_USB_DEVICE_ATTACHED; UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE); if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) setDevice(device); } private void setDevice(UsbDevice device) { Log.d(TAG, "setDevice " + device); if (device.getInterfaceCount() != 1) { Log.e(TAG, "could not find interface"); return; } UsbInterface intf = device.getInterface(0); // device should have three endpoints if (intf.getEndpointCount() != 3) { Log.e(TAG, "could not find endpoint"); return; } // endpoint 0 should be of type interrupt UsbEndpoint ep0 = intf.getEndpoint(0); if (ep0.getType() != UsbConstants.USB_ENDPOINT_XFER_INT) { Log.e(TAG, "endpoint 0 is not interrupt type"); return; } if (ep0.getDirection() != UsbConstants.USB_DIR_IN) { Log.e(TAG, "endpoint 0 is not an input endpoint"); return; } mEndpointIntr = ep0; // endpoint 1 should be of type bulk UsbEndpoint ep1 = intf.getEndpoint(1); if (ep1.getType() != UsbConstants.USB_ENDPOINT_XFER_BULK) { Log.e(TAG, "endpoint 1 is not bulk type"); return; } if (ep1.getDirection() != UsbConstants.USB_DIR_OUT) { Log.e(TAG, "endpoint 1 is not an output endpoint"); return; } mEndpointBulkOut = ep1; // endpoint 2 should be of type bulk UsbEndpoint ep2 = intf.getEndpoint(2); if (ep2.getType() != UsbConstants.USB_ENDPOINT_XFER_BULK) { Log.e(TAG, "endpoint 2 is not bulk type"); return; } if (ep2.getDirection() != UsbConstants.USB_DIR_IN) { Log.e(TAG, "endpoint 2 is not an output endpoint"); return; } mEndpointBulkOut = ep2; mDevice = device; if (device != null) { UsbDeviceConnection connection = mUsbManager.openDevice(device); if (connection != null && connection.claimInterface(intf, true)) { Log.d(TAG, "open SUCCESS"); mConnection = connection; byte[] init = {0x00,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; //14 00 00 00 FE 00 00 00 00 00 00 00 int x = connection.bulkTransfer(mEndpointBulkOut,init, init.length, 100); Log.e(TAG, "BulTransfer returned " + x); } else { Log.d(TAG, "open FAIL"); mConnection = null; } } } }
-39726429 0 Just to note that this was resolved in Django 1.8 with the addition of the from_db_value
method on custom fields.
See https://docs.djangoproject.com/en/1.8/howto/custom-model-fields/#converting-values-to-python-objects
-8097820 0 Detect time taken to type into Autocomplete field and auto select if only one item foundRight, I've nearly found what I'm after but not quite.
Given a simple jQUery call to Autocomplete
$(".autoItem").each(function () { var id = $(this).attr("id"); var itemNumber = id.replace('item', ''); $(this).autocomplete({ source: "jsonOut/products.aspx", minLength: 2, select: function (event, ui) { $('#price' + itemNumber).val(ui.item.price); $('#id' + itemNumber).val(ui.item.id); } }); });
Which works lovely, I am now over complicating it as usual due to my application.
This is for a web form for making sales in a shop. The text box can be populated by two methods:
A) Simply typing as normal.
B) Scanning a code with a bar code scanner.
In case A, everything's fine, autocomplete works exactly as autocomplete was intended.
In case B though, I have two issues:
I need to be able to detect that this entry is from a scanner, so that the code behind knows to search the barcode field of my database, not item titles. Clearly the browser's not gonna know that, so the only way I can think is to do it by time. The scanner will populate the field faster than anyone can type.
Once a result has been generated by AutoComplete with a barcode, it will clearly only return one result, so in cases where only one result is returned, I want it to auto-select that result and run it's select function populating the other fields as required.
(the bar code scanner has a TAB terminator, so after scanning it immediately blurs the text field an moves on to the next one)
Would something like this be possible?
If someone could help with issue in isolation, that'd be cool. I have looked at https://github.com/scottgonzalez/jquery-ui-extensions/blob/master/autocomplete/jquery.ui.autocomplete.selectFirst.js for point B, but couldn't get it to work.
NOTE: If the worst comes to the worst, I could detect scanned entries by using isNumeri
c in the code behind, BUT, some codes we scan are not numeric, clearly proper UPC codes are, but we have some items with barcodes generated from product SKUs, these might not be numeric.
How to dis-allow my app to run on a specific API level? i know about the 3 specifiers in uses-sdk tag in the manifest. But that can't produce a logic i want to implement.
For eg: i want to allow my application to be installed on Level 4
to Level 10
, dis-allow for Level 11
to Level 13
and again allow for Level 14
and Level 15
.
Is that possible?
-923865 0It's definitely not the idea of MVC (or whatever you're doing) to render HTML in the Controller. HTML has to be handled in the view. What if you want to provide an alternative UI (e.g. Windows Application)? HTML does not really fit into an WinApp.
-31750690 0I have removed all unused code and left only addNumbers function. I have also removed events on each button - no such function.
I sum over all checked radio buttons so if you have other on the page you probably need more specific selector.
function addNumbers() { var selectedRadios = document.querySelectorAll('input[type="radio"]:checked'); var sum = 0; for (var i = 0; i < selectedRadios.length; i++) { sum += parseInt(selectedRadios[i].value); } document.getElementById('answer').value = sum; var showDiv = sum < 15 ? "lowResult" : (sum < 25 ? "mediumResult" : "highRisk"); document.getElementById(showDiv).style.display = 'block'; }
.results { display: none; }
<table> <tr> <th scope="col"></th> <th scope="col">noRisk</th> <th scope="col">lowRisk</th> <th scope="col">mediumRisk</th> <th scope="col">HighRisk</th> </tr> <tr> <th scope="row"> <div class="lefttext">How old are you?</div> </th> <td> <input type="radio" id="value1" name="selectedAge" value="0" checked>1-25</td> <td> <input type="radio" id="value1" name="selectedAge" value="5">26-40</td> <td> <input type="radio" id="value1" name="selectedAge" value="8">41-60</td> <td> <input type="radio" id="value1" name="selectedAge" value="10">1-25</td> </tr> <tr> <th scope="row"> <div class="lefttext">What is you BMI?</div> </th> <td> <input type="radio" id="value2" name="selectedBmi" value="0" checked>0-25</td> <td> <input type="radio" id="value2" name="selectedBmi" value="0">26-30</td> <td> <input type="radio" id="value2" name="selectedBmi" value="9">31-35</td> <td> <input type="radio" id="value2" name="selectedBmi" value="10">35+</td> </tr> <tr> <th scope="row"> <div class="lefttext">Does anybody in your family have diabetes?</div> </th> <td> <input type="radio" id="value3" name="selectedDiabete" value="0" checked>No</td> <td> <input type="radio" id="value3" name="selectedDiabete" value="7">Grandparent</td> <td> <input type="radio" id="value3" name="selectedDiabete" value="15">Sibling</td> <td> <input type="radio" id="value3" name="selectedDiabete" value="15">Parent</td> </tr> <tr> <th scope="row"> <div class="lefttext">How would you describe your diabete</div> </th> <td> <input type="radio" id="value4" name="description" value="0" checked>Low sugar</td> <td> <input type="radio" id="value4" name="description" value="0">Normal sugar</td> <td> <input type="radio" id="value4" name="description" value="7">Quite high sugar</td> <td> <input type="radio" id="value4" name="description" value="10">High sugar</td> </tr> </table> <input type="button" name="submit" value="Submit" onclick="javascript:addNumbers()" />Total = <input type="text" id="answer" name="answer" value="" /> <section> <h2>Your results:</h2> <div class="results" id="lowResult"> <p>Your results show that you currently have a low risk of developing diabetes. However, it is important that you maintain a healthy lifestyle in terms of diet and exercise. </p> </div> <div class="results" id="mediumResult"> <p>Your results show that you currently have a medium risk of developing diabetes. For more information on your risk factors, and what to do about them, please visit our diabetes advice website at <a href="http://www.zha.org.zd">http://www.zha.org.zd</a>. <p> </div> <div class="results" id="highRisk"> <p>Your results show that you currently have a HIGH risk of developing diabetes. [Your main risk factors are your BMI and your diet.] We advise that you contact the Health Authority to discuss your risk factors as soon as you can. Please fill in our contact form and a member of the Health Authority Diabetes Team will be in contact with you. </div> </section>
You can't do that unless the subroutine is a built-in Perl operator, like sqrt
for instance, when you could write
perl -e "print sqrt(2)"
or if it is provided by an installed module, say List::Util
, like this
perl -MList::Util=shuffle -e "print shuffle 'A' .. 'Z'"
-26040440 0 Remove Duplicates Linq Query Dropdownlist in VB.net I have bound my data source to the drop down list and it works, but it is showing duplicates. Here is my code
Private Sub ddlMasterPids_Load(sender As Object, e As EventArgs) Handles ddlMasterPids.Load Dim db As New DesignConstructionDataContext Dim Master = (From Master_Name In db.groups Where (Master_Name.Master_Name IsNot Nothing) Select Master_Name).ToList().Distinct() ddlMasterPids.DataSource = Master ddlMasterPids.DataTextField = "Master_Name" ddlMasterPids.DataValueField = "Master_Name" ddlMasterPids.DataBind() End Sub
The .Distinct() does not throw an error, but there are still duplicates. I also tried switching the distinc and tolist, but still just ignored the distinct. Any ideas?
-16990726 0 NSMenuDelegate methods not called for contextual menuI have a Document based application. I want to add a contextual menu that displays context-sensitive info when the user right-clicks selected text in an NSTextView.
I have followed the advice in the Apple documentation and
menu
outlet of the NSTextView.So far so good. Every thing works as expected: the menu item appears and the action is called when it is selected.
I need to get the selected text from the NSTextView before the menu appears so that I can configure my menu item appropriately. According to the docs
If you need to customize the contextual menu, you can do so by setting an appropriate object as the menu’s delegate and implementing the menuWillOpen: method to customize the menu as you see fit just before it appears.
I connect the delegate of the NSMenu to File's Owner. None of the delegate methods are called. ( menuWillOpen:
is the only one I need, but I've tried others, too).
I set a breakpoint inside the IBAction that gets called when the menu item is selected. If I inspect the menu with the debugger I can see that the delegate is correctly set to the object that implements the delegate method.
Is there anything else to check? Anything I'm doing blatantly wrong?
Xcode v4.6.3
SDK v10.8
Deployment target 10.7
this is that iPhone camera rotates the image comparing with home button. it uses EXIF that is meta data of image. see this thread.
-14342553 0 git push heroku master permission deniedI am following the ruby.railstutorial. I run the command "git push heroku master" and it spits out this error.
Permission denied (publickey). fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists.
I am inside my rails app "/Users/lexi87/rails_projects/first_app". Any solutions?
-20819572 0You can create a Blob for this, but it won't be "saved" to the client's device. The Blob can then be submitted to the server using an XMLHttpRequest
// bytes , mime var b = new Blob(['text data'], 'text/plain'); // make it easy to submit or just submit it directly var fd = new FormData(); fd.append('fileParam', b, 'file_name.txt'); // assuming XMLHttpRequest xhr xhr.send(fd);
If FormData is not available for the device, then you can send the blob directly. Adding a FormData makes the server side easier as it is the same as if you submitted a <form>
with some <input>
.
Finally I tried to work with different USB<->CAN interface from different manufacturer and it worked like a charm. My old interface was either broken or incompatible for reasons unknown. While working on this problem I learned couple of things about CAN bus and so now I share what I think was the right answer to my original question: How to troubleshoot CAN bus communication?
Streaming to string is already implemented, you can use
Writing: TClientDataSet.SaveToFile or TClientDataSet.SaveToStream
Reading: TClientDataSet.LoadFromFile or TClientDataSet.LoadFromStream
procedure SaveToStream(Stream: TStream; Format: TDataPacketFormat = dfBinary); procedure SaveToFile(const FileName: string = ''; Format: TDataPacketFormat = fBinary); procedure LoadFromStream(Stream: TStream); procedure LoadFromFile(const FileName: string = '');
the TDataPacketFormat options are:
dfBinary: Information is encoded in binary format.
dfXML:Information is encoded in XML, with extended characters encoded using an escape sequence.
dfXMLUTF8:Information is encoded in XML, with extended characters represented using UTF8.
Using dfXMLUTF8 you should have no problems with non/ansi characters sets.
-36878498 0 What the " {% " in a javascript code suppose to mean?I'm applying to a front-end test, that have a page that i might develop a responsive version. So i git clone
they repository, run npm install
, run grunt
and when i finally open the html at browser i receive this error at console:
So i go find why this is happening, and i found this javascript:
var marker = new google.maps.Marker({ map: map, icon: { url: '{% static "assets/images/marker_center.png" %}', size: new google.maps.Size(71, 156), origin: new google.maps.Point(0, 0), anchor: new google.maps.Point(38, 95) }, position: pyrmont });
So i thought that's this {%
was a sintaxe used at google maps api, but it isn't. It's not required, i can just write the path to the image and the page run without errors. My question is, why they put {%
?
I am trying to insert an image from an ajax repsonse. Everything work, but not in IE.
I have tried: Image load not working with IE 8 or lower, but get "broken image".
Tried to solve it described here: http://www.paulund.co.uk/handle-image-loading-errors-with-jquery, but it does not solve anything. I did not attach it to the document.ready function though, since this is ajax, the IE < 9 hack will never be triggered by the ajax call. the Ajax call is triggered by a mouse click which repsonds with an image link. When using JQuery's dialog function, IE does not show the image. Forcing it by right-clicking and 'Show image' shows the image.
Anybody know how to solve this problem?
function search(url){ $.ajax({ type: "GET", url: url, dataType: "html", success: function(data, status, XMLHttpResponse){ clickListenerEvent(); }, error: function(data, textStatus, XMLHttpResponse){ alert("AJAX error"); } }); } function clickListenerEvent(){ $('a.show-image').click(function (e) { var element = $(this); var href = element.attr('href'); var title = element.attr('title'); var thisId = 'dialogbox_'; var exisitingDialog = $('.dialogbox[id='+thisId+']'); if(!exisitingDialog.length){ element.parent().append("<div id='"+thisId+"'></div>"); } var thisDialog = $('.dialogbox[id='+thisId+']'); var img = new Image(); $(img).load(function() { alert('successfully loaded'); }).error(function() { alert('broken image!'); //$(this).attr('src', href); }).attr('src', href); $(thisDialog).append(img); //create the dialog $('.dialogboks[id='+thisId+']').dialog({ closeText: 'Close', title: title }); if ( $.browser.msie && $.browser.version < 9 ) { $('img').each(function(){ $(this).attr('src', $(this).attr('src')); }); } e.preventDefault(); }); }
-19291767 0 SearchView in ActionBarSherlock I'm using the SearchView widget in ActionbarSherlock as a follows:
File.java
public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getSupportMenuInflater(); inflater.inflate(R.menu.main, menu); SearchManager searchManager = (SearchManager)getSystemService(Context.SEARCH_SERVICE); SearchView searchView = (SearchView) menu.findItem(R.id.MenuSearch).getActionView(); searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); searchView.setIconifiedByDefault(true); searchView.setSubmitButtonEnabled(true); return true; }
File.xml
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/MenuSearch" android:title="@string/Bs" android:icon="@drawable/ic_action_search" android:showAsAction="always|withText" android:actionViewClass="com.actionbarsherlock.widget.SearchView" > </item> </menu>
In my application I get to show the search icon and select it unfolds the search box for the widget, but when I write any search I do not know how to interact with the widget SearchView to launch a new activity and show a series of results.
With the command searchView.setSubmitButtonEnabled(true);
appears a icon similar to 'play' and I suppose it is for just that, but I do not know how to interact with it.
Can anyone help?
-31653886 0Never mind. I just found the json in request.body.read
.
You can simply put the conditions with the range of data types and check whether the input number falls in which data type.
class FindDataType { public static void main(String[] argh) { Scanner sc = new Scanner(System.in); //no. of input values int t = sc.nextInt(); for (int i = 0; i < t; i++) { try { //Take input as long data type long x = sc.nextLong(); System.out.println(x + " can be fitted in:"); //Putting conditions to check the data type if (x >= -128 && x <= 127) { System.out.println("* byte"); System.out.println("* short"); System.out.println("* int"); System.out.println("* long"); } else if (x >= -32768 && x <= 32767) { System.out.println("* short"); System.out.println("* int"); System.out.println("* long"); } else if (x >= -2147483648 && x <= 2147483647) { System.out.println("* int"); System.out.println("* long"); } else if (x >= -9223372036854775808l && x <= 9223372036854775807l) { System.out.println("* long"); } } catch (Exception e) { //Printing exception if no data type matches. System.out.println(sc.next() + " can't be fitted anywhere."); } } sc.close(); }}
-18690633 0 I'm not sure if this is you intention, but it's weird to me...
First, you declare a class that extends from JFrame
...
public class login extends JFrame {
Then you declare a instance variable of the same class...
JFrame login = new JFrame();
You than add all your components to this instance...
login.add(panel1); login.add(panel2); login.add(panel3);
Now, I can't see how you are using this, but I imagine you are doing something like...
login login = new login() login.setVisible(true);
Which basically, doesn't show anything...
Instead. Rather than extending from JFrame
, I would extend from JPanel
and drop the login
instance variable.
Create a instance of login
and then add it to a JFrame
instance that you have created...
I also recommend that you take a look at Code Conventions for the Java Programming Language
-5833218 1 CoreDumpDirectory isn't working on ubuntu; getting segmentation fault in apache2 error logI am not able to log the apache2 crashes in CoreDumpDirectory on ubuntu 10.10. I am using Django 1.2.3 and apache2 with mod_wsgi. I followed the steps listed in response to this question but to no avail. I added - CoreDumpDirectory /var/cache/apache2/
at the end of apache2.conf file and then after executing 'ulimit -c unlimited'
, restarted the apache server. Then I replicated the condition that causes apache error log to show- "child pid 27288 exit signal Segmentation fault (11)
" but there is no mention of apache2 logging that crash in CoreDumpDirectory and also there is nothing in /var/cache/apache2.
EDIT:
I was able to solve this problem. The issue was with PyLucene environment being initialized on the run time. I was executing initvm() call everytime a request comes and it was causing segmentation fault. This link directed that I should do it in .wsgi file and after I did that there were no segmentation faults.
-803013 0 C# /windows forms: linking trackbar and textfield with a factorlinking a trackbar and a textfield is very easy in windows forms. it is like this: textBox.DataBindings.Add("Text", trackBar, "Value");
the problem is, that trackbars only allow for integer values but i want to have floating point values. so i usually just divide the value by 100, since on the trackbar the value is not directly visible to the user. but in the textbox it is.
so is it possible to link these two with a factor of 100?
thanks!
-20328424 0Usually Tag
property will be of type Object
, so I assume it is of type Object
. ==
operator with System.Object
work as reference comparison (meaning references of the instances are compared than value).
To fix it just introduce a cast to string.
if ((string)answer[0].Tag == "bla bla" && (string)answer[1].Tag== "blabla2") { MessageBox.Show("They Match"); } else { MessageBox.Show("They don't"); }
-8186617 0 Application shortcuts:
You can list installed applications with:
final PackageManager pm = getPackageManager(); //get a list of installed apps. List<ApplicationInfo> packages = pm .getInstalledApplications(PackageManager.GET_META_DATA); for (ApplicationInfo packageInfo : packages) { Log.d(TAG, "Installed package :" + packageInfo.packageName); Log.d(TAG, "Launch Activity :" + pm.getLaunchIntentForPackage(packageInfo.packageName)); }// the getLaunchIntentForPackage returns an intent that you can use with startActivity() }
If you need more info like app icon check this: How to get a list of installed android applications and pick one to run
Then you can add a Layout with a ListView to the page Fragment/Activity.
Add within the adapter for the ListView the applications you want, and onClick events to create an intent to open them.
I think this is the best way to show a list of applications, with icons etc.
Widgets: I never seen widgets inside an app, but according to the answer below http://stackoverflow.com/a/8218587/327011 apparently there is a way.
If you are interested in something a little different... you can instead create a custom Home Screen, and use it instead of custom. This will not be a app.
-40892415 0 Blank MySQL error on shared hostingI am doing a little bit of learning on mysql, php and the like. I'm using a shared hosting plan so am quite limited from a settings changes point of view.
I am attempting to run a simple mysql select command through PHP, but all i get back is a blank error
<?php $typeID = $_GET['tid']; //variables for the database server $server = "localhost"; $user = "codingma_rbstock"; $pwd = "M@nL%V{%RI+h"; $db = "codingma_rbstock"; //variables for the database fields $itemNo; $itemNm; $itemDesc; $buyPr; $sellPr; $quan; $dept; //database connection //create connection $conn = new mysqli($server, $user, $pwd, $db); //if the connection fails throw an error. if ($conn->connect_error){ die("Connection Failed: " . $conn->connect_error); } echo "Welcome to " . $typeID . "<br>"; $sql = "select ITEM_NAME from stock where ITEM_NO='00001'"; if ($conn->query($sql) === TRUE){ $res = $conn->query($sql); if ($res->num_rows > 0){ echo "success"; } }else{ echo "Error: " .$sql . "<br>" . $conn->error; } echo $res; ?>
I have checked and it seems to be connecting to the database fine (I changed a few account details to see if that threw a different error and it did).
I am sure I am missing something completely obvious here! The below is the text output from the error;
Error: select ITEM_NAME from stock where ITEM_NO='00001'
Thanks for any help.
-4046546 0Be careful with the ":method" argument. It specifies an HTTP method, not the action.
-29607437 0I am assuming you have a length
measure. If so, the below should work.
WITH MEMBER Measures.SumOfLengths AS SUM ( [DimDate].[Alldate].[Day].members, [Measures].[Length] ) SELECT Measures.SumOfLengths ON 0, [DimDate].[Alldate].[Day].members ON 1 FROM [YourCube]
-35597331 0 Because of the fact that you only write out the results after the loops have finished, you are only seeing the last result.
Also, I would expect 4 results from that data, not 2.
You need to write the output on each iteration or store each iteration and then write out the stored values.
Try printing res2
each time you calculate it and you will see something like this:
('Final Results', array([[ 0.44, 0.3 , 6.5 ]])) ('Final Results', array([[ 0.275 , 0.6 , 2.16666667]])) ('Final Results', array([[ 0.32857143, 0.3 , 1.1 ]])) ('Final Results', array([[ 0.25555556, 0.6 , 2.2 ]]))
-19034025 0 If all you need to know if its admin, don't bring all fields from CommunityMembers. Try this
$sql = $dbc->prepare(" SELECT DISTINCT cm.Power, com.* FROM Community com LEFT JOIN CommunityMembers cm ON cm.UseriID=com.CreaterByUser WHERE cm.UserID = '" . $_SESSION['UserID'] . "'");
Didn't test it, but this should work even without DISTINCT.
-33693359 0 php function - how to make dynamic with a queryHow can I take a function which creates a metabox with a dropdown of hard coded values ("Hard", Soft" and "None") and make it create the metabox dynamically according to a given array of strings?
Original function:
function your_prefix_product_fields( $meta_boxes ) { $meta_boxes[] = array( 'title' => __( 'Product Fields', 'your-prefix' ), 'post_types' => array( 'product', ), 'fields' => array( array( 'name' => __( 'Package', 'test' ), 'id' => 'package', 'type' => 'select', 'clone' => false, 'options' => array( 'Soft' => __( 'Soft', 'test' ), 'Hard' => __( 'Hard', 'test' ), 'None' => __( 'None', 'test' ), ), 'multiple' => true, 'std' => 'none', 'placeholder' => __( 'Select Package', 'test' ), ), ) ); return $meta_boxes; }
I have the array: ["Hard", "Soft", "None"]
EDIT: I thought more about my question and perhaps I can make it more clear:
What I want to do is create this array dynamically from a query output:
'options' => array( 'Soft' => __( 'Soft', 'test' ), 'Hard' => __( 'Hard', 'test' ), 'None' => __( 'None', 'test' ), ),
Additional Questions:
1) If I can create the 'options array' manually, can I write something like:
'options' => $packages,
given that I was able to create the array packages so that it will look like:
array( 'Soft' => __( 'Soft', 'test' ), 'Hard' => __( 'Hard', 'test' ), 'None' => __( 'None', 'test' ), ),
2) How can I create this type of array? Is it a hash map?
I tried something like:
$packages['Soft'] = ('Soft', 'test');
With no luck... What is the syntax for it?
-31992814 0 Adding dependencies to my project when my AAR already contains themWhy does gradle force me to add dependencies to my main module when my AAR library already uses those dependencies?
Example:
My AAR library gradle:
apply plugin: 'com.android.library' android { compileSdkVersion 22 buildToolsVersion "22.0.1" defaultConfig { minSdkVersion 15 targetSdkVersion 22 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile('com.android.support:design:22.2.1') compile('com.android.support:appcompat-v7:22.2.1') compile('com.android.support:cardview-v7:22.2.1') compile('com.android.support:recyclerview-v7:22.2.1') compile('de.greenrobot:eventbus:2.4.0') }
My app gradle:
apply plugin: 'com.android.application' android { compileSdkVersion 22 buildToolsVersion "22.0.1" defaultConfig { applicationId "com.firetrap.blaap" minSdkVersion 15 targetSdkVersion 22 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } repositories { flatDir { dirs 'libs' } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile ('my_package_name:channels.base@aar') }
Why can't I use, for example, com.android.support:cardview-v7:22.2.1
from my AAR?
There is such jQuery package called jquery-ui-personalized-1.5.2.packed.js
Download link: http://code.google.com/p/deroc/downloads/detail?name=jquery-ui-personalized-1.5.2.packed.js&can=2&q=
The Project Home tab saying Anything
Could some one explain the benefits/idea of that plugin?
For example this package used here http://www.ryantetek.com/demos/page_tab/
Why should i reference this one instead of original jquery-ui ones?
Is it jquery-ui-*.custom.min.js was called before lake that?
Where it is originality was came from?
-39589061 0 Many to many relationship hibernate with join on non-primary column hibernateI have 4 tables -
How can i create the pojo for last table (which is the join table) in Hibernate for this.
-308245 0First of all, inheritance in interfaces is OK, it applies in the same way as it does for class inheritance and is a very powerful tool.
Interfaces describe behavior, let's say an interface defines what a class "can do" so if you implement an interface you are declaring you can do what that interface specifies. For example:
interface ISubmergible { void Submerge(); }
So is obvious, if the class implements the interface then it can submerge. Some interfaces nonetheless imply other interfaces, for example, imagine this interface
interface IRunner { void Run(); }
That defines an interface that indicates that the class implementing it can run... nonetheless, in the context of our program is understood that, if something can run it can obviously walk, so you want to make sure that is fulfill:
interface IWalker { void Walk(); } interface IRunner : IWalker { void Run(); }
Finally, about the whole NotImplementedException thing... I'm amazed with some of the suggestions. A NotImplementedException should never, ever, be raised by an interface method of a class. If you implement an interface your are explicitly accepting the contract that interface establishes, if you raise a NotImplementedException you are basically saying "ok, I lied, I told you I supported the interface but I really don't".
Interfaces are meant to avoid having to worry about what the class implements and what doesn't. If you take that away they are useless. Much more important, your fellows will expect such behavior, even if you understand what you're doing the rest of your team won't and even you, 6 months from now won't understand the logic beneath it. So class2 violates common sense and interface purpose. Class2 does not implement the IBase so don't claim it does.
-9861754 0 Tile Engine CollisionOkay, so, I am making a small tile-based digging game, now I want to do collision. How would I go about doing this correctly? I know how to check if the player collides with a tile, but I don't know how to actually make the player stop when it hits a wall.
This is the game, I got 20x20 tiles here.
This is the code I'm using atm:
foreach (Tile tiles in allTiles) { if (ply.rect.Intersects(tiles.rect)) { if (tiles.ID != -1 && tiles.ID != 1) { if (ply.X > tiles.X) { Console.WriteLine("Right part."); ply.X = tiles.pos.X + 30; } if (ply.X <= tiles.X) { Console.WriteLine("Left part."); ply.X = tiles.pos.X - 30; } if (ply.Y > tiles.Y) { Console.WriteLine("Bottom part."); ply.Y = tiles.pos.Y + 30; } if (ply.Y <= tiles.Y) { Console.WriteLine("Upper part."); ply.Y = tiles.pos.Y - 30; } } } }
-9688121 0 what are Static Nested Classes in Java? I am new to java and have been scratching my head understanding some its concepts. I am following the tutorial Java tutorial. However, I cannot find the usefulness of using Static Nested Classes. I mean I think I need some good examples as to why I should want to use it. Can someone provided me some codes as examples so I can understand it better? thax
-20502798 0SELECT COUNT(*) FROM (SELECT * FROM tbl WHERE id=1 UNION SELECT * FROM tbl WHERE id=2) a
If you got two rows, they different, if one - the same.
-29320474 0 Using query URL in the formI am practicing on how to query url. But i could not get my expected output. Here is my code:
Form 1:
<html> <head> <title>Save Value</title> </head> <body> <form action="display.html" method="get"> <label> First Name: <input name="name" size="20" maxlength="25" type="text" id="name" /> </label> <input type="submit" value="submit" /> </form> </body> </html>
Form 2:
<html> <head> <title>Display</title> <script type="text/javascript"> <script type="text/javascript"> function queryVar(variable) { var query = location.search.substring(1); var vars = query.split("&"); var i; for (i = 0; i < vars.lenght; i++) { var pair = vars[i].split("="); if (pair[0] == variable) { return pair[1]; } } return(false); } </script> </head> <body> <form action="#"> <label> First Name: <input name="name" size="20" maxlength="25" type="text" id="name" readonly="readonly" /> </label> <script type="text/javascript"> var firstName = document.getElementById("name").value; firstName = location.search.substring(1); </script> </form> </body> </html>
So when i clicked submit button it will go to form 2 and will display the value that i typed in the form 1.
Thank you for your help!
-1349043 0I don't have any experience with this, but you could use a combination of ajax and server side metrics. Log when the server side first starts executing and then have an ajax call fire when the page is done loading and subtract the two. It's somewhat dirty, but it should work
-36655963 0 Recursive functions and removeEventListenerI want to write a dynamic button creator. So I have the html
file
<body> <button id="0" type="button" onclick="create_button(0)">Create button 1</button> </body>
and js
file which "simulates" proper action
var counter = 0; function create_button(n) { /*Shift up*/ for (i=counter; i>n; i--) { document.getElementById(i).id = i+1; document.getElementById(i+1).innerHTML = i+1; }; /*Create new button*/ var new_button = document.createElement("Button"); new_button.innerHTML = n+1; new_button.type = "button"; new_button.id = n+1; function helper() { create_button(n+1); }; new_button.addEventListener('click', helper ); document.body.insertBefore(new_button,document.getElementById(n).nextSibling); counter++; };
However /*Shift up*/
part only changes id
and innerHTML
of buttons not the action of click
. So in order to fix that I need to add in /*Shift up*/
two lines which should work as
document.getElementById(i+1).addEventListener('click', helper(i+1) ); document.getElementById(i+1).removeEventListener('click', helper(i) );
Clearly It will not work. Due to recursive nature of create_button
function, I imagine that helper
should be moved outside of create_button
. But I have no idea how to do it.
Some additional info I simplified the code, but in practice buttons have some addition functions which depend on n. Let say that we also want to alert the position of the button. So we change helper to
function helper() { create_button(n+1); alert(n+1); };
See in https://jsfiddle.net/o3Lsttyq/3/ what alerts say. Click for example 1,1,3.
-8597728 0Can anyone help me to understand why is it so?
The C# compiler has the reasonable expectation that the transitive closure of the referenced assemblies is available at compile time. It does not have any kind of advanced logic that reasons about what it definitely needs, might need, might not need, or definitely does not need to know in order to solve all the problems in type analysis that your program is going to throw at it. If you reference an assembly directly or indirectly, the compiler assumes that there might be type information in there that it needs.
Also, if you don't have the set of referenced assemblies at compile time then what expectation is there that users will have them at runtime? It seems reasonable to expect that the compile time environment has at least the set of assemblies that are going to be required at runtime.
I don't want to do it.
We all have to do things we don't want to do in life.
-1887761 0 Translating Sql to LinqHow to translate
select *from ( select EmployeeID,FirstName,LastName,Region from Employees where city in ('London','Seattle') ) x where x.Region is not null
into Linq Equivalent.
I tried (But null values also get selected)
LinqDBDataContext Context = new LinqDBDataContext(); var query = from emps in ( from empls in Context.Employees where empls.City == "London" || empls.City == "Seattle" && empls.Region != null select new { FirstName = empls.FirstName, LastName = empls.LastName, City = empls.City, Region = empls.Region } ) select emps; GridView1.DataSource = query; GridView1.DataBind();
-37078857 0 You need <bar>
(|
) between each command, and you can join the set
s together:
au BufNewFile,BufRead *.py,*.pyw,*.c,*.h,*.pyx match BadWhitespace /\s\+$/ | \ setlocal tabstop=4 shiftwidth=4 softtabstop=4 noexpandtab autoindent \ textwidth=79 fileformat=unix set encoding=utf-8
You can show trailing whitespaces with the listchars trail
:
set listchars+=trail:-
-20855339 0 For the benefit of those of you who land up here in search of a working implementation. The following code works for every search criteria no matter how complex. I am using Codeigniter, just for the record.
if($this->input->get('_search')=="true"){ $where = ""; $ops = array( 'eq'=>'=', 'ne'=>'<>', 'lt'=>'<', 'le'=>'<=', 'gt'=>'>', 'ge'=>'>=', 'bw'=>'LIKE', 'bn'=>'NOT LIKE', 'in'=>'LIKE', 'ni'=>'NOT LIKE', 'ew'=>'LIKE', 'en'=>'NOT LIKE', 'cn'=>'LIKE', 'nc'=>'NOT LIKE' ); $filters = json_decode($this->input->get('filters'), true); $first = true; foreach ( $filters['rules'] as $item){ $where .= $first ? " WHERE" : " AND "; $searchString = $item['data']; if($item['op'] == 'eq' ) $searchString = "'".$searchString."'"; if($item['op'] == 'bw' || $item['op'] == 'bn') $searchString = "'".$searchString."%'"; if($item['op'] == 'ew' || $item['op'] == 'en' ) $searchString = "'%".$searchString."'"; if($item['op'] == 'cn' || $item['op'] == 'nc' || $item['op'] == 'in' || $item['op'] == 'ni') $searchString = "'%".$searchString."%'"; $where .= " ".$item['field']." ".$ops[$item['op']]." ".$searchString; if ($first) { $first = false; } } $sql = "SELECT * FROM applicant".$where; $query = $this->db->query($sql); $result = $query->result_array(); $i=0; foreach ($result as $myrow){ $responce->rows[$i]['id']=$myrow['id']; $responce->rows[$i]['cell']=array($myrow['id'],$myrow['contingent_id'],$myrow['firstname'],$myrow['lastname'],$myrow['age'],$myrow['grouptype_id'],$myrow['registrationtype_id']); $i++; } }
-3027563 0 You will have 2 ViewModels because you have 2 views
1 ViewModel will have
2 ViewModel will have
Once you have the ViewModel use WPF binding and command to connect data from VM to XAML
MVVM for user control becomes a bit more complicated, so if possible stay away from UserControls for now.
-9923681 0 Stop dynamic div to push other elementsI have the following:
Text text text2 text text text text text text text.
At some point I am replacing this to this:
Text text <div class="highlight" style="background-color:red;">text2</div> text text text text text text text.
But it pushes the text, how can I make it stay in the same order as before?
This is what I tried:
float:left;
And
parent().css('overflow', 'auto');
It didn't work.
Do you know any solution?
Thanks in advance.
-12262458 0 How to get all factual monetize deals wit ruby driverI tried to get all deals for a city in the US from the Factual monetize API by the help of the ruby driver
query = factual.monetize.filters("place_locality" => "San Francisco")
Is there a limit of 20 results? How is it possible to get more deals?
-6040666 0To change date-time format take a look at this http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/263d73b2-8611-4398-9f09-9aa76bbf325e/
You basically need to use native Win API method SetLocaleInfo
.
Another tee - encoder problem.. there is problem with tee that it does not redistribute latency event or something resulting in queue hanging.. you can use bigger queue sizes its about x264enc but the principle is the same - set queue to unlimited buffers (or some big value - but this is just fine tunning)
Try to experiment with the values and write back if not working - maybe there is different problem with vpuenc.
gst-launch v4l2src device=/dev/video2 ! 'video/x-raw-yuv,width=704,height=576, framerate=25/1' ! tee name=liveTee ! queue name=mfw_queue max-size-time=0 max-size-bytes=0 max-size-buffers=0 ! mfw_isink liveTee. ! queue name=vpuenc_queue ! videorate ! vpuenc ! avimux ! filesink location=/home/RecordingFile.avi
I set bigger queue on opposite side of vpuenc as the problem that happens is that vpuenc buffers a lot of data which causes to symetrically buffer data at the other branch of tee which causes the queue to block.
If you can check if this is indeed the cause of your problem try debugging with:
GST_DEBUG=queue_dataflow:5,3 your ! pipe ! etc
and look which queue was blocked and when.. do not forget to give queues names so you can track which one was blocked..
Also you can experimentaly use leaky attribute for queue like
! queue leaky=2 ! ...
or maybe leaky=1 will do the trick (try that on queue which is on mfw_isink branch of tee)
-11709514 0 ajax jsonp request 503 responsePossible Duplicate:
Display jQuery $.ajax 503 error response
I am making a call to an api which is a bit temoermental. Alot of the time it is responding with a 503. My problem is that when this happens it none of the functions (complete, error, success) are triggered. I am looking for a way to log this in my code. Any ideas greatly appreciated
$.ajax ({ url : engine.getQuery(), dataType : 'jsonp', success : entErrorFunction, complete : entErrorFunction, error : entErrorFunction }); var entErrorFunction = function(){ console.log('test2'); };
-39071119 0 I cant really be specific about your template structure (template-part content-title??) but using a generic example the following will display the featured image where available;
functions.php
if ( ! function_exists( 'mytheme_setup' ) ) : function mytheme_setup() { /* * Enable support for Post Thumbnails on posts and pages. * * See: https://codex.wordpress.org/Function_Reference/add_theme_support#Post_Thumbnails */ add_theme_support( 'post-thumbnails' ); set_post_thumbnail_size( 825, 510, true ); } endif; add_action( 'after_setup_theme', 'mytheme_setup' );
your content template page (content.php, template-page, etc..)
// WP_Query arguments $args = array ( 'nopaging' => false, 'posts_per_page' => '2', 'offset' => '1', ); // The Query $the_query = new WP_Query( $args ); // The Loop if ( $the_query->have_posts() ) { while ( $the_query->have_posts() ) { $the_query->the_post(); ?> <article> <?php if ( has_post_thumbnail() ) : ?> <div class="post-thumbnail"> <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"> <?php the_post_thumbnail(); ?> </a> </div> <?php endif; ?> <div class="post-title"> <?php echo '<h2>' . get_the_title() . '</h2>'; ?> </div> </article> <?php } /* Restore original Post Data */ wp_reset_postdata(); } else { // no posts found echo "NADA"; }
-35195139 0 For academic purposes (learning Python) you could use recursion:
def getSum(iterable): if not iterable: return 0 # End of recursion else: return iterable[0] + getSum(iterable[1:]) # Recursion step
But you shouldn't use recursion in real production code. It's not efficient and the code much less clear then with using built-ins. For this case you do not need neither recursion nor loop. Just use built-in sum:
>>>a = [1, 2, 3, 4, 5] >>>sum(a) 15
-182625 0 I agree with the crowd saying that the 7 makes sense in this case, but I would add that in the case where the 6 is important, say you want to make clear you're only acting on objects up to the 6th index, then the <= is better since it makes the 6 easier to see.
-30918873 0 check if id exists in multiple tablesI am using SQL Server 2012.
I have 5 tables (lets call them A, B, C, D & E). Each table contains a column called m_id, which contains id's that are nvarchar(10).
I currently run the query below 5 times (changing the table name). To see if the table contains the id.
select m_id from A where m_id = 'some_id'
Basically I want to know if the id is any of the 5 tables, if so return 1 else if does not exist in any of the 5 tables return 0.
I feel the current way I'm doing this is very inefficient. Is there a better way to do this?
-34678458 0Remove the _ from the lines. You would use them if you are splitting the line, but if you have it all on one line you don't need them.
So:
Retval = ShellExecute(Me.hwnd, "open", "5.exe", _ 0, 0, SW_HIDE)
or
Retval = ShellExecute(Me.hwnd, "open", "5.exe", 0, 0, SW_HIDE)
would be ok.
Edit Based on comment:
Just had a look for the error code and I think this might help you: Expected end of statement
Try removing the As Long. Just as a side note, I would move the dim to the top of the function as well.
-36625404 0 how hadoop reduce tasks deal with map grouped dataReduce method deals with grouped data from map. But I wonder how do reduce tasks take the groups data? If maps output many grouped data, do each reduce task just read the same numbers of groups?? What is the mechanism??
-2746040 0List is an interface. It (like Collection) defines optional operations. Optional operations are part of the interface (for consistency) but there is no guarantee that subtypes would actually support them (it kind of violates behavioral subtyping). In other words, not all actual implementations of lists have to support these operations, they just have to document whether they do.
What actual list type are you using? ArrayList? LinkedList? A custom type?
For the best of my knowledge ArrayList DOES support the set operation. I am not sure about LinkedList If you have a custom implementation, it may not support it unless you override the method.
-17196581 0I have found the answer in the wiki of the project
The text passed is the literal block, unrendered.
But it provides a Mustache_LambdaHelper
that can be used to render the text passed.
So I have to add this to my lambda function:
$data->stars = function($label, Mustache_LambdaHelper $helper) { $aux = ""; $level = $helper->render($label); $l = intVal($level); for ($i = 0; $i < $l; $i++) { $aux .= "+"; } for ($i = $l; $i < 5; $i++) { $aux .= "."; } return $aux; };
And that's all it's needed to make it works. Thanks to all readers!
-40606285 0 C# FtpWebRequest creates corrupted filesI'm using .NET 3.5 and I need to transfer by FTP some files. I don't want to use files because I manage all by using MemoryStream
and bytes arrays
.
Reading these articles (article and article), I made my client.
public void Upload(byte[] fileBytes, string remoteFile) { try { string uri = string.Format("{0}:{1}/{2}", Hostname, Port, remoteFile); FtpWebRequest ftp = (FtpWebRequest)WebRequest.Create(uri); ftp.Credentials = new NetworkCredential(Username.Normalize(), Password.Normalize()); ftp.UseBinary = true; ftp.UsePassive = true; ftp.Method = WebRequestMethods.Ftp.UploadFile; using (Stream localFileStream = new MemoryStream(fileBytes)) { using (Stream ftpStream = ftp.GetRequestStream()) { int bufferSize = (int)Math.Min(localFileStream.Length, 2048); byte[] buffer = new byte[bufferSize]; int bytesSent = -1; while (bytesSent != 0) { bytesSent = localFileStream.Read(buffer, 0, bufferSize); ftpStream.Write(buffer, 0, bufferSize); } } } } catch (Exception ex) { LogHelper.WriteLog(logs, "Errore Upload", ex); throw; } }
The FTP client connects, writes and close correctly without any error. But the written files are corrupted, such as PDF cannot be opened and for DOC/DOCX Word shows a message about file corruption and tries to restore them.
If I write to a file the same bytes passed to the Upload method, I get a correct file. So the problem must be with FTP transfer.
byte[] fileBytes = memoryStream.ToArray(); File.WriteAllBytes(@"C:\test.pdf", fileBytes); // --> File OK! ftpClient.Upload(fileBytes, remoteFile); // --> File CORRUPTED on FTP folder!
-20113789 0 creating quiz jquery, function load options store quiz code: http://jsfiddle.net/HB8h9/7/
<div id="tab-2" class="tab-content"> <label for="tfq" title="Enter a true or false question"> Enter a Multiple Choice Question </label> <br /> <textarea name="tfq" rows="3" cols="50"></textarea> <p>Mark the correct answer</p> <input type="radio" name="multians" value="A">A)</input> <input name="Avalue" type="text"> <br> <input type="radio" name="multians" value="B">B)</input> <input name="Bvalue" type="text"> <br> <input type="radio" name="multians" value="C">C)</input> <input name="Cvalue" type="text"> <br> <input type="radio" name="multians" value="D">D)</input> <input name="Dvalue" type="text"> <br>
//different file below used as main page
$(document).ready(function() { $("#second li ").click(function() { $("#content").load("file_above.html .tabs"); }); });
trying to create a quiz using div elements from different file containing select option tags. Need to create a function which will load all the "appropriate div tags" according to the selected option and display the dropdown options again after each option has been selected. I'm not sure when to implement submit button either after each question type is loaded or somewhere between 5 - 10 questions. the submit button will "store" the questions selected into a quiz which will later be used for another user to answer.
I hope this makes sense, I'm not too familiar with jquery and any help would be highly appreciated.
Any other techniques which would be better suited are also welcomed. thanks.
-4625577 0 Trouble including httparty in ruby on railsI've been trying to use HTTParty in my rails code
sudo gem install httparty
From the command line I can now successfully do
httparty "http://twitter.com/statuses/public_timeline.json"
When I try this in my rails app
require 'rubygems' require 'httparty' class FooController < ApplicationController include HTTParty def bar blah = HTTParty.get("http://twitter.com/statuses/public_timeline.json") end end
I get the error message "no such file to load -- httparty"
I suspect there is something wrong with my environment?
-23132498 0 WP 8.1 - Debug Universal App in device not working with VS 2013im trying to ebug my universal app from VS 2013 update 2 in my WP8.1 device but i have this error:
Failed to deploy. Make sure another deployment or debugging session is not in progress for the same emulator or device from a different instance of Visual Studio: Error writing file '%FOLDERID_SharedData%\PhoneTools\11.0\Debugger\bin\RemoteDebugger\msvsmon.exe'. Error 0x80070005: Access Denied.
I tried run as administrator and got the same error. Im using VS 2013 Update 1+2, Windows Phone 8.1 on my device (unlocked with WP8.1 developer tool).
Thanks in advance!
-13607416 0If you mean JavaScript code running in a web browser and figuring out the name of the other folder on your server, no, there's no (reasonable) way to do that.
(The unreasonable way would be to do a bunch of ajax requests with guesses about what the other folder's name was, working through various alphanumeric combinations, etc., handling the 404s until it got lucky. Like I said, unreasonable. And you'd have to have the name of a resource in that folder unless it supported a default document.)
-7456006 0 Maven packaging without test (skip tests)I am new to Maven. I am trying to package my project. But, it automatically runs the tests. The tests insert some content in the database. This is not what I want, I need to avoid running tests while package the application. Anybody knows how run the package with out test?
-11440989 0 How do I winsorize data in SPSS?Does anyone know how to winsorize data in SPSS? I have outliers for some of my variables and want to winsorize them. Someone taught me how to do use the Transform -> compute variable
command, but I forgot what to do. I believe they told me to just compute the square root of the subjects measurement that I want to winsorize. Could someone please elucidate this process for me?
It seems like you are trying to implement OrderBy dynamically using expression trees. You should try the following:
public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, string sortProperty, ListSortDirection sortOrder) { var type = typeof(T); var property = type.GetProperty(sortProperty); var parameter = Expression.Parameter(type, "p"); var propertyAccess = Expression.MakeMemberAccess(parameter, property); var orderByExp = Expression.Lambda(propertyAccess, parameter); var typeArguments = new Type[] { type, property.PropertyType }; var methodName = sortOrder == ListSortDirection.Ascending ? "OrderBy" : "OrderByDescending"; var resultExp = Expression.Call(typeof(Queryable), methodName, typeArguments, source.Expression, Expression.Quote(orderByExp)); return source.Provider.CreateQuery<T>(resultExp); }
and then you can call it as:
collection.OrderBy("Property on which you want to sort", ListSortDirection.Ascending);
-11457195 0 The Below code will loop through your source data and store it in an array, while simultaneously checking for duplicates. After the collection is complete it uses the array as a key to know which columns to delete.
Due to the high number of potentiol screen updates with the deletion be sure to turn screenupdating off. (included)
Sub Example() Application.ScreenUpdating = false Dim i As Long Dim k As Long Dim StorageArray() As String Dim iLastRow As Long iLastRow = ActiveSheet.Cells(ActiveSheet.Rows.Count, "A").End(xlUp).Row ReDim StorageArray(1 To iLastRow, 0 To 1) 'loop through column from row 1 to the last row For i = 1 To iLastRow 'add each sheet value to the first column of the array StorageArray(i, 0) = ActiveSheet.Range("A" & i).Value '- keep the second column as 0 by default StorageArray(i, 1) = 0 '- as each item is added, loop through previously added items to see if its a duplicate For k = 1 To i-1 If StorageArray(k, 0) = StorageArray(i, 0) Then 'if it is a duplicate set the second column of the srray to 1 StorageArray(i, 1) = 1 Exit For End If Next k Next i 'loop through sheet backwords and delete rows that were maked for deletion For i = iLastRow To 1 Step -1 If StorageArray(i, 1) = 1 Then ActiveSheet.Range("A" & i).EntireRow.Delete End If Next i Application.ScreenUpdating = true End Sub
As requested, here is a similar way to do it, using Collections instead of an Array for key indexing: (RBarryYoung)
Public Sub RemovecolumnDuplicates() Dim prev as Boolean prev = Application.ScreenUpdating Application.ScreenUpdating = false Dim i As Long, k As Long Dim v as Variant, sv as String Dim cl as Range, ws As Worksheet Set ws = ActiveWorksheet 'NOTE: This really should be a parameter ... Dim StorageArray As New Collection Dim iLastRow As Long iLastRow = ws.Cells(ActiveSheet.Rows.Count, "A").End(xlUp).Row 'loop through column from row 1 to the last row i = 1 For k = 1 To iLastRow 'add each sheet value to the collection Set cl = ws.Cells(i, 1) v = cl.Value sv = Cstr(v) On Error Resume Next StorageArray.Add v, sv If Err.Number <> 0 Then 'must be a duplicate, remove it cl.EntireRow.Delete 'Note: our index doesn't change here, since all of the rows moved Else 'not a duplicate, so go to the next row i = i + 1 End If Next k Application.ScreenUpdating = prev End Sub
Note that this method does not need to assume any datatype or integer limits for the values of the cells in the column.
(Mea Culpa: I had to hand-enter this in Notepad, because my Excel is busy running project tests right now. So there may be some spelling/syntax errors...)
-2171082 0 In which order Rails does the DB queriesIn Select n objects randomly with condition in Rails Anurag kindly proposed this answer to randomly select n posts with votes >= x
Post.all(:conditions => ["votes >= ?", x], :order => "rand()", :limit => n)
my concern is that the number of posts that have more than x votes is very big.
what is the order the DB apply this criteria to the query?
Does it
The challenge here is that two reflection steps are involved, one to invoke the generic CreateObjectSet
method and one to get the EntitySet
from the result. Here's a way to do this:
First, the method:
string GetObjectSetName(ObjectContext oc, MethodInfo createObjectSetMethodInfo, Type objectSetType, Type entityType) { var objectSet = createObjectSetMethodInfo.MakeGenericMethod(entityType) .Invoke(oc, null); var pi = objectSetType.MakeGenericType(entityType).GetProperty("EntitySet"); var entitySet = pi.GetValue(objectSet) as EntitySet; return entitySet.Name; }
As you see, I first get the ObjectSet
by invoking the MethodInfo
representing the generic method CreateObjectSet<T>()
. Then I find the PropertyInfo
for the EntitySet
property of the generic type ObectSet<T>
. Finally, I get this property's value and the name of the obtained EntitySet
.
To do this, I first get a MethodInfo
for CreateObjectSet<>()
(the one without parameters) and the ObjectSet<>
type
var createObjectSetMethodInfo = typeof(ObjectContext).GetMethods() .Single(i => i.Name == "CreateObjectSet" && !i.GetParameters().Any()); var objectSetType = Assembly.GetAssembly(typeof(ObjectContext)) .GetTypes() .Single(t => t.Name == "ObjectSet`1");
In GetObjectSetName
their generic parameters are specified by a concrete entity type, which is done by these "MakeGeneric..." methods.
var oc = (dbContextInstance as IObjectContextAdapter).ObjectContext; var entityType = typeof(UserRole); var name = GetObjectSetName(oc, createObjectSetMethodInfo, objectSetType, entityType);
In EF 6 these should be the using
s:
using System.Data.Entity.Core.Metadata.Edm using System.Data.Entity.Core.Objects using System.Data.Entity.Infrastructure using System.Linq using System.Reflection
-23168878 0 Try to assign value like this ,
document.getElementsByName('ga')[0].value = ga;
where ga would be your sum ,
ga = (pa+ma+oa).toFixed(2);
-34867784 0 Tableau Public is the free-to-use version of Tableau, with some features limitation. Data for Tableau Public is hosted on the cloud and is public.
-38577314 0 If you want to modify the initial object - it would be enough to use Object.keys
and Array.forEach
functions:
var obj = { "page": [ "POST", "DELETE" ], "news": [ "PUT" ] }; Object.keys(obj).forEach(function(k) { obj[k] = obj[k].join(","); }); console.log(JSON.stringify(obj, 0, 4));
Additional solution for another complex case:
var obj = { "page": { "POST": [ "POST" ], "PUT": 122 }, "news": { "PUT": [ "PUT" ] } }; Object.keys(obj).forEach(function (k) { var innerKeys = Object.keys(obj[k]), items = []; innerKeys.forEach(function(key) { items.push((Array.isArray(obj[k][key]))? key : key + ":" + obj[k][key]); }); obj[k] = items.join(","); }); console.log(JSON.stringify(obj, 0, 4));
It depends.
If the validation is simple, and can be checked using only information contained in the class, then most of the time it's worth while to add the state checks to the class.
There are sometimes, however, where it's not really possible or desirable to do so.
A great example is a compiler. Checking the state of abstract syntax trees (ASTs) to make sure a program is valid is usually not done by either property setters or constructors. Instead, the validation is usually done by a tree visitor, or a series of mutually recursive methods in some sort of "semantic analysis class". In either case, however, properties are validated long after their values are set.
Also, with objects used to old UI state it's usually a bad idea (from a usability perspective) to throw exceptions when invalid values are set. This is particularly true for apps that use WPF data binding. In that case you want to display some sort of modeless feedback to the customer rather than throwing an exception.
-27746145 0Try:
$("#slider").val()[0];
To get the first element in the array.
-14438675 0var s = new Array; var i = 0; var x = $(".ch").length; $(".ch").each( function() { s[i] = $(this).data("id"); i++; }); var g = s.sort(function(a,b){return a-b}); for(var c = 0; c < x; c++) { var div = g[c]; var d = $(".ch[data-id="+div+"]").clone(); var s = $(".ch[data-id="+div+"]").remove(); $(".pa").append(d); }
-20307980 0 PHP if/else not working as intended Below is some code I am using to check if a field says "CIT" to display that as the selected item in the html select box. Elseif the field says "CSE", display "CSE" as selected and CIT/CSE in the drop downs respectively if one or the other is selected in the database. No matter what is in the database field the code always seems to use the first if statement. So courses with "CSE" as course_major are showing "CIT" as the first option in the drop down, however it shouldn't be this way.
while ($row = mysqli_fetch_array ($r, MYSQLI_ASSOC)) { $bg = ($bg=='#B39C56' ? '#000000' : '#0A0A0A'); echo '<tr> <form action="edit_course.php" method="post"> <!--Next Course First Line of Table --><td>Major:</td> <td style="text-align:left">'; if ($row['course_major'] = "CIT") { echo' <select name="course_major" class="rounded"> <option value="'.$row['course_major'].'">'.$row['course_major'].'</option> <option value="CSE">CSE</option> </select>'; } elseif ($row['course_major'] = "CSE") { echo' <select name="course_major" class="rounded"> <option value="'.$row['course_major'].'">'.$row['course_major'].'</option> <option value="CIT">CIT</option> </select>'; }; echo'</td> ........................
-973722 0 Posix/Perl regex in php I have the simple regular expression:
\{[0-9]*\}
which works fine with PHP's ereg_ functions (Posix compatible), but I need to use the preg_match_all function, which doesn't have an ereg_ equivalent. My expression above doesn't seem to work with preg_ (perl compatible) functions. How can I go about "converting" it to be perl compatible?
-7915444 0 How to play a few video in youtube player on Java, Android?I have a few videos for Android. My app plays it by code:
Intent youtube=new Intent(Intent.ACTION_VIEW, Uri.parse(link)); startActivityForResult(youtube, 100);
But it code play 1 video from list. How can I put a few video for Intent in order to standart player play it in series?
-13815278 0 System.InvalidOperationException: Cannot use a DependencyObject that belongs to a different thread than its parent FreezableI have this problem... but can't figure out where is coming from. Do you know of a way to debug this? This happens in a WPF application that has several windows each running in different dispatchers.
System.InvalidOperationException: Cannot use a DependencyObject that belongs to a different thread than its parent Freezable. at System.Windows.Freezable.EnsureConsistentDispatchers(DependencyObject owner, DependencyObject child) at System.Windows.Freezable.OnFreezablePropertyChanged(DependencyObject oldValue, DependencyObject newValue, DependencyProperty property) at System.Windows.Media.RenderData.PropagateChangedHandler(EventHandler handler, Boolean adding) at System.Windows.UIElement.RenderClose(IDrawingContent newContent) at System.Windows.Media.RenderDataDrawingContext.DisposeCore() at System.Windows.Media.DrawingContext.System.IDisposable.Dispose() at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Controls.StackPanel.ArrangeOverride(Size arrangeSize) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Controls.Grid.ArrangeOverride(Size arrangeSize) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Controls.DockPanel.ArrangeOverride(Size arrangeSize) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Controls.Control.ArrangeOverride(Size arrangeBounds) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Controls.Grid.ArrangeOverride(Size arrangeSize) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Controls.Grid.ArrangeOverride(Size arrangeSize) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Controls.Control.ArrangeOverride(Size arrangeBounds) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Controls.Control.ArrangeOverride(Size arrangeBounds) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Controls.Grid.ArrangeOverride(Size arrangeSize) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Controls.Border.ArrangeOverride(Size finalSize) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Controls.Grid.ArrangeOverride(Size arrangeSize) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Controls.Control.ArrangeOverride(Size arrangeBounds) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Controls.Grid.ArrangeOverride(Size arrangeSize) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Controls.Grid.ArrangeOverride(Size arrangeSize) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Controls.Grid.ArrangeOverride(Size arrangeSize) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at MS.Internal.Helper.ArrangeElementWithSingleChild(UIElement element, Size arrangeSize) at System.Windows.Controls.ContentPresenter.ArrangeOverride(Size arrangeSize) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Controls.Grid.ArrangeOverride(Size arrangeSize) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Controls.Control.ArrangeOverride(Size arrangeBounds) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Controls.DockPanel.ArrangeOverride(Size arrangeSize) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Controls.Border.ArrangeOverride(Size finalSize) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at MS.Internal.Helper.ArrangeElementWithSingleChild(UIElement element, Size arrangeSize) at System.Windows.Controls.ContentPresenter.ArrangeOverride(Size arrangeSize) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Controls.Grid.ArrangeOverride(Size arrangeSize) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Controls.Border.ArrangeOverride(Size finalSize) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Controls.Grid.ArrangeOverride(Size arrangeSize) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Controls.Border.ArrangeOverride(Size finalSize) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Controls.Border.ArrangeOverride(Size finalSize) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Documents.AdornerDecorator.ArrangeOverride(Size finalSize) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Window.ArrangeOverride(Size arrangeBounds) at Syncfusion.Windows.Shared.ChromelessWindow.ArrangeOverride(Size arrangeBounds) at System.Windows.FrameworkElement.ArrangeCore(Rect finalRect) at System.Windows.UIElement.Arrange(Rect finalRect) at System.Windows.Interop.HwndSource.SetLayoutSize() at System.Windows.Interop.HwndSource.set_RootVisualInternal(Visual value) at System.Windows.Window.SetRootVisualAndUpdateSTC() at System.Windows.Window.SetupInitialState(Double requestedTop, Double requestedLeft, Double requestedWidth, Double requestedHeight) at System.Windows.Window.CreateSourceWindow(Boolean duringShow) at System.Windows.Window.ShowHelper(Object booleanBox) at Djali.Services.WindowInfo.PreloadWindow() in c:\src-tfs\Development\Djali\Djali\Services\GuiThreadsService.cs:line 612 at Djali.Services.GuiThreadsService.<>c__DisplayClass20.<InitializeRuntime>b__11() in c:\src-tfs\Development\Djali\Djali\Services\GuiThreadsService.cs:line 293 at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs) at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
-37804444 0 Latest Versions of mysql don't support DATEADD instead use the syntax
DATE_ADD(date,INTERVAL expr type)
To get the last 3 months data use,
DATE_ADD(NOW(),INTERVAL -90 DAY) DATE_ADD(NOW(), INTERVAL -3 MONTH)
-26493197 0 Follow following steps: 1. Click on Developers Tool 2. In Html select element for which you want to add css 3. Select attribute tab present on right side 4. Add Name and Value. Check your style is applied to html element.
-8645865 0 3D World with GPS data in Javascript and html5I would like to create a 3D rotating world in javascript, dynamically positioning points from a json to display data such as text or pictures, and randomly rotating from a point to another.
I would like to receive examples and suggestions before beginning to develop. Which libraries would you use? Which algorythm would you use to rotate the world accordingly to the gps data?
Edit: Reading again my question I think I should make it more clear. I want to make something like Google Earth, without the zoom. There will be points on a 3d model of the earth, and a rotation from a point to another.
-4341105 0I don't know a very short way, but I would use something like this (as qick hack to get an impression):
try { // this is a new frame, where the picture should be shown final JFrame showPictureFrame = new JFrame("Title"); // we will put the picture into this label JLabel pictureLabel = new JLabel(); /* The following will read the image */ // you should get your picture-path in another way. e.g. with a JFileChooser String path = "C:\\Users\\Public\\Pictures\\Sample Pictures\\Koala.jpg"; URL url = new File(path).toURI().toURL(); BufferedImage img = ImageIO.read(url); /* until here */ // add the image as ImageIcon to the label pictureLabel.setIcon(new ImageIcon(img)); // add the label to the frame showPictureFrame.add(pictureLabel); // pack everything (does many stuff. e.g. resizes the frame to fit the image) showPictureFrame.pack(); //this is how you should open a new Frame or Dialog, but only using showPictureFrame.setVisible(true); would also work. java.awt.EventQueue.invokeLater(new Runnable() { public void run() { showPictureFrame.setVisible(true); } }); } catch (IOException ex) { System.err.println("Some IOException accured (did you set the right path?): "); System.err.println(ex.getMessage()); }
-7516775 0 Why not create a user control that generates the required <OBJECT />
html to display the swf file and then you can dynamically load these if there are swf file present?
Is instance of Feign thread safe...? I couldn't find any documentation that supports this. Do anyone out there think otherwise?
Here is the standard example posted on github repo for Feign...
interface GitHub { @RequestLine("GET /repos/{owner}/{repo}/contributors") List<Contributor> contributors(@Param("owner") String owner, @Param("repo") String repo); } static class Contributor { String login; int contributions; } public static void main(String... args) { GitHub github = Feign.builder() .decoder(new GsonDecoder()) .target(GitHub.class, "https://api.github.com"); // Fetch and print a list of the contributors to this library. List<Contributor> contributors = github.contributors("netflix", "feign"); for (Contributor contributor : contributors) { System.out.println(contributor.login + " (" + contributor.contributions + ")"); } }
Should I change this to following... Is it thread safe...?
interface GitHub { @RequestLine("GET /repos/{owner}/{repo}/contributors") List<Contributor> contributors(@Param("owner") String owner, @Param("repo") String repo); } static class Contributor { String login; int contributions; } @Component public class GithubService { GitHub github = null; @PostConstruct public void postConstruct() { github = Feign.builder() .decoder(new GsonDecoder()) .target(GitHub.class, "https://api.github.com"); } public void callMeForEveryRequest() { github.contributors... // Is this thread-safe...? } }
For the example above... I've used spring based components to highlight a singleton. Thanks in advance...
-15733463 0 using datenum results in not showing both strings1. How do I read in this data properly so that the date parses properly? I am trying to concatenate strings I read from a file but the output I get is mixed up. The output is the x axis.Also, the spacing from x axis has numbers instead of the string I want. The file has 4 columns,date,time,temperature and value. The date is "01.01.2013 " and the time "09:08:02"
Also, if I want to use only first column (with date) how can I do this? Because using datenum(mydata{1}) results to "Cannot parse date 01.01.2013"
... mydata = textscan(fid, '%s %s %f %f', 'delimiter',';', 'HeaderLines',1); date={}; temp={}; .. date{1}=datenum( strcat(mydata{1},{' '},mydata{2}) ); ...
2. How do I correct the axis ticks?
I am then trying to plot data using plotyy and want the x-axis to be the date, but I am getting two different axis labels.
Here is the code I am using:
temp = mydata{4}; plotyy(date,temp,date,2*temp); datetick('x','mmm.dd,yyyy');
Here is the resulting image:
---------------UPDATE---------------------------------------
Here is the code:
fid = fopen('test2.txt','r'); mydata = textscan(fid, '%s %s %f %f', 'delimiter',';', 'HeaderLines',1); fclose(fid); date=datenum( strcat(mydata{1},{' '},mydata{2}),'mmm.dd,yyyy HH:MM:SS' ); temperature=mydata{3}; value=mydata{4}; [AX,H1,H2]=plotyy(date,temperature,date,value,'plot'); set(get(AX(1),'Ylabel'),'String','Temperatures'); set(get(AX(2),'Ylabel'),'String','Value'); set(H1,'LineStyle','--'); set(H2,'LineStyle',':'); datetick(AX(1),'x','mmm.dd,yyyy'); title('Temperatures - Values'); xlabel('Date')
and the file
Date;Time;Temp;value Jan.01,2013; 11:00:00;20;10 Feb.08,2013; 12:00:00;23;11 Mar.04,2013; 04:02:00;24;15 Apr.10,2013; 08:04:00;28;20 May.10,2013; 12:05:00;32;30 Jun.04,2013; 10:06:0;33;27
-34101309 0 The second parameter of SetFileAttributesW should be a code to set the value
Try this
HIDE_ATTRIBUTE = 0x02 filepath='file path' ctypes.windll.kernel32.SetFileAttributesW(unicode(file2path), HIDE_ATTRIBUTE)
-21060265 0 Thats quite simple, on page load you can check if the property has some value or not. You can check it for Null or Empty case depending on your property type. like if i have this
private string _someString; public string SomeString { get { return _someString; } set { _someString = value; } }
On page_load event i will check if
if(_someString != null && _someString != "") { String message = "Missing someString property"; isAllPropertySet = false; //This is boolean variable that will decide whether any property is not left un-initialised }
All The Best.
and finally
-7381478 0Here's a diagram I put together to illustrate the ideas in the other posts:
Test-Path
can be used with a special syntax:
Test-Path variable:global:foo
-2950178 0 What you're describing sounds like the proper behavior for a "p" tag. See here. If you don't want the link below it why don't you use a "div" instead of a "p" tag? You should be able to transfer all styles over to the new div.
Update: I think the HTML below would do what you are saying. I did the styles inline for simplicity, you'll want to move those to your css file.
<div class="footer"> <div style="float:left">bla bla bla bla</div> <a href="url_here" style="float:right" class="next" title="Next">Next</a> </div>
-16697347 0 In your code last line
returnValue = (int)sqlComm.ExecuteScalar();
is culprit, you are trying to parser the null to int. This is why your code is throwing exception. Before parsing to is you should check is object is null. You can use try and catch to prevent unwanted error.
-21748197 0Here is sample code for you, please note how there are domain classes like Range and Attribute are used for string parsing convenience. All the grouping is done via regular java map.
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class PetalGrouping { private static final String input = "Petal_Length\t0\t1.3 - 2.42\n" + "Petal_Length\t1\t2.42 - 3.54\n" + "Petal_Length\t2\t3.54 - 4.66\n" + "Petal_Length\t3\t4.66 - 5.78\n" + "Petal_Length\t4\t5.78 - 6.9\n" + "Petal_Width\t 5\t0.3 - 0.76\n" + "Petal_Width\t 6\t0.76 - 1.2200000000000002\n" + "Petal_Width\t 7\t1.2200000000000002 - 1.6800000000000002\n" + "Petal_Width\t 8\t1.6800000000000002 - 2.14\n" + "Petal_Width\t 9\t2.14 - 2.6\n" + "Sepal_Length\t10\t4.3 - 5.02\n" + "Sepal_Length\t11\t5.02 - 5.739999999999999\n" + "Sepal_Length\t12\t5.739999999999999 - 6.459999999999999\n" + "Sepal_Length\t13\t6.459999999999999 - 7.179999999999999\n" + "Sepal_Length\t14\t7.179999999999999 - 7.899999999999999\n" + "Sepal_Width\t 15\t2.3 - 2.76\n" + "Sepal_Width\t 16\t2.76 - 3.2199999999999998\n" + "Sepal_Width\t 17\t3.2199999999999998 - 3.6799999999999997\n" + "Sepal_Width\t 18\t3.6799999999999997 - 4.14\n" + "Sepal_Width\t 19\t4.14 - 4.6"; public static void main(String... args) { Map<String, List<Attribute>> map = new HashMap<String, List<Attribute>>(); String[] lines = input.split("\n"); for (String line : lines) { Attribute attribute = Attribute.parse(line); List<Attribute> attributeList = map.get(attribute.getName()); if (attributeList == null) { attributeList = new ArrayList<Attribute>(); map.put(attribute.getName(), attributeList); } attributeList.add(attribute); } System.out.println(map); } } class Range { private double from; private double to; private Range(double from, double to) { this.from = from; this.to = to; } public static Range parse(String string) { String[] parts = string.split(" "); if (parts.length != 3) { throw new RuntimeException("Parsing failed for line: " + string); } return new Range(Double.parseDouble(parts[0].trim()), Double.parseDouble(parts[2].trim())); } @Override public String toString() { return "{from=" + from + ", to=" + to + '}'; } } class Attribute { private String name; private int index; private Range range; protected Attribute(String name, int index, Range range) { this.name = name; this.index = index; this.range = range; } public static Attribute parse(String line) { String[] lineParts = line.split("\t"); if (lineParts.length != 3) { throw new RuntimeException("Parsing failed for line: " + line); } String name = lineParts[0].trim(); int index = Integer.parseInt(lineParts[1].trim()); Range range = Range.parse(lineParts[2].trim()); return new Attribute(name, index, range); } @Override public String toString() { return "index=" + index + " " + range + '}'; } public String getName() { return name; } }
-1647199 0 Yes, you will need a 64 bit JVM to utilize all your memory. I am not up to date with what you can get for Windows so I will let someone else answer that.
However, I think the main reason why you can't find a 64 bit netbeans is that it is 100% pure java and architecture independent. Eclipse provides an alternative GUI framework with a more native look and feel (SWT) and uses it for the development environment itself. Once you link to your java app to native libraries you need to distribute the libraries for the correct architecture, hence the architecture dependence of the eclipse distribution (your second item).
-22529246 0I like this version of splice, removing an element by its value using $.inArray
:
$(document).ready(function(){ var arr = ["C#","Ruby","PHP","C","C++"]; var itemtoRemove = "PHP"; arr.splice($.inArray(itemtoRemove, arr),1); });
-27217219 0 You have this problem because you're not correctly using pointers. Look, you create two TreeNode
's on a stack, then you take their addresses, and make them children of new node. But, because they are on stack, they have the same address. So all the left and right children will point to the same location.
You probably wanted to allocate them on heap using new
or shared_ptr
.
I have some media queries in a class and they're working absolutely fine, but the Chrome browser displays it wrongly as the only browser. So I used a browser hack for the other classes but I don't know how to target the media query. I tried this inside the browser hack:
.firstclass > h1 > @media(min-width: 1620px) { font-size: 3.7vw; }
But my code editor says that "media definitions require block statements after any features"
, so it seems that it takes it as a new media query...
How can I target it correctly? Isn't the media query a child of the class?
-25292230 0See here for multiindex using slicers, introduced in 0.14.0
In [36]: idx = pd.IndexSlice In [37]: df.loc[:, idx[:, ['j', 'k']]] Out[37]: c d e f j j k k 0 0.750582 0.877763 0.262696 0.226005 1 0.025902 0.967179 0.125647 0.297304 2 0.463544 0.104973 0.154113 0.284820 3 0.631695 0.841023 0.820907 0.938378
-33160475 0 Dynamic column in jQuery DataTables In my application there are some columns that were given privileges. If the column is not given the right to access that particular column is not shown.
My code is like this : http://jsfiddle.net/oscar11/5jccbzdy/11/
// DataTable var table = $('#example').DataTable({ "order": [[0, 'asc']], "drawCallback": function (settings){ var api = this.api(); // Zero-based index of the column containing names var col_name = 0; // If ordered by column containing names if (api.order()[0][0] === col_name) { var rows = api.rows({ page: 'current' }).nodes(); var group_last = null; api.column(col_name, { page: 'current' }).data().each(function (name, index){ var group = name; var data = api.row(rows[index]).data(); if (group_last !== group) { $(rows[index]).before( '<tr class="group" style="background-color:' + data[4] + '"><td colspan="5">' + group + '</td></tr>' ); group_last = group; } }); } } });
How to make the above code becomes more dynamic and adjusting the number of columns that are given privileges?
If the number of columns that were given privileges: 5, then:
'<tr class="group" style="background-color:' + data[4] + '"><td colspan="5">' + group + '</td></tr>'
If the number of columns that were given privileges: 3, then:
'<tr class="group" style="background-color:' + data[2] + '"><td colspan="3">' + group + '</td></tr>'
Thank you
-37440671 0I think your problem is with the declaration of overFeature and outFeature.
Actually, while onSelect and onUnselect are template methods, designed to be overriden, overFeature and outFeature are not. Overriding those methods cause the override of the default behaviour ( layer.drawFeature(feature, style); ).
Anyway, I'd suggest you to use events instead. Try with
selectControlHover.events.register('featurehighlighted', null, function(e) { console.log('feature selected ', e.feature); });
Also, I'm quite sure that you can use one single control instead of two, but not knowing what you're trying to do, I can't suggest you another approach.
-16107749 0If you're running rails in development mode, it comes with webrick
by default which has access restricted just to localhost. You could use something like thin
in dev, which allows access from another machines.
I've made some boxes which will be be expanded and hidden by clicking on the titles of the boxes. I've just used slideToggle() for making it. I need another effect. Here is my fiddle: http://jsfiddle.net/qheJQ/
On that, I have three boxes: Slow Task, Different type of Task and Quick Tasks When anyone click on the Slow Task, the box will be expanded. If user click on Slow Task again, that box will be hidden. if user don't click again for hiding the Slow Task box and click Different type of Task, both the box will remain expanded. So, I want, when user click on Different type of Task, this box will be expanded and other boxes will be hidden if they are extended just like this accordion.
How can I get this without using any plugin for accordion?
My Script:
$('.title').click(function() { $(this).children('.arrow').toggleClass('arrow_up'); $(this).next('.box_expand').slideToggle(); });
-34254375 0 Can the multiplication of chars/digits be made more performant? I have following code where a sum is calculated, based on a very large series.
The series char *a
is a char array, which contains digits only (0..9).
I wanted to ask if there is any possibility to make the code faster. It is currently a bottle neck in a distributed computing application.
A small reproduction code. Not the actual code, and more simplified.
int top = 999999999; char *a; a = (char*) calloc(top+1, sizeof(char)); // ... fill a with initial values ... for (int i=0; i<10; ++i) { unsigned long long int sum = 0; for (m = 1, k = top; m < k; ++m, --k) { // Here is the bottle neck!! sum += a[m]*a[k]; } printf("%d\n", sum); // ... Add something at the end of a, and increase top ... }
I have already tried following:
Optimizing the code with -O3
(gcc compiler). The compiler line is now:
gcc -c -Wall -fopenmp -Wno-unused-function -O3 -std=c99 -g0 -march=native -pipe -D_FILE_OFFSET_BITS=64 -m64 -fwhole-program -fprefetch-loop-arrays -funsafe-loop-optimizations -Wunsafe-loop-optimizations -fselective-scheduling -fselective-scheduling2 -fsel-sched-pipelining -fsel-sched-pipelining-outer-loops -fgcse-sm -fgcse-lm -fgcse-las -fmodulo-sched -fgcse-after-reload -fsee -DLIBDIVIDE_USE_SSE2 -DLIBDIVIDE_USE_SSE4_1 xxx.c -o xxx.o
Using of GNU openMP to split the for-loop to multiple cores
unsigned long long int halfway = (top>>1) + 1; // = top/2 + 1 // digits is defined as top+1 #pragma omp parallel // firstprivate/*shared*/(a, digits, halfway) for (unsigned long long int m = 1; m < halfway; ++m) { sum += a[m] * a[digits-m]; }
Result: Much, much faster, but requires more cores, and I still would like to make it faster.
Casting a[m]
to unsigned long long int
before multiplication
sum += (unsigned long long int)a[m] * a[k];
Result: A small performance boost.
Using a multiplication lookup table, because an array-lookup is faster than the actual multiplication.
sum += multiply_lookup[a[m]][a[k]]; // a[m]*a[k];
Result: A small performance boost.
I have tried to find a mathematical solution to reduce operations, but it seems like nothing can be optimized, mathematically seen.
I have following idea for optimization:
I have read that the multiplication of floats (asm fmul
) is much faster than the multiplication of integers (asm mul
). Just changing int
to float
doesn't help -- but I think the code might become much more performant if the work is done using MMX or SSE instruction sets, or if the work is done by the FPU. Although I have some assembler knowledge, I have no knowledge about these topics.
However, if you have additional ideas how to optimize it, I am glad to hear them.
Update Some additional information:
top
gets increased.top
is reaching the array limit, a
will get increased by 100000 bytes using realloc()
.Additional off-topic question: Do you know the mathematical name of this sum, where the pairs of elements of the series are multiplied from outside to inside?
-23066371 0Without data/reproducible example is difficult to help you. But you can try something like:
ggplot(movies, aes(x = year, y = rating)) + stat_summary(geom="ribbon", fun.ymin = function(x) quantile(x, 0.05), fun.ymax = function(x) quantile(x, 0.95)) + stat_summary(geom="line", fun.y=median)
Hope it helps,
alex
-31409870 0 CPLEX and Bluemix integrationI am new to Bluemix and I want to use Cplex. I want to know if it is possible to integrate Cplex with Bluemix framework? Any examples are appreciated
-19601316 0Instead of taking a container as a parameter, take a pair of iterators:
template <typename Iter> void show(Iter first, Iter last) { while (first != last) { cout << *first++; } } vector<int> v; show(v.begin(), v.end()); deque<int> d; show(d.begin(), d.end()); int arr[10]; show(begin(arr), end(arr));
-1187941 0 I'm not sure if this will work, but you could try using:
<bean id="driverJob" .../>
instead of:
<bean name="driverJob" .../>
-32892462 0 "Value of optional type 'String?' not unwrapped; did you mean to use '!' or '?' ?" I have not been studying iOS or Swift for very long. With one of the latest Xcode updates, many of the apps I have made on my computer now appear to be using obsolete syntax.
Xcode talks us through converting it to new syntax but often that does not solve anything and I have a new problem. Here is code for one of the first app I made after the syntax has been converted. I am getting an error saying:
Value of optional type 'String?' not unwrapped; did you mean to use '!' or '?' ?
I know this must be really simple but I don't know how to fix it. Here is my code:
@IBAction func findAge(sender: AnyObject) { var enteredAge = Int(age.text) if enteredAge != nil { var catYears = enteredAge! * 7 resultLabel.text = "Your cat is \(catYears) in cat years" } else { resultLabel.text = "Please enter a whole number" } }
-1847105 0 How to determine which assembly a specific class belongs to? Often i have a problem that I need to determine which assebmly to include into my project in order to use specific class. For instance I want to you TypeInfo class. MSDN does not say it belongs to. Actually I am not even been able to find TypeInfo class using MSDN document explorer search. All the results relate to some other stuff. For instance first result is about System.Runtime.Remoting.
Also MSDN says - assembly mscorlib. In the components page of Add Reference dialog box i can see mscorlib but also fully qualified names like System.RunTime.Serialization
What is the difference?
-24218038 0 Replace Function with "," in string in access 2007Suppose I have:
Str1 = "Corpse" Str2 = "Co, p"
Now I want to use "Replace Function" and color "Co" and "p" in "Corpse". Can I do this?
x = Str1 y = Str2(?) z = "<font color=#ee00ee>" + y + "</font>" Replace(x, y, z)
-19115264 0 WordPress doesn't have wp_dropdown_posts
just like it has wp_dropdown_categories
and wp_dropdown_users
.
It has to be made by hand with get_posts
or WP_Query
, loop the results and make the <select><option>
. For your use case, I think you'll need to use the Custom Fields parameters.
You can find a sample code at WPSE: Dropdown list of a custom post type.
-11914289 0 How to add an Array of TextViews into a ListView?I got this piece of code that creates new TextView
, then adds it to ArrayList<View>
and when it is finished adding TextViews
to Array it sets adds that Array into ListView
. But somehow my ListView
is appearing empty. Any idea what am I doing wrong?
Here is the code:
ListView lv = (ListView) findViewById(R.id.listView1); ArrayList<View> textvs = new ArrayList<View>(); for (int i=0; i<10;i++) { TextView tv = new TextView(MainActivity.this); tv.setText(""+i); textvs.add(tv); } lv.addTouchables(portit); // lv is my listview
-20842093 0 Heroku: Python Flask app - automatically redirecting from https to http I'm writing an app for Facebook, which needs to be secure. The initial page, https://myapp.com, loads perfectly fine.
However when I click a link to https://myapp.com/link, Chrome complains that the app is trying to load from an insecure source. I get the following message in the console:
"[blocked] The page at 'https://www.facebook.com/page/app_###' was loaded over HTTPS, but ran insecure content from 'http://myapp.com/link/': this content should also be loaded over HTTPS."
Now the link is an absolute URL with the https prefix, yet apparently the page is trying to load from the http version.
I visited the domain itself and checked the Network tab in the Chrome console to see what was happening. The following happens:
As far as I can tell, there is nothing in my python code to make this happen, so I suspect some feature of Heroku is causing this, but I haven't been able to find anyone else with this problem.
As a side note, I used Flask-SSLify to add a redirect back to the https version. This redirect works, but Chrome still blocks the page because it passes through the insecure version.
-36156137 0Are you using Meteor 1.3 beta? If so you should not use react from Atmosphere, but from npm
(npm i react react-dom
).
Likewise, if you are using Meteor 1.2.1 or bellow, you should not use packages directly from npm
, but a wrapper from Atmosphere.
TextViews can only contain a small subset of HTML tags not CSS. These tags include <strong>
, <underline
>, <emphasis
>, <p>
, <small>
, <medium>
etc. There are a few others as well.
You can change the font and font colour by doing something like
<p font-color="blue">This is my blue text</p>
but you can't add CSS. If you need to do formatting in this way that would require CSS then a webview would be better.
-38804848 1 Select texts between tags in Xpath in Python<td width="250"> 10.03.1984 16:30 <br/> Lütfi Kırdar, İstanbul <br/> <br/> 47-38, 49-58, 8-10 </td>
I want to get all text between "td" tags. My code is mactarih=tree.xpath("//tr//td[@width='250']//text()") . But it is wrong.
The expected result is: text=['10.03.1984 16:30','Lütfi Kırdar, İstanbul','47-38, 49-58, 8-10']
-2995775 0Can you check by setting Send to back after adding the control?
-25297563 0You can use Tesseract with mcr.traineddata
language data file.
I'm running a few years old pretty big Rails 4.1 App, where one of the central models has a column called model_name
.
After the failed attempt to upgrade the app to rails 4.2, we have found out, that this column name is actually a rails reserved word. This did not come to our attention before, since the rails method which used the name, was a private method. Now, since rails 4.2 this is public, and rails complains big time over the naming confusion.
I really really really don't wanna rename the column, since it's referenced everywhere in our application, even in a lot of serialized data, historic URL's etc.
Any suggestions on an alternative upgrade procedure other than renaming the column?
-27345615 0In your code se1
still has its base type SalaryEmployee
where setSalesAmount
method does not exist.
I would say your program is badly designed.
-10712231 0 Is there a search engine for C++ commands?I do C++ and R programming since last 3 years.
I wish to know is there a search engine for C++ commands where I can find all the details regarding the command.
This is the example of what I am looking for: This is a search engine for R commands: http://www.rseek.org/
-20100886 0You can instantiate SimpleXMLElement and iterate through all its items.
-16338903 0 creating dependencies with other existing projectsthis my third various post about the same subject! Actually, I have three Spring maven-based project: let's name them projectA, projectB and projectC. all of them compose the same and unique project named myProject. I have no problem with projectA coz it compiles and built by importing it in eclipse, but with the both other, i have a real problem:projectB can't be built because first, it depends on projectA, second it gets jlibrtp and xuggler jar dependencies. In its pom file, all these dependences are declared but maven can't built it; error message like these: missing artifact projectA:jar missing artifact xuggle-xuggler ... projectC depends on both and the one file contained in this one is just the pom file.So same error messages there. I spent long time trying to resolve it but I'm out of skills now, i would you to help me to resolve this problem. If you think i would better explain it more, i'll do it, just make me aware. thank you!
-12105036 0 How to get gmail inbox feed from a nested labelAs specified here https://developers.google.com/google-apps/gmail/gmail_inbox_feed, I can get a feed of unread emails under a label 'work' by simply calling https://mail.google.com/mail/feed/atom/work/
But what to do in case I have nested labels? i.e. in case I have a label named 'Important' nested under 'Work'
-27739726 0I found a better solution by extending System.Windows.Forms.DataObject
Transferring Virtual Files to Windows Explorer in C#
also found some threads here on StackOverFlow that may help
Drag and drop large virtual files from C# to Windows Explorer
would be possible to pass javascript variable to php and execute function on it and convert it back to javascript
what I want is to get the value on click of an input field and deocode and pass it back
<script type="text/javascript"> $('.my_id').click(function(){ var lv = $('div.special_box form input').val(); var lv = <?php base64_decode( 'here should come my javascript variable' )?> }); </script>
-12686778 0 I think for posting comment main problem you will be having is with the login, before that you need to authorize user, for authorizing user you can use django-social-auth.
As you told that after save you want to do something, you can do it by overriding save function in model. For eg
class Updates(models.Model) ........... ........... def save(): super(save()) .................... # Do your job here ....................
Thanks
-34284353 0I am not an SQL Server expert but... Adding all the field length above I got 4,046
(I might have made few mistakes - it is too early here and I am still on the first coffee...). Now looking at the manual:
nchar [ ( n ) ] Fixed-length Unicode string data. n defines the string length and must be a value from 1 through 4,000. The storage size is two times n bytes. When the collation code page uses double-byte characters, the storage size is still n bytes. Depending on the string, the storage size of n bytes can be less than the value specified for n. The ISO synonyms for nchar are national char and national character..
Note that storing each characters requires two bytes. Doing 2 * 4046
we have 8092
bytes line length! Also note that nchar
is fixed length which I assume is allocated when an entry/row is created and thus it generates the error that you see, telling you that the line is too long. I would expect it to warn you at least when you create the table...
normalize more: Split the table into two, for example have an emploeeyAddress
table which can make sense if you later need home and work addresses for each employee
Use nvarchar
which is variable or dynamic length. The storage is still 2 bytes per character but only for the data inserted (not pre-allocated). You will hit the same limit if you try to populate all fields to their maximum length
I just want to understand how below code snippet work ?
class AnnaThread extends Thread { public static void main(String args[]){ Thread t = new AnnaThread(); t.start(); } public void run(){ System.out.println("Anna is here"); } public void start(){ System.out.println("Rocky is here"); } }
Output - Rocky is here
-28573387 0You may refer to the documentation.
[The garbage collector] may choose to clear atomically all soft references to that object and all soft references to any other softly-reachable objects from which that object is reachable through a chain of strong references.
[The garbage collector] will atomically clear all weak references to that object and all weak references to any other weakly-reachable objects from which that object is reachable through a chain of strong and soft references.
The point is moot for PhantomReference
because the referent cannot be retrieved from it (get
always returns null).
maybe I didn't understand OP's question well, why a simple grep command cannot do the job?
like
grep -Po 'OPR\d+'
output for both lines are same:
OPR20120126120537008893
-8500923 0 you may need to implement a switch using the value of ...
require('os').type()
and the use spawn("open") or spawn("xdg-open") depending on the platform?
-24375276 0You are probably getting this error because Access' Tabledefs list does not always immediately reflect changes you make, i.e. a delete. You can refresh it with CurrentDB.TableDefs.Refresh
after any .Append
s and/or .Delete
s, but this takes time, and considering that refreshing linked tables takes a significant amount of time each, time is something you may not be able to afford.
It is better practice to check your TableDefs
for pre-existing links and refresh them, not delete and recreate them, as deleting them also deletes any formatting, such as column widths and field formats that a refresh would leave unchanged.
If you have tables that need their links refreshed, change the .Connect
property, then use CurrentDB.TableDefs(TableName).RefreshLink
You should only be using CurrentDb.TableDefs.Delete tdf.Name
when the source table no longer exists.
I use a method similar to this myself, however I also store the date and time of the last linked table refresh, and only refresh those tables that had their schema modified after that time. With a hundred or more table links and 2+ seconds per table to refresh the links, I need to save all the time I can.
EDIT:
The following code is the code I use to perform a similar task linking MS Access to SQL Server.
Disclaimer: The following code is provided as-is, and will not work for a pure Access front-end/back-end situation. It will be necessary to modify it to suit your needs.
Public Sub RefreshLinkedTables() Dim adoConn As ADODB.Connection Dim arSQLObjects As ADODB.Recordset Dim CreateLink As Boolean, UpdateLink As Boolean, Found As Boolean Dim dWS As DAO.Workspace Dim dDB As DAO.Database Dim drSQLSchemas As DAO.Recordset, drSysVars As DAO.Recordset, drMSO As DAO.Recordset Dim dTDef As DAO.TableDef Dim ObjectTime As Date Dim sTStart As Double, sTEnd As Double, TStart As Double, TEnd As Double Dim CtrA As Long, ErrNo As Long Dim DescStr As String, SQLStr As String, ConnStr As String Dim SQLObjects() As String sTStart = PerfTimer() Set dWS = DBEngine.Workspaces(0) Set dDB = dWS.Databases(0) Set drSysVars = dDB.OpenRecordset("tbl_SysVars", dbOpenDynaset) If drSysVars.RecordCount = 0 Then Exit Sub AppendTxtMain "Refreshing Links to """ & drSysVars![ServerName] & """: """ & drSysVars![Database] & """ at " & Format(Now, "hh:mm:ss AMPM"), True Set adoConn = SQLConnection() Set arSQLObjects = New ADODB.Recordset SQLStr = "SELECT sys.schemas.name AS [Schema], sys.objects.*, sys.schemas.name + '.' + sys.objects.name AS SOName " & _ "FROM sys.objects INNER JOIN sys.schemas ON sys.objects.schema_id = sys.schemas.schema_id " & _ "WHERE (sys.objects.type IN ('U', 'V')) AND (sys.objects.is_ms_shipped = 0) " & _ "ORDER BY SOName" ObjectTime = Now() arSQLObjects.Open SQLStr, adoConn, adOpenStatic, adLockReadOnly, adCmdText Set drSQLSchemas = dWS.Databases(0).OpenRecordset("SELECT * FROM USys_tbl_SQLSchemas WHERE LinkObjects = True", dbOpenDynaset) Set drMSO = dWS.Databases(0).OpenRecordset("SELECT Name FROM MSysObjects WHERE Type In(1,4,6) ORDER BY Name", dbOpenSnapshot) ReDim SQLObjects(0 To arSQLObjects.RecordCount - 1) With arSQLObjects drMSO.MoveFirst If Not .EOF Then .MoveLast .MoveFirst End If prgProgress.Max = .RecordCount prgProgress = 0 CtrA = 0 ConnStr = "DRIVER={SQL Server Native Client 10.0};SERVER=" & drSysVars![ServerName] & ";DATABASE=" & drSysVars![Database] If Nz(drSysVars![UserName]) = "" Then ConnStr = ConnStr & ";Trusted_Connection=YES" Else ConnStr = ConnStr & ";Uid=" & drSysVars![UserName] & ";Pwd=" & drSysVars![Password] & ";" End If Do Until .EOF TStart = PerfTimer SQLObjects(CtrA) = arSQLObjects![Schema] & "_" & arSQLObjects![Name] AppendTxtMain ![SOName] & " (" & ![modify_date] & "): ", True drSQLSchemas.FindFirst "[SchemaID] = " & ![schema_id] If Not drSQLSchemas.NoMatch Then UpdateLink = False CreateLink = False drMSO.FindFirst "Name=""" & drSQLSchemas![SchemaName] & "_" & arSQLObjects![Name] & """" If drMSO.NoMatch Then CreateLink = True AppendTxtMain "Adding Link... " Set dTDef = dDB.CreateTableDef(arSQLObjects![Schema] & "_" & arSQLObjects![Name], dbAttachSavePWD, ![SOName], "ODBC;" & ConnStr) dDB.TableDefs.Append dTDef dDB.TableDefs(dTDef.Name).Properties.Append dTDef.CreateProperty("Description", dbText, "«Autolink»") ElseIf ![modify_date] >= Nz(drSysVars![SchemaUpdated], #1/1/1900#) Or RegexMatches(dDB.TableDefs(arSQLObjects![Schema] & "_" & arSQLObjects![Name]).Connect, "SERVER=(.+?);")(0).SubMatches(0) <> drSysVars![ServerName] _ Or (dDB.TableDefs(arSQLObjects![Schema] & "_" & arSQLObjects![Name]).Attributes And dbAttachSavePWD) <> dbAttachSavePWD Then UpdateLink = True AppendTxtMain "Refreshing Link... " With dDB.TableDefs(arSQLObjects![Schema] & "_" & arSQLObjects![Name]) .Attributes = dbAttachSavePWD .Connect = "ODBC;" & ConnStr .RefreshLink End With End If End If TEnd = PerfTimer() AppendTxtMain SplitTime(TEnd - TStart, 7, "s") .MoveNext prgProgress = prgProgress + 1 CtrA = CtrA + 1 Loop End With prgProgress = 0 prgProgress.Max = dDB.TableDefs.Count DoEvents dDB.TableDefs.Refresh TStart = PerfTimer() AppendTxtMain "Deleting obsolete linked tables, started " & Now() & "...", True For Each dTDef In dDB.TableDefs If dTDef.Connect <> "" Then ' Is a linked table... On Error Resume Next DescStr = dTDef.Properties("Description") ErrNo = Err.Number On Error GoTo 0 Select Case ErrNo Case 3270 ' Property does not exist ' Do nothing. Case 0 ' Has a Description. If RegEx(DescStr, "«Autolink»") Then ' Description includes "«Autolink»" Found = False For CtrA = 0 To UBound(SQLObjects) If SQLObjects(CtrA) = dTDef.Name Then Found = True Exit For End If Next If Not Found Then ' Delete if not in arSQLObjects AppendTxtMain "Deleting """ & dTDef.Name & """", True dDB.TableDefs.Delete dTDef.Name End If End If End Select End If prgProgress = prgProgress + 1 Next TEnd = PerfTimer() AppendTxtMain "Completed at " & Now() & " in " & SplitTime(TEnd - TStart, 7, "s"), True drSysVars.Edit drSysVars![SchemaUpdated] = ObjectTime drSysVars.Update drSQLSchemas.Close dDB.TableDefs.Refresh Application.RefreshDatabaseWindow Set drSQLSchemas = Nothing arSQLObjects.Close Set arSQLObjects = Nothing adoConn.Close Set adoConn = Nothing drSysVars.Close Set drSysVars = Nothing drMSO.Close Set drMSO = Nothing dDB.Close Set dDB = Nothing dWS.Close Set dWS = Nothing prgProgress = 0 End Sub
-31493755 0 AppleScript choose file dialog box with default location not working So there goes four hours of my life that I will never get back.
I'm trying to do something seemingly simple...
I want to open a file select dialog box and specify the default location.
I actually got this to work using the following...
choose file with prompt "Please choose a file:" of type {"XLSX", "APPL"} default location "/Users/lowken/Dropbox/"
This works and does exactly what I want (the file dialog opens up in the Dropbox folder).
However when I try to use a string variable it doesn't work...
set strPath to "/Users/lowken/Dropbox/" choose file with prompt "Please choose a file:" of type {"XLSX", "APPL"} default location strPath
Now the dialog box opens in the root directory of the hard drive :-(
It seems that the default location is being ignored however if the path is not correct Applescript does raise a error.
I've tried casting the value as a string. I even tried to use the POSIX format...
"Macintosh HD:Users:lowken:Dropbox"
This didn't format didn't work at all.
I'm running OS X Yosemite 10.10.4 on a mid 2012 MacBook Pro.
Can anyone help me?
-16098195 0 Retrieve elements of a CV_32FC3 CvMat?I'm creating a CvMat structure by calling
cvCreateMat(1,1,CV_32FC3);
This structure is filled by a subsequent OpenCV function call and fills it with three values (as far as I understand it, this is a 1x1 array with an additional depth of 3).
So how can I access these three values? A normal call to
CV_MAT_ELEM(myMat,float,0,0)
would not do the job since it expects only the arrays dimensions indices but not its depth. So how can I get these values?
Thanks!
-28484603 0 ejabberd users autocreation/export from dovecotI want ejabberd (ejabberd 14.12) to use Dovecot's table 'users' for authentication (which is done already) but keep all ejabberd's data in different mysql database.
Is there anything, like autocreation option? For example, if user was successfully authenticated via external script, create that user in ejabberd's database? Or I have to make this up by my own? Im new in ejabberd
For authentication, I have this in ejabberd.yml
auth_method: external extauth_program: "/opt/ejabberd/bin/auth_mysql_dovecot.php"
Will this allow me to use odbc as back-end?
-12906237 0 How do I create a parent from child in Rails?In my app I'm receiving this error.
Couldn't find Vendor with ID=1 for InventoryItem with ID=
InventoryItem.rb
belongs_to :vendor accepts_nested_attributes_for :vendor
Vendor.rb
has_many :inventory_items
_form.html.erb
<%= simple_nested_form_for @inventory_item, :html => {:class => 'form-inline' } do |f| %> <h2>Inventory Data</h2> <%= f.input :name, :input_html => {:autocomplete => :off, :placeholder => 'Item Name' }%> <%= f.input :id, :as => :hidden %> <%= f.simple_fields_for :vendor do |v| %> <%= v.input :name, :label => 'Vendor name', :input_html => {:autocomplete => :off, :placeholder => 'Vendor Name' } %> <%= v.input :id, :as => :hidden %> <% end %> <% end %> ----snip----
My parameters hash comes out accordingly
{"utf8"=>"✓", "authenticity_token"=>"ZY9fum4XGStTMNbpRQxrzmP7PT3A6BUU+wOymV0fZ/c=", "inventory_item"=>{"name"=>"testing", "id"=>"7678", "vendor_attributes"=>{"name"=>"test", "id"=>"1"}, "item_instances_attributes"=>{"0"=>{"barcode"=>"", "funding_source"=>"", "serial"=>"", "version"=>"", "website_id"=>"", "item_type"=>"Retail", "type_of_at"=>"Vision", "os"=>"Mac", "registration_key"=>"", "dealer_price"=>"", "retail_price"=>"", "reuse_price"=>"", "estimated_current_purchase_price"=>"", "cost_to_consumer_for_loan"=>"", "repair_status"=>"Working", "date_reviewed"=>"10-15-2012", "qr_url"=>"", "location"=>"", "restrictions"=>"", "notes"=>""}}}, "commit"=>"Create Inventory item"}
inventory_items_controller.rb
def create params[:inventory_item].delete(:estimated_dealer_price) @inventory_item = InventoryItem.create(params[:inventory_item]) @inventory_item.name = inventory_item.name.downcase if inventory_item.save redirect_to(inventory_items_path, :notice => "Item created.") else render 'new' end end
The controller is receiving the id and attempting to find the right vendor (which exists), has issues when left to the built-in rails methods for finding the vendor and building the relationship.
The input for vendor name is an autocomplete which assigns the id to the hidden id field.
possible solutions:
Change:
int a = tortoise(random, nt); int b = hare(random, nt);
into:
a = tortoise(random, a); b = hare(random, b);
Declare a
and b
before the loop:
int a=h, b=h;
-10388700 0 Do not pretend the Isolated Storage as a SQL Server. There will be great performance difference. If you want to process too much data, send them to server.
However, there is a method for getting a thumbnail. You can use it:
http://msdn.microsoft.com/en-us/library/system.drawing.image.getthumbnailimage.aspx
Also, please check this answer:
-8064340 0Instead of using myVar.IntProperty
can't you just put them in variables first, like you already did, and then use then for your method?
so method(intVar , strVar);
seems fine. At least more elegant than casting.
Of course, if you're already certain your object will have IntProperty
and StringProperty
, why not just make an actual object with those properties instead?
Refer to this SO Discussion which details the reasons for a problem similar to yours.
BETWEEN 'a' and 'b'
actually matches to columnValue >='a' and columnValue <= 'b'
In your case w52 is greater than w5 due to lexicographic ordering of Strings - this means that the BETWEEN
clause will never return a true (think about it as equivalent to saying BETWEEN 10 and 1
instead of BETWEEN 1 and 10
.
Edit to my response:
Refrain from storing the week value as a string. Instead here are a couple of approaches in order of their preference:
YEAR, WEEKNO
where YEAR
will store values like 2015, 2016 etc and WEEKNO
will store the week number. This way you can query data for any week in any year.$("#TextContent").wysihtml5({useLineBreaks: true, ...})
var myCustomTemplates = { custom1: function (context) { var s = "" s += '<li class="dropdown">'; s += '<a class="btn btn-default dropdown-toggle" data-toggle="dropdown" tabindex="-1" aria-expanded="false">'; s += '<span class="current-color">Size</span>'; s += '<b class="caret"></b>'; s += '</a>'; s += '<ul class="dropdown-menu" style="margin-top: 0px;">'; s += '<li><a class="fontSize" data-wysihtml5-command="fontSize" data-wysihtml5-command-value="fs5">5px</a></li>'; s += '</ul>'; s += '</li>'; return s; } };
$("#TextContent").wysihtml5( { customTemplates: myCustomTemplates, "stylesheets": ["~/Content/wysiwyg/editor.css"] });
editor.css
.wysiwyg-font-size-fs5 { font-size: 5px; }
-13061732 0 Thank You, but I resolved my issue. Instead of using XML I used JSON parsing and this is much more faster than XML parsing. I have used wikisuggest api and parsed it to show the suggestions as the user types. Sorry to say but I think no bounty now.
By the way thank you all for giving it attention and trying to solve my problem, I really appreciate all.
-22710210 0It's not possible out of the box. There is however a possible work around -
Lets assume the spacing wanted is 0.5 pixel, then you can:
ctx.scale(0.5, 0.5);
The scaling will force the pattern to sub-pixel so you get the appearance of "decimal lines". Just remember to scale back to original scale afterwards (use save()/restore() for a simple solution to that).
If you wanted the gap to be 0.33 then use 3 as a factor, 4 for 0.25 and so on.
-19004850 0Alternatively you can control can interface via netlink protocol. See http://www.pengutronix.de/software/libsocketcan/download/ or libnl (http://lists.infradead.org/pipermail/libnl/2012-November/000817.html)
-14706402 0 ViewExpiredException - Firefox onlyEnvironment: JBoss 5.1, RichFaces 3.3.3 Final, Facelets 1.1.15.B1, Seam 2.2.0
I am getting an unexpected ViewExpiredException with the following steps:
The thing is this - it only happens in a particular dialogue and only when using Firefox (Chrome & IE are OK). I can happily use other dialogues but once I get into this particular dialogue it goes belly up. I've trawled the forums looking for solutions and have tried a number of recommended things such as a custom ViewHandler to cope with the session expiring whilst the browser is sat on the login page but idle (this works fine - trying to extend it to pages other than login gives an " No Converter was created" exception ) and a filter to prevent caching (as described in this forum) but nothing seems to stop this happening. I've set the facelets context parameter BUILD_BEFORE_RESTORE which again didn't help
Anyone had a similar experience?
The dialogue in question is quite complex in structure and is built from several includes, decorates etc so is nigh on impossible to list unfortunately but then I'm not sure it would help anyway.
Any help would be very much appreciated
Ian
-3247417 0Let's do this.
• I know that lazy sequences only evaluate the items in the sequence that are asked for, how does it do this?
Lazy sequences (henceforth LS, because I am a LP, or Lazy Person) are composed of parts. The head, or the part(s, as really 32 elements are evaluated at a time, as of Clojure 1.1, and I think 1.2) of the sequence that have been evaluated, is followed by something called a thunk, which is basically a chunk of information (think of it as the rest of the your function that creates the sequence, unevaluated) waiting to be called. When it is called, the thunk evaluates however much is asked of it, and a new thunk is created, with context as necessary (how much has been called already, so it can resume from where it was before).
So you (take 10 (whole-numbers))
– assume whole-numbers
is a lazy sequence of whole numbers. That means you're forcing evaluation of thunks 10 times (though internally this may be a little difference depending on optimizations.
• What makes lazy sequences so efficient that they don't consume much stack?
This becomes clearer once you read the previous answer (I hope): unless you call for something in particular, nothing is evaluated. When you call for something, each element of the sequence can be evaluated individually, then discarded.
If the sequence is not lazy, oftentimes it is holding onto its head, which consumes heap space. If it is lazy, it is computed, then discarded, as it is not required for subsequent computations.
• How come you can wrap recursive calls in a lazy sequence and no longer get a stack over flow for large computations?
See the previous answer and consider: the lazy-seq
macro (from the documentation) will
will invoke the body only the first time seq is called, and will cache the result and return it on all subsequent seq calls.
Check out the filter
function for a cool LS that uses recursion:
(defn filter "Returns a lazy sequence of the items in coll for which (pred item) returns true. pred must be free of side-effects." [pred coll] (let [step (fn [p c] (when-let [s (seq c)] (if (p (first s)) (cons (first s) (filter p (rest s))) (recur p (rest s)))))] (lazy-seq (step pred coll))))
• What resources do lazy sequences consume to do what it does?
I'm not quite sure what you're asking here. LSs require memory and CPU cycles. They just don't keep banging the stack, and filling it up with results of the computations required to get the sequence elements.
• In what scenarios are lazy sequences inefficient?
When you're using small seqs that are fast to compute and won't be used much, making it an LS is inefficient because it requires another couple chars to create.
In all seriousness, unless you're trying to make something extremely performant, LSs are the way to go.
• In what scenarios are lazy sequences most efficient?
When you're dealing with seqs that are huge and you're only using bits and pieces of them, that is when you get the most benefit from using them.
Really, it's pretty much always better to use LSs over non-LSs, in terms of convenience, ease of understanding (once you get the hang of them) and reasoning about your code, and speed.
-22793855 0 How do I run a ldap query using R?I want to make a query against a LDAP directory of how employees are distributed in departments and groups...
Something like: "Give me the department name of all the members of a group" and then use R to make a frequency analysis, but I can not find any examples on how to connect and run a LDAP query using R.
RCurl seems to have some kind of support ( http://cran.r-project.org/web/packages/RCurl/index.html ):
Additionally, the underlying implementation is robust and extensive, supporting FTP/FTPS/TFTP (uploads and downloads), SSL/HTTPS, telnet, dict, ldap, and also supports cookies, redirects, authentication, etc.
But I am no expert in R and have not been able to find a single example using RCurl (or any other R library) to do this..
Right now I am using CURL like this to obtain the members of a group:
curl "ldap://ldap.replaceme.com/o=replaceme.com?memberuid?sub?(cn=group-name)"
Anyone here knows how to do the same in R with RCurl?
-10992871 0 CodeIgniter: Passing information from the Model to the Controller using result_array()I have the following model that print_r
shows Array ( [id] => 1 [cms_name] => Content Mangement System )
Currently in my controller I have $data['contentMangement'] = $this->model->function
but I am unsure how to bring my above array into this.
function systemOptions($options) { $this->db->select($options); $query = $this->db->get('options'); if($query->num_rows() > 0) { $row = $query->row_array(); $row['cms_name']; } print_r($row); return $query->result_array(); }
-2175388 0 Yes, you can do this by implementing ISerializationSurrogate and ISurrogateSelector interfaces.
Something like this:
[AttributeUsage(AttributeTargets.Class)] public class SerializeLinqEntities : Attribute { } public class LinqEntitiesSurrogate : ISerializationSurrogate { public void GetObjectData( object obj, SerializationInfo info, StreamingContext context) { EntitySerializer.Serialize(this, obj.GetType(), info, context); } public object SetObjectData( object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector) { EntitySerializer.Deerialize(obj, obj.GetType(), info, context); return obj; } } /// <summary> /// Returns LinqEntitySurrogate for all types marked SerializeLinqEntities /// </summary> public class NonSerializableSurrogateSelector : ISurrogateSelector { public void ChainSelector(ISurrogateSelector selector) { throw new NotImplementedException(); } public ISurrogateSelector GetNextSelector() { throw new NotImplementedException(); } public ISerializationSurrogate GetSurrogate( Type type, StreamingContext context, out ISurrogateSelector selector) { if (!type.IsDefined(typeof(SerializeLinqEntities), false)) { //type not marked SerializeLinqEntities selector = null; return null; } selector = this; return new LinqEntitiesSurrogate(); } } [SerializeLinqEntities] public class TestSurrogate { public int Id { get; set; } public string Name { get; set; } } class Program { static void Main(string[] str) { var ns1 = new TestSurrogate {Id = 47, Name = "TestName"}; var formatter = new BinaryFormatter(); formatter.SurrogateSelector = new NonSerializableSurrogateSelector(); using (var ms = new MemoryStream()) { formatter.Serialize(ms, ns1); ms.Position = 0; var ns2 = (TestSurrogate) formatter.Deserialize(ms); // Check serialization Debug.Assert(ns1.Id == ns2.Id); Debug.Assert(ns1.Name == ns2.Name); } } }
-37730575 1 Object has no attribute 'encode' I'm trying to attach an xlsx file to my email. I looked up solutions and it involves using email.encoders. But when I use this solution I get an error. I'm using a solution that someone else has working.
File "C:\Documents and Settings\Desktop\AppTera\dev\MTC_test\MTC_sender.py", line 41, in sendmail s.sendmail(FROMADDR, TOADDR, message.as_string()) AttributeError: 'list' object has no attribute 'encode'
def sendmail(): SERVER = 'server.com' FROMADDR = "joe@example.com" TOADDR = ['bob@example.com'] CCADDR = ['bill@example.com'] message = MIMEMultipart('mixed') message['From'] = FROMADDR message['To'] = TOADDR message['Subject'] = "Reporting for IVR Application" BODY = "Hello Angela,\n\nI'm attaching the reports for %s/%s. These are the same reports\ you have requested in the past.\n\nPlease let me know if you need any additional reports.\n\n\ Thank you"% (str(MONTH), str(YEAR)) message.attach(MIMEText(BODY, 'plain')) filename = "results.csv.xlsx" path = r'C:\Documents and Settings\Desktop\MonthlyReports\MTC\%s_%s' % (str(YEAR), str(MONTH)) os.chdir(path) fileMsg = MIMEBase('application', 'xlsx') fileMsg.set_payload(open('results.csv.xlsx', 'rb').read()) encoders.encode_base64(fileMsg) fileMsg.add_header('Content-Disposition','attachment;filename=results.csv.xls') message.attach(fileMsg) s = smtplib.SMTP(SERVER, 25) s.set_debuglevel(1) s.sendmail(FROMADDR, TOADDR, message.as_string()) s.quit()
Is there another way that I can send an attached file along with a body message?
-6346862 0Replace every occurrence of TODAY() with DATE(2011,9,1):
=YEAR(DATE(2011,9,1))-YEAR(C2)-1 + (MONTH(DATE(2011,9,1))>MONTH(C2)) + (MONTH(C2)=MONTH(DATE(2011,9,1)))*(DAY(DATE(2011,9,1))>=DAY(C2))
For a person born on the date in cell C2, this would give what their age will be on Sept 1, 2011.
Edit: Or, more simply, try this:
=2011-YEAR(C2)-1 + 9>MONTH(C2) + (MONTH(C2)=9)*(1>=DAY(C2))
-26913506 0 HTML Data not displaying as I want, (PHP array) I have all my data stored in array's
<div class="box"> <div class="box-header"> <h3 class="box-title">History Page Station Number: <? php if($_POST){ $id; }?> </h3> </div><!-- /.box-header --> <div class="box-body table-responsive"> <table id="example2" class="table table-bordered table- hover"> <thead> <tr> <th> Station Name</td> <th> Country </th> <th> Date </th> <th> Timestamp </th> <th> Temperature(celcius) </th> <th> Rainfall(mm)</th> <th> Windspeed(km/h)</th> </tr> </thead> <tbody> <!-- loop displaying all data --> <?php if($_POST){ $cols = 1; for ($i=1; $i < count($wind); $i++) { echo "<tr>"; for ($c=0; $c<$cols; $c++) { echo "<td>".$station->name."</td>"; echo "<td>".$station->country."</td>"; echo "<td>".$date[$i]."</td>"; echo "<td>".$time[$i]."</td>"; echo "<td>".$temp[$i]."</td>"; echo "<td>".$rain[$i]."</td>"; echo "<td>".$wind[$i]."</td>"; } echo "</tr>"; } } ?> </tbody> <tfoot> <tr> <th> Station Name</td> <th> Country </th> <th> Date </th> <th> Timestamp </th> <th> Temperature(celcius) </th> <th> Rainfall(mm)</th> <th> Windspeed(km/h)</th> </tr> </tfoot> </table> </div><!-- /.box-body --> </div><!-- /.box -->
When I check the output its displaying element[0] in the first row
Element[0] in 2nd row Element[1] in 3rd Element[0] in 4 Element[1] in 5 Element[2] in 6 etc
it starts at first element again and adds 1.. I dont know what im doing wrong.
I have 22 different elements in my array
-11790987 0Find out where the time is spent
add the StopWatch in the method which you said "more that 2 minutes for a button click". you can find which statment spent the most time.
If it is a query on DB that cost time. Check your sql statement.
are you using "SELECT Count(*)" instead of "SELECT Count(Id)"? the * is always slower. also, don't try "SELECT * FROM...."
Use cache.
there are many ways to do cache. both in ASPX pages and your biz layer. the OutputCache is the most easy way.
and also, cache the page (for example a blog post) on the first time when a user visit it.
Did you use memory paging?
be careful when doing paging on gridview or other list. If you just call DataSource=xxx and DataBind(), even with PagedDataSource, this is likely a memory paging. It cost a lot of performance. Please use stored procedures to do paging.
Check your server environment
where did you deploy the website? many ISP will limit brandwide and IIS connection count and also CPU time to your account.
if you have RD access to your server. you can watch CPU and memory usage to see if they are high when many user comes to your site. If the site is slow and neither CPU nor memory useage is high, it may be a network brandwide problem.
Can we use grid lines to align shapes or images in PowerPoint using VBA? Are there any properties which are related to grid line?
-11693124 0Or you can use $_REQUEST['hitme']
, this one will check both $_POST['hitme']
and $_GET['hitme']
You can use a subquery to make calculations by day and after that make calculations by country. The result SQL query can be like this:
-- Make calculation by country, from the subquery SELECT Country, UniqueDays = count(TheDay), CallsUserPerDay = sum(CallsPerUser), FinalCalc = sum(CallsPerUser) / cast(count(TheDay) as DECIMAL) FROM ( -- SUBQUERY: Make calculations by day SELECT c.Country, c.ActualStart as TheDay, Calls = COUNT(c.CallID), Users = COUNT(Distinct c.UserID), COUNT(c.CallID) /CAST(COUNT(Distinct c.UserID) AS DECIMAL) as CallsPerUser FROM CallInfo as c WHERE (c.Status = 3) GROUP BY c.Country, c.ActualStart ) data GROUP BY Country
Note: I avoid use precission on DECIMAL casting to avoid rounding on final result.
-34051131 0you're not implementing background processes, you're trying to start a background process using the syntax of the already-implemented-shell on your computer (but honestly, it's pretty hard to tell what's going on with that indentation. That's really bad. Can you make it readable, please?). That '&' character is recognised by your shell, not by execvp. Have a look at this similar looking question which was the first hit in a google search for your problem.
-14692739 0 Batch to compare last-modify from two files in different foldersI want a batch file that will compare the last-modify
date of two different files located in two different folders. If the local file is older than the server file, I want to overwrite the local file.
All I've found yet it a comparing the files with the dir
command, which only works when both files are in the same folder (eg. dir /b /OD file1.txt file2.txt
).
This is what I got actually, just need to add the comparison:
set "source=\\server\myApp.otm" set "target=%userprofile%\Application Data\myApp\" copy /Y /B "%source%" "%target%" start outlook.exe /altvba "%target%\myApp.otm"
As you can see, the batch file is here to start Outlook with the VBA *OTM* file in parameter. I don't want to copy the 10MB file from the server each time if it isn't needed, thus the need for a comparison of last-modify
dates (filesize
would be okay too I guess).
I would at least consider doing this job somewhat differently. Right now, you're reading a word at a time, then putting the words back together until you get to a period.
One possible alternative would be to use std::getline
to read input until you get to a period, and put the whole string into the vector at once. Code to do the job this way could look something like this:
#include <iostream> #include <string> #include <algorithm> #include <vector> #include <iterator> int main() { std::vector<std::string> s; std::string temp; while (std::getline(std::cin, temp, '.')) s.push_back(temp); std::transform(s.begin(), s.end(), std::ostream_iterator<std::string>(std::cout, ".\n"), [](std::string const &s) { return s.substr(s.find_first_not_of(" \t\n")); }); }
This does behave differently in one circumstance--if you have a period somewhere other than at the end of a word, the original code will ignore that period (won't treat it as the end of a sentence) but this will. The obvious place this would make a difference would be if the input contained a number with a decimal point (e.g., 1.234
), which this would break at the decimal point, so it would treat the 1
as the end of one sentence, and the 234
as the beginning of another. If, however, you don't need to deal with that type of input, this can simplify the code considerably.
If the sentences might contain decimal points, then I'd probably write the code more like this:
#include <iostream> #include <string> #include <algorithm> #include <vector> #include <iterator> class sentence { std::string data; public: friend std::istream &operator>>(std::istream &is, sentence &s) { std::string temp, word; while (is >> word) { temp += word + ' '; if (word.back() == '.') break; } s.data = temp; return is; } operator std::string() const { return data; } }; int main() { std::copy(std::istream_iterator<sentence>(std::cin), std::istream_iterator<sentence>(), std::ostream_iterator<std::string>(std::cout, "\n")); }
Although somewhat longer and more complex, at least to me it still seems (considerably) simpler than the code in the question. I guess it's different in one way--it detects the end of the input by...detecting the end of the input, rather than depending on the input to contain a special delimiter to mark the end of the input. If you're running it interactively, you'll typically need to use a special key combination to signal the end of input (e.g., Ctrl+D on Linux/Unix, or F6 on Windows).
In any case, it's probably worth considering a fundamental difference between this code and the code in the question: this defines a sentence as a type, where the original code just leaves everything as strings, and manipulates strings. This defines an operator>>
for a sentence, that reads a sentence from a stream as we want it read. This gives us a type we can manipulate as an object. Since it's like a string in other ways, we provide a conversion to string so once you're done reading one from a stream, you can just treat it as a string. Having done that, we can (for example) use a standard algorithm to read sentences from standard input, and write them to standard output, with a new-line after each to separate them.
Note I'm assuming you just have the data part of the string, not an entire JSON fragment - i.e.
string s = @"blah \u003c blah \u00252 blah";
If the above assumption is wrong and you have a full JSON fragment, just use JavaScriptSerializer
to get an object from the data.
Annoyingly, HttpUtility
has encode but not decode.
You could spoof the string into a full JSON object, though - this seems a bit overkill:
class Dummy { public string foo { get; set; } } static void Main(string[] args) { string s = @"blah \u003c blah \u00252 blah"; string json = @"{""foo"":""" + s + @"""}"; string unencoded = new JavaScriptSerializer().Deserialize<Dummy>(json).foo; }
-17954648 0 unable to correctly define edittexts in java I am trying to define 3 edittexts adjacent to each other in java.
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // LinearLayout mainLayout=(LinearLayout)findViewById(R.id.linearLayout); // LinearLayout -> RelativeLayout main=new RelativeLayout(this); mainParams=new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT ); main.setLayoutParams(mainParams); mainLayout.addView(main); // LinearLayout -> RelativeLayout -> EditText1 EditText item1=new EditText(this); item1.setHint("Enter the item"); item1.setId(5); RelativeLayout.LayoutParams etParams=new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); etParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT); item1.setLayoutParams(etParams); main.addView(item1); // LinearLayout -> RelativeLayout -> EditText2 EditText quantity1=new EditText(this); item1.setHint("Quantity"); item1.setId(6); RelativeLayout.LayoutParams qparams=new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); etParams.addRule(RelativeLayout.ALIGN_LEFT, 5); item1.setLayoutParams(qparams); main.addView(quantity1); // LinearLayout -> RelativeLayout -> EditText3 EditText rate1=new EditText(this); item1.setHint("rate"); item1.setId(7); RelativeLayout.LayoutParams rparams=new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); etParams.addRule(RelativeLayout.ALIGN_RIGHT, 6); item1.setLayoutParams(rparams); main.addView(rate1);
`
I know you might be thinking that i can also do it in xml but the thing is that i have to create more edittexts at runtime.
The problem is that all the editTexts are overlapping each other. plz help
-16509197 0 I can not find the same extension in the Open DialogWhy sometimes in the Open dialog I cannot load the same file extension on the Open dialog filters, so I had to refresh the first to find the file.
E.g.: Filter = *.jpg
I can not find the file *.jpg
in Explorer Open dialog, but there are a lot of images with extension *.jpg
.
This happens on Win 7 OS [x86 & x64]. The compiler version I am using is Delphi 7.
procedure TForm1.Button1Click(Sender: TObject); var JpgIF: TJpegImage; BmpIF: TBitmap; begin JpgIF := TJpegImage.Create; BmpIF := TBitmap.Create; OD.FileName := ''; OD.DefaultExt := '*.jpg;*.jpeg;*.psd;*.tga*.png;*.gif;*.bmp'; OD.Filter := 'JPG|*.jpg|Jpeg|*.jpeg|PSD|*.psd|TGA|*.tga|PNG|*.png|GIF|*.gif|Bmp|*.bmp'; if not OD.Execute then Exit else if LowerCase(ExtractFileExt(OD.FileName)) = '.jpg' then begin JpgIF.LoadFromFile(OD.FileName); Img1.Picture.Bitmap.Assign(JpgIF); end else begin if LowerCase(ExtractFileExt(OD.FileName)) = '.bmp' then begin BmpIF.LoadFromFile(OD.FileName); Img1.Picture.Bitmap.Assign(BmpIF); end; //etc... end; JpgIF.Free; BmpIF.Free; end;
-25745805 0 When you include a report id in your report descriptor then all HID reports (on that interface) must be prefixed with a report id. In your case you would need to send a 3 byte report:
0x01 0xcd 0x00
...or remove the report id from your report descriptor.
-11908034 0I have no idea what the question in there is, but I'll offer:
where ( param1 is not NULL or param2 is not NULL ) and ( ( ( col1 like param1 ) or param1 is NULL ) or ( ( col2 like param2 ) or param2 is NULL ) )
-33583653 0 Put your code in an override
of layoutSubviews
so that it uses the updated bounds:
override func layoutSubviews() { super.layoutSubviews() let maskLayer = CAShapeLayer() maskLayer.path = UIBezierPath(roundedRect: bounds, byRoundingCorners: [.BottomLeft, .BottomRight], cornerRadii: CGSizeMake(20, 20)).CGPath self.layer.mask = maskLayer }
-37161455 0 List<Person> persons = Person.findAll(Person.class);
Will give you all Person records.
-18835981 0 Install problems: Nokogiri on Mac OSx Mountain LionFor some reason I cannot install Nokogiri on my MacBook for traveling.
This is short output from gem install nokogiri
:
Extracting libxml2-2.8.0.tar.gz into tmp/x86_64-apple-darwin12/ports/libxml2/2.8.0... OK Running 'configure' for libxml2 2.8.0... OK Running 'compile' for libxml2 2.8.0... OK Running 'install' for libxml2 2.8.0... OK Activating libxml2 2.8.0 (from /Users/jseidel/.rvm/gems/ruby-1.9.3-p327@rails3213/gems/nokogiri-1.6.0/ports/x86_64-apple-darwin12/libxml2/2.8.0)... Extracting libxslt-1.1.26.tar.gz into tmp/x86_64-apple-darwin12/ports/libxslt/1.1.26... OK Running 'configure' for libxslt 1.1.26... OK Running 'compile' for libxslt 1.1.26... OK Running 'install' for libxslt 1.1.26... OK Activating libxslt 1.1.26 (from /Users/jseidel/.rvm/gems/ruby-1.9.3-p327@rails3213/gems/nokogiri-1.6.0/ports/x86_64-apple-darwin12/libxslt/1.1.26)... checking for libxml/parser.h... yes checking for libxslt/xslt.h... yes checking for libexslt/exslt.h... yes checking for iconv_open() in iconv.h... yes checking for xmlParseDoc() in -lxml2... no ----- libxml2 is missing. please visit http://nokogiri.org/tutorials/installing_nokogiri.html for help with installing dependencies.
However, I used MacPorts and it says that it's already installed:
port installed | grep lib libxml @1.8.17_0 (active) libxml2 @2.9.1_0 (active)
Is it getting confused because both libxml and libxml2 are installed? (Probably not.) Or is there something else going on?
I've followed the installation instructions for Nokigiri installation and that doesn't help.
Finally, I uninstalled ports libxml and libxml2 and now it fails attempting to use libiconv, having gotten past the previous XML issue it seems.
-22929105 0You are treating an array of integers like an array of chars. The line that is marked as "means nothing" actually means a lot.
When you increment char* p
by one, you shift your pointer one byte, but in order to point to the arr[1]
you need to increment it sizeof(int)
bytes. Declare p
as int* p
, then p+1
will do what you need.
Since it's a new closure, the meaning of this
is lost. this
has always been a tricky thing to deal with, so I prefer to always start such a function with var that = this
to ensure that the meaning is not lost within closures.
You can not name functions numbers, try this,
<input type="button" value="test" /> $('input[type=button]').click( function() { alert("test"); });
Sometimes jsfiddle can be a pain when doing alert functions.
You have to make sure to separate your html
css
and js
as much as you can and leave out script tags
Here is a working example,
-26146782 0You are getting a cross domain error because some properties on the window (global) object are not accessible within the iframe, assuming you should be allowed to access the global variable you are trying to read (because its in the iframe itself), you can wrap the inner part of the loop in a try catch block, this way it will continue after getting an access denied. See code:
var listScopeVars = function(scope) { for (var prop in scope) { try{ if(scope[prop] && typeof(scope[prop]) != "function") { console.log(prop + "=" + scope[prop]); } }catch(e){ console.log("Error: "+e.message); //or use console.error("Error: "+e.message); } } };
-15628273 0 This is a WordPress site I believe?
If so you need to look at editing the theme template file that is responsible for showing the preview of your post on the category pages and remove the section where it is showing images/videos from the post.
Unfortunately not knowing what theme it is you are using or what the file names are called it's hard to tell but look for a page template which has the word home or categories in it or open up the category.php from within your activated theme folder if you have them to see if you can find something related to this and comment it out to see if it fixes it.
Also try adding the following inside your custom function:
$content = preg_replace("/<embed[^>]+>/i", "", $content, 1);
-5223012 0 The connections strings that I use look like
<add name="myOracleConnection" connectionString="Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=MyServer)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=XE))); User Id=MyUser; Password=MyPassword;" providerName="system.data.oracleclient"/>
I.e. I do not rely on these external configuration files (were they named .ora
? I forgot it).
Maybe you can lower dependencies and side-effects if you also try to make your connection string self-containing with everything included?
-26136894 1 Why does tuple(set([1,"a","b","c","z","f"])) == tuple(set(["a","b","c","z","f",1])) 85% of the time with hash randomization enabled?Given Zero Piraeus' answer to another question, we have that
x = tuple(set([1, "a", "b", "c", "z", "f"])) y = tuple(set(["a", "b", "c", "z", "f", 1])) print(x == y)
Prints True
about 85% of the time with hash randomization enabled. Why 85%?
The simple answer is you don't debug through a compressed file - you use an uncompressed version for development.
-5164487 0The way doctrine creates tables in the db is by loading the models and reading the definitions within each of these models. If the CLI is not able to load the models then the table creation will fail. Unfortunately the CLI task does not report this.
Further I would advise you to check other CLI tasks such as generate-migrations-diff and migrate. I have had issues with these in the past and have resolved them successfully.
-27480594 0I think all you need to have is a so called application defined in your Wowza Streaming Servier, which I guess you already have. This application, let's suppose it's called live
can receive multiple live streams from different sources, e.g. GoCoders. Each source can publish a stream with custom name into your application, and then you can choose which one to play in your JW Player's setup, by specifying the stream name in the URL.
(It's not clear to me if you wanted to play multiple videos simultaneously in the same JW Player instance, in a picture-in-picture style.)
-15868721 0 Unable to grant external access to published web appI'm working on Web App using Google App Script. I'm a Google Apps reseller and would like to be able to share my Web App with other Google Apps users that I sign up.
The web app is currently stored in my Drive. When I deploy the app the only options I have available under Who has access to the app are
I've gone into my Google Apps domain management and set Drive permissions so that users can share documents outside this organization. I've also tried to share the script from Google Drive and the Google Apps Script interface, but the only sharing options are:
I've also tried explicitly sharing the script (can view) with an email address of a Google Apps user, on another domain, but I get a Sorry, the file you have requested does not exist. error. You can probably see the result by trying to view the web app at this url
The only other cause I can think of is that I registered my Google Apps account when Google still gave 50 free user accounts per domain.
Any ideas?
-11193167 0 intercept data changes and alter/validate from a serverI'm working on a solution to intercept changes to the data from our node.js server and validate/alter them before they are stored/synced to other clients.
Any strategies or suggestions on how to solve this with the current code base?
Currently, it seems like the only option is to rewrite it post-sync operation. That would mean each client would probably receive the sync (including the server), then the server would rewrite the data and trigger a second sync.
To help understand the context of the question, here's what seems like an ideal strategy for my needs:
firebase.child('widgets').beforeSync(myCallback)
without understanding way more than I care to know about your data model and you business it's hard to give concrete positive advice. But here are some notes about your indexing strategy and why I would guess the optimizer is not using the indxes you have.
In the sub-query the access path to REDLINE_MSATTRIBUTE drives from three columns:
CLASS is not indexed. but that is presumably not very selective. OBJECT_ID is the leading column of a compound index but the other columns are irrelevant the sub-query.
But the biggest problem is CHANGE_RELEASE_DATE. This is not indexed at all. Which is bad news, as your one primary key look up produces a date which is then compared with CHANGE_RELEASE_DATE. If a column is not indexed teh database has to read the table to get its values.
The main query drives off
ATTID is indexed but how sleective is that index? The optimizer probably doesn't think it's very selective. ATTID is also in a compound index with CHANGE_ID and OLD_VALUE but none of them are the leading columns, so that's not very useful. And we've discussed CLASS, CHANGE_RELEASE_DATE and OBJECT_ID already.
The optimizer will only choose to use an index if it is cheaper (fewer reads) than a table scan. This usually means WHERE clause criteria need to map to the leading (i.e. leftmost) columns of an index. This could be the case with OBJECT_ID and ATTID in the sub-query except that
So, you might get some improvement by building an index on (CHANGE_RELEASE_DATE, CLASS, OBJECT_ID, ATTID)
. But as I said upfront, without knowing more about your situation these are just ill-informed guesses.
self.ages = [ageValues allKeys];
or ages = [[ageValues allKeys] retain];
I have built facebook app. It's hosted on: http://resihop.herokuapp.com/.
The app is suppose to be visible here: https://apps.facebook.com/393963983989013/
On facebook it's embedded in an iframe. The weird part is that for some users the content of the iframe is empty, just: and for some users it displays the page. Here is the html: that I got from inspect element:
Working:
<div> <noscript><div class="mas"><div class="pam uiBoxRed">Du måste ha javascript aktiverat i din webbläsare för att använda Facebook-applikationer.</div></div></noscript> <form action="https://resihop.herokuapp.com/?fb_source=search&ref=ts" method="post" target="iframe_canvas_fb_https" id="canvas_iframe_post_4fe8ad942b9be6531902412" onsubmit="return Event.__inlineSubmit(this,event)"> <input type="hidden" autocomplete="off" name="signed_request" value="x4b_ddxAkL71eQEdopzIZJpWZCmTPFqOMmmMvx_TCC8.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsImV4cGlyZXMiOjEzNDA2NTQ0MDAsImlzc3VlZF9hdCI6MTM0MDY0ODg1Miwib2F1dGhfdG9rZW4iOiJBQUFGbVR1TlI2UlVCQU9zQkRkc2hwbkpNN0pKR0ZaQTNsaGhtMlViNWFlWkFpeFpDNnNYcWVEbXpaQjVqb1dtVUwzVTg1WW5wUWg2WkJVdUxQV3o2M1lIQk5aQVQ4a3dNNGNtWkExZU00MXZ5SU5KeVpDeWFpbDhWIiwidXNlciI6eyJjb3VudHJ5Ijoic2UiLCJsb2NhbGUiOiJzdl9TRSIsImFnZSI6eyJtaW4iOjIxfX0sInVzZXJfaWQiOiIxMDAwMDA2MjcwMTQzODQifQ"> </form> <iframe class="smart_sizing_iframe" frameborder="0" scrolling="yes" id="iframe_canvas" name="iframe_canvas_fb_https" src='javascript:""' height="800" style="height: 574px; "></iframe> </div>
Broken:
<div> <noscript><div class="mas"><div class="pam uiBoxRed">You need Javascript enabled in your browser to use Facebook Applications.</div></div></noscript> <form action="https://resihop.herokuapp.com/" method="post" target="iframe_canvas_fb_https" id="canvas_iframe_post_4fe8adec0223e0f59580030" onsubmit="return Event.__inlineSubmit(this,event)"> <input type="hidden" autocomplete="off" name="signed_request" value="yx5eMWJ-0WFSOHg5bkfxesurLc5zZcfuYdyuJqffv0M.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsImV4cGlyZXMiOjEzNDA2NTQ0MDAsImlzc3VlZF9hdCI6MTM0MDY0ODk0MCwib2F1dGhfdG9rZW4iOiJBQUFGbVR1TlI2UlVCQUJ6NVRxdWRuaW1tN01ZVzRkdXhSMHczTU1zcDZvbU9ZZ3ZZVm1zZG11dVJLN1lEb1h6Mm9TYUFIeUpaQ2NsSjg5cFBFWkJaQ2haQURyMGZCWWIxOUxaQ0o0QnVaQnR3WkRaRCIsInVzZXIiOnsiY291bnRyeSI6InNlIiwibG9jYWxlIjoiZW5fVVMiLCJhZ2UiOnsibWluIjoyMX19LCJ1c2VyX2lkIjoiNjUxNjY2NDgzIn0"></form> <iframe class="smart_sizing_iframe" frameborder="0" scrolling="yes" id="iframe_canvas" name="iframe_canvas_fb_https" src='javascript:""' height="800" style="height: 294px; "></iframe> </div>
One difference I have noticed is that the actions are different. I have waited for several hours now, so it might be a server-unsync-thing, but probably not.
-13222676 0You can use Process
and Runtime
classes
Eg :
Runtime r = Runtime.getRuntime(); Process p = r.getRuntime().exec("C:\\newfolder\\run.exe");
For taking screenshot refer to how to take sc in java
This way you can save the image and then send this image to user.
For sending image to client refer to how to send file from sever to client
these are.the pieces , you need to put them together
UPDATE 1 : to kill the exe you can use p.destroy()
( not a good implementation though, as it forcefully kills the process)
UPDATE2 : to check if the process( which is executing your exe) hence to check if the exe is running or not, you can refer to how to check if a process is running
-2284 0 How to contribute code back to an Open Source project?If you're following an Open Source project and would like to contribute code changes, what will you need to do?
-31082197 0Seems there are some basics which are not clear to you.
Members are always private and to interact them you should create public setter and getter.
public List getUsers(){ return users; }
public void getUsers(List users){ this.users=users; }
As a good coding standard, the naming should describe the behavior which provides specific action Hence
User addUser(String name)
seems very ambiguous considering it's actual implementation as given adds User to the list.
If DB class is a dependency then it should be instantiated Let's assume you are calling this code from main
User user= new User(); DB dbInstance=new DB(); dbInstance.setUsers(new ArrayList()); dbInstance.getUsers().add(user);
To provide a more specific answer awaiting further requested details
-3356905 0I figured out a way somehow. Actually it is in "http://msdn.microsoft.com/en-us/library/ms752347.aspx"
ListBox ItemsSource="{**Binding**}" IsSynchronizedWithCurrentItem="true"/>
Note that although we have emphasized that the Path to the value to use is one of the four necessary components of a binding, in the scenarios which you want to bind to an entire object, the value to use would be the same as the binding source object. In those cases, it is applicable to not specify a Path. Consider the following example:
XAML Copy
-19416528 0 Java : Method return IssueHi there I have created a class to run another Test class but I am facing some problems. I have declared both the agePremium and ticketPremium as private doubles. I later on use them in 2 methods to calculate the premium respectively. But when it gets to the part where i want t use the calculated variables in another calculation here
/* public double premium() { if (ticket <4){ return ((BASE_PREMIUM*value) * agePremium) * ticketPremium; } else { System.out.println("Sorry, you have too many tickets !!"); return 0; } } */
it does not read the values from my methods and instead reads the 1 from the declaration and initialization.
private double agePremium =1; private double ticketPremium =1;
and it multiplies them.
How do i get them to link them to each other and replace the 1 with the new values and multiply. Thanks
import java.util.Scanner; public class Driver { private int age; private int ticket; private double value; final double BASE_PREMIUM=0.05; private double agePremium =1; private double ticketPremium =1; Scanner scanner = new Scanner(System.in); public void read() { System.out.println("Driver’s Age?"); age = scanner.nextInt(); System.out.println("Number of Tickets?"); ticket = scanner.nextInt(); System.out.println("Value of Car?"); value = scanner.nextDouble(); } public double premium() { if (ticket <4){ return ((BASE_PREMIUM*value)*agePremium)*ticketPremium; } else { System.out.println("Sorry, you have too many tickets !!"); return 0; } } public void premiumAge() { if (age > 29) { agePremium += 0; } else if (age <= 29 && age >= 25) { agePremium += 0.10; } else { agePremium += 0.15; } } public void premiumTicket() { switch (ticket) { case '1': ticketPremium += 0.1; break; case '2': ticketPremium += 0.25; break; case '3': ticketPremium += 0.50; break; case '0': ticketPremium += 0.00; default: ticketPremium = 0.00; break; } } }
-24029988 0 Passing Cookies from Java to Browser I've been trying to pass cookies from an HttpsURLConnection to my browser. Unfortunately, I haven't found... Well, anything at all on the topic besides Android, which is not what I want. The cookies are session-specific, so I have to download them from the webpage every time. Is there any way to open a webpage from Java in a browser (Firefox, Chrome, etc) and send cookies over?
Code so far: (Yes, I know putting "throws Exception" on the main method is not smart in any way. Please just ignore it, it won't be there when this is working.)
public static void main(String[] args) throws Exception { String httpsURL = "https://www.link.com"; URL myurl = new URL(httpsURL); HttpsURLConnection con; CookieManager cManager = new CookieManager(); CookieHandler.setDefault(cManager); /* Start by connecting to website so CookieManager can grab cookies */ con = (HttpsURLConnection) myurl.openConnection(); /*COOKIES*/ CookieStore cookieJar = cManager.getCookieStore(); List<HttpCookie> cookies = cookieJar.getCookies(); System.out.println("COOKIES:"); String list = null; for (HttpCookie cookie : cookies) { if (list != null) { list += "; "; } list += cookie.getName()+"="+cookie.getValue(); System.out.println(cookie.getName() + " : " + cookie.getValue()); } con.disconnect(); // Here is where I want the cookies to transfer to the browser... }
-28406405 0 You need to add <tr>
in while loop like,
<?php $result = mysql_query("SELECT * FROM A"); while($row=mysql_fetch_array($result)){ ?> <tr> <!-- add this tr --> <td><?php echo $row["source_id"]; ?></td> <td><?php echo $row["escl_status"]; ?></td> <td><?php echo $row["escl_notice"]; ?></td> </tr> <?php } ?>
Also change .odd
to :odd
in your jquery selector,
$("#report tr:odd").click(function(){ // :odd not .odd $(this).next("tr").toggle(); $(this).find(".arrow").toggleClass("up"); });
-34355141 0 This works:
panel.invalidate(); //call the method u desire panel.revalidate();
-12446412 0 Check out DTGridView - it may be what you are looking for.
-21875094 0I would recommend to either always escape and wrap attribute values in double quotes or use singe codes for the string delimter and inline double quotes.
At one point you write:
"<textarea name="+"mp3link"+"
Which actually becomes <textarea name=mp3link
and then you escape the double quotes: id=\"mp33\"
which becomes id="mp33"
. Its easier to just write ('<textarea att="value"')
.
Second, why dont you just create the audio and set the src via method?
snd1 = new Audio(); snd1.src = $(mp33).val(); snd1.play();
Does $(mp33)
even exist?
Edit: I just saw you are using the textarea to get the value, but rather use the .text() method:
snd1 = new Audio(); snd1.src = $('#mp33').text(); snd1.play();
-6230939 0 Putting aside the argument of whether dates should be stored in UTC or not, the place to check for these kinds of things in your code is in the build process, or failing that, using a pre-commit hook.
The latter will only allow the developer to commit code that adheres to your standards. Doing it at the database layer is too late, IMO.
-1166114 0 Checkbox user selection validation questionI have a checkbox, the business rule is it has to be selected by user manually (so that he is aware what he is doing, not check automatically by the program).
If the user didn't check it, we need to show an error msg. How should apply the validation by ASP.NET? RequiredFieldValidator or something?
Thanks,
-31120987 0 Go: "tail -f"-like generatorI had this convenient function in Python:
def follow(path): with open(self.path) as lines: lines.seek(0, 2) # seek to EOF while True: line = lines.readline() if not line: time.sleep(0.1) continue yield line
It does something similar to UNIX tail -f
: you get last lines of a file as they come. It's convenient because you can get the generator without blocking and pass it to another function.
Then I had to do the same thing in Go. I'm new to this language, so I'm not sure whether what I did is idiomatic/correct enough for Go.
Here is the code:
func Follow(fileName string) chan string { out_chan := make(chan string) file, err := os.Open(fileName) if err != nil { log.Fatal(err) } file.Seek(0, os.SEEK_END) bf := bufio.NewReader(file) go func() { for { line, _, _ := bf.ReadLine() if len(line) == 0 { time.Sleep(10 * time.Millisecond) } else { out_chan <- string(line) } } defer file.Close() close(out_chan) }() return out_chan }
Is there any cleaner way to do this in Go? I have a feeling that using an asynchronous call for such a thing is an overkill, and it really bothers me.
-36100203 0 Error in Internet Explorer 11 for website automation using vb6I am automating the website ("http://incometaxindiaefiling.gov.in/e-Filing/UserLogin/LoginHome.html") filling using vb6. The code which works in IE10 & below,
Dim WithEvents Web As SHDocVw.InternetExplorer Private Sub Form_Load() Set Web = New SHDocVw.InternetExplorer Web.Visible = True Web.Navigate "http://incometaxindiaefiling.gov.in/e-Filing/UserLogin/LoginHome.html" End Sub Private Sub Web_DocumentComplete(ByVal pDisp As Object, URL As Variant) On Error GoTo aaa msgbox " URL: " & URL if url = "http://incometaxindiaefiling.gov.in/e-Filing/UserLogin/LoginHome.html" then Web.Document.getElementById("Login_userName").Value = "abcde1111h" Web.Document.getElementById("Login_userName").onchange Web.Document.getElementById("Login_password").Value = "123456789" Web.Document.getElementById("dateField").Value = "15/09/1954" end if Exit Sub aaa: MsgBox Err.Description & " URL: " & URL End Sub Private Sub Web_OnQuit() MsgBox "OnQuit fired" End Sub
In IE11 (Windows 10) I am facing the following problem with my code,
when navigated to above URL using SHDocVw.InternetExplorer control
First DocumentComplete event will be fired with URL being empty. Then OnQuit event is fired. Then again DocumentComplete event is fired with URL 'about:blank'
When I run the exe with ‘Run as admin’ option then it works in IE11 without any errors.
Please help.
-33017588 0Just an example how to use dynamic mysql variable inside the query:
http://sqlfiddle.com/#!9/9eecb7d/24641
SELECT case when 1 then @var := 'one' else @var := 'two' end field1, case when @var ='one' then 'two' else 'three' end field2
UPDATE In your case it would be something like
CASE WHEN DD.STATUS_CODE ='Denied' THEN CASE WHEN CHK.MAXTRAILDATE BETWEEN '2015-05-22 00:00:00.0000000' AND '2015-05-31 00:00:00.0000000' THEN @var := '201506' ELSE @var := (CONVERT(CHAR(4),CHK.MAXTRAILDATE, 120) +''+SUBSTRING(CONVERT(nvarchar(6),CHK.MAXTRAILDATE, 112),5,2)) END ELSE CASE WHEN DD.APPROVAL_DATE BETWEEN '2015-05-22 00:00:00.0000000' AND '2015-05-31 00:00:00.0000000' THEN @var := '201506' ELSE @var := (CONVERT(CHAR(4),DD.APPROVAL_DATE, 120) +''+SUBSTRING(CONVERT(nvarchar(6),DD.APPROVAL_DATE, 112),5,2)) END END AS APPROVAL_PERIOD, CASE WHEN @var between '2004-10-01 00:00:00.000' and '2005-09-30 23:59:00.000' THEN 'FY05' WHEN @var between '2005-10-01 00:00:00.000' and '2006-09-30 23:59:00.000' THEN 'FY06' WHEN @var between '2006-10-01 00:00:00.000' and '2007-09-30 23:59:00.000' THEN 'FY07' WHEN @var between '2007-10-01 00:00:00.000' and '2008-09-28 23:59:00.000' THEN 'FY08' WHEN @var between '2008-09-29 00:00:00.000' and '2009-09-30 23:59:00.000' THEN 'FY09' WHEN @var between '2009-10-01 00:00:00.000' and '2010-09-30 23:59:59.000' THEN 'FY10' WHEN @var between '2010-10-01 00:00:00.000' and '2011-09-30 23:59:59.000' THEN 'FY11' WHEN @var between '2011-10-01 00:00:00.000' and '2012-09-30 23:59:59.000' THEN 'FY12' WHEN @var between '2012-10-01 00:00:00.000' and '2013-09-30 23:59:59.000' THEN 'FY13' WHEN @var between '2013-10-01 00:00:00.000' and '2014-09-30 23:59:59.000' THEN 'FY14' WHEN @var between '2014-10-01 00:00:00.000' and '2015-09-30 23:59:59.000' THEN 'FY15' WHEN @var between '2015-10-01 00:00:00.000' and '2016-09-30 23:59:59.000' THEN 'FY16' WHEN @var between '2016-10-01 00:00:00.000' and '2017-09-30 23:59:59.000' THEN 'FY17' WHEN @var between '2017-10-01 00:00:00.000' and '2018-09-30 23:59:59.000' THEN 'FY18' WHEN @var between '2018-10-01 00:00:00.000' and '2019-09-30 23:59:59.000' THEN 'FY19' WHEN @var between '2019-10-01 00:00:00.000' and '2020-09-30 23:59:59.000' THEN 'FY20' WHEN @var between '2020-10-01 00:00:00.000' and '2021-09-30 23:59:59.000' THEN 'FY21' WHEN @var between '2021-10-01 00:00:00.000' and '2022-09-30 23:59:59.000' THEN 'FY22' ELSE ' ' END AS FY FROM table
You are very welcome if any questions
-10449952 0Updated after rereading the question.
You are mixing GROUP BY
and DISTINCT ON
. What you want (how I understand it) can be done with a window function combined with a DISTINCT ON
:
SELECT DISTINCT ON (a) a, b, c , count(d) OVER (PARTITION BY a, b, c) AS d_ct , e FROM tbl ORDER BY a, d_ct DESC;
Window functions require PostgreSQL 8.4 ore later.
What happens here?
d_ct
how many identical sets of (a,b,c)
there are in the table with non-null values for d
. a
. If you don't ORDER BY
more than just a
, a random row will be picked.ORDER BY
d_ct DESC
in addition, so a pseudo-random row out of the set with the highest d_ct
will be picked.Another, slightly different interpretation of what you might need, with GROUP BY
:
SELECT DISTINCT ON (a) a, b, c , count(d) AS d_ct , min(e) AS min_e -- aggregate e in some way FROM t GROUP BY a, b, c ORDER BY a, d_ct DESC;
GROUP BY
is applied before DISTINCT ON
, so the result is very similar to the one above, only the value for e
/ min_e
is different.
I've created a possibility by using the informations from Glix @Glix I use the EEPlus Lib to create multiple Worksheets.
For exmaple in a way like this:
private MemoryStream createMemoryStream(DataTable[] tables, int[] divs) { MemoryStream ms = new MemoryStream(); ExcelPackage pck = new ExcelPackage(); for (int i = 0; i < tables.Length; i++) { ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Division_" + divs[i].ToString()); ws.Cells["A1"].LoadFromDataTable(tables[i], true); } pck.SaveAs(ms); return ms; }
The MemoryStream could be used for a Response.BinaryWrite. In this way you could download the Excel File with different Tabs/Worksheets.
-459672 0I'm not sure if this is even possible with standard NHibernate. You're best asking this on the NHibernate users mailing list, you're more likely to get a helpful answer there.
-587003 0http://www.kronenberg.org/ies4osx/
-38090493 0Try:
#+CALL: foo()
Also, check the value of the variable org-babel-library-of-babel
to make sure that the C-c C-v i worked properly.
I am using Both types in my database. And Found information regarding these two types as i given following : 1. InnoDB locks the particular row in the table, and MyISAM locks the entire MySQL table. 2. MyISAM is the original storage engine. It is a fast storage engine. It does not support transactions. 3. InnoDB is the most widely used storage engine with transaction support. It is an ACID compliant storage engine.
So, I am confused on which table store as MyISAM type and which table store as InnoDB type in My database. Please provide suggestion to me.
-27338161 0 Javascript Timestamp to php - mysql timestamp typeI send javascript timestamp data to php to add into mysql where I have type TIMESTAMP:
DATABASE - startTime type:
Now I try to send with ajax, timestamp from javascript var startTime = Date.now();
to php where I need to tranform into TIMESTAMP type for mysql... so I try:
$datum = $app->request->post('startTime'); $startTime = $datum->format('Y-m-d H:i:s'); //FIRST ATTEMP $startTime = date("Y-m-d H:i:s", $datum); //SECOND TRY
Above I write two cases I try but both dont work... How I can transform it to correct format to add it to database...
Probbaly you will ask why that when you have this in PHP, why get it with JS? Becouse my app will use people in Autralia (and all ov r the world) and server is in EUROPE, so if I use php server time then I will make wrong date
-24784673 0The NetworkInformation.GetInternetConnectionProfile()
on Windows Phone 8 is a newer WinRT based API but unfortunately it doesn't look like most of the methods were implemented.
At runtime, using the debugger, you'll see that nearly all of the properties throw exceptions of type NotImplementedException
. But because the methods and properties were stubbed, Visual Studio doesn't know any better and allows the code to be compiled.
I have tested the following methods in WP8 SL, WP8.1 SL, WP8.1 XAML projects with the WP8 and WP8.1 emulators, where possible, to confirm the following...
As NetworkInformation.GetInternetConnectionProfile()
either isn't implemented fully (or at all on 7.5), the MSDN documentation recommends...
DeviceNetworkInformation.IsNetworkAvailable();
Note: this can still be used in Windows Phone 8.1 Silverlight
Due to increasing convergence between Windows 8 and Windows Phone 8, nearly all of WinRT APIs are now available in Windows Phone 8.1. If you're making a Windows Phone 8.1 (SL or XAML) or a Universal all (Windows 8.1 + Windows Phone 8.1), it makes sense to use the latest API...
NetworkInformation.GetInternetConnectionProfile()
-33826801 0 Cannot find symbol R after renaming package name After renaming my project package name (with Refactor) I got this error:
Error:(7, 44) error: cannot find symbol class R
All my R
usages is invalid. I try fix it manual but it doesn't work for me. Invalidate chases/Restart
doesn't help me.
I'm an experienced C++/Java programmer working in Javascript for the first time. I'm using Chrome as the browser.
I've created several Javascript classes with fields and methods. When I read an object's field that doesn't exist (due to a typo on my part), the Javascript runtime doesn't throw an error or exception. Apparently such read fields are 'undefined'. For example:
var foo = new Foo(); foo.bar = 1; var baz = foo.Bar; // baz is now undefined
I know that I can check for equality against 'undefined' as mentioned in "Detecting an undefined object property in JavaScript", but that seems tedious since I read from object fields often in my code.
Is there any way to force an error or exception to be thrown when I read an undefined property?
And why is an exception thrown when I read an undefined variable (as opposed to undefined object property)?
-21760294 1 How do I report results back to the main process from multiple processes?I currently have 18 functions that perform different sets of validations on large XML files. I've created a custom ValidationWarning
class that extends UserWarning
, and these functions raise warnings for each validation failure. In the end, I need to produce an XLSX report containing all of the failures (identifying information for each failure is available in the ValidationWarning
object).
I'm planning to spawn a process for each function (I saw examples where tasks were placed in a JoinableQueue
, but I don't understand why this is necessary, unless the task list will be modified later). The order of the validation failures is irrelevant, and I don't need to see the results until all of the validations have finished. Should I replace the showwarning()
function for each validation function to write to a list
returned by Manager()
? I can export the results to XLSX after joining all of the processes. Is this better than writing to a Queue
? Queue
may be faster, but writing results isn't a bottleneck, and I don't understand how I'd solve the following problem (see http://docs.python.org/2/library/multiprocessing.html#programming-guidelines):
This means that whenever you use a queue you need to make sure that all items which have been put on the queue will eventually be removed before the process is joined. Otherwise you cannot be sure that processes which have put items on the queue will terminate.
Is there a better approach that I'm ignoring? To my understanding, I can't use a catch_warnings
context manager in the main process and expect it to catch warnings from each validation process, although I haven't tested it yet (edit: I tested it, and, as expected, it fails). Writing to XLSX directly instead of getting all of the results first also sounds difficult, because I'd need to create a blank XLSX file and update it in each process while managing access to the shared XLSX file.
Thank you!
-9100032 1 Convert Nested List string to ListsI want to convert '[[0,0,0],[0,[0],1],2,[1,1,0]]'
to a nested list. I am aware of eval
, but understand that it's arbitrary. I would rather not use a library; but have a Python code (as I will eventually distribute code).
Instead of appending the data, generate the output with one execution of the template:
package main import ( "fmt" "os" "text/template" ) var t = template.Must(template.New("").Parse(` type Client struct { Opts *ClientOpts Schemas *Schemas Types map[string]Schema {{range .}} Container *{{.schema.Id}}Client{{end}} } `)) type schema struct { Id string } func main() { data := []map[string]interface{}{ {"schema": schema{Id: "abcClient"}}, {"schema": schema{Id: "xyzClient"}}, } if err := t.Execute(os.Stdout, data); err != nil { fmt.Println(err) } }
-9224664 0 As suggested in Matthieu M.'s comment, it is the linker job to find the right "function" at the right place. Compilation steps are, roughly:
Why can't htmlspecialchars() continually encode characters after each form submission? Take a look at the following example:
<?php $_POST['txt'] = htmlspecialchars($_POST['txt']); ?> <form method="post"> <input name="txt" value="<?=$_POST['txt'] ?>" /> <input type="submit" name="save" value="test" /> </form>
You can see it at running at http://verticalcms.com/htmlspecialchars.php.
Now do the following
1) Type & into the text field 2) Hit the test button once 3) When the page completes post back, hit the test button again 4) When the page completes post back, view the page source code
In the input box, the value is & amp;
I was expecting & amp; amp;
Why is it not & amp; amp; ???
-40310595 1 How to not block making initial connection with python requests?I have a server that uses requests to make queries to another server that may or may not be running. If that server is not running, I do not want to block for a long time; I can just handle the error right away. However, the timeout parameter does not seem to apply to the process of making the initial connection.
From the terminal, I run:
>>> import time >>> import requests >>> t1 = time.time() ; exec("try: requests.get('http://192.168.99.100/', timeout=1.0)\nexcept: pass") ; t2 = time.time() ; t2 - t1 21.00611114501953
This takes about 21 seconds and has no dependance on the timeout I give. I also tried using eventlet's timeout, but it turned out the same:
>>> import time >>> import eventlet >>> requests = eventlet.import_patched('requests') >>> t1 = time.time() ; exec("try: \n with eventlet.Timeout(1): requests.get('http://192.168.99.100/')\nexcept: pass") ; t2 = time.time() ; t2 - t1 21.00276017189026
The error I am getting for the connection is:
ConnectionError: ('Connection aborted.', error(11, 'Resource temporarily unavailable'))
Finally, I am running python under the Windows Subsystem for Linux, which might be working with sockets differently.
-31736555 0Seems to partially work. Writing files seems to be fine but it seems to be failing on any runcmd. I think if you can get away w/ it do this:
In the VM metadata create a key called user-data with your entire cloud config script in it as text. That will be picked up by the VM as it comes up.
Then in startup-script paste all your commands you'd put in runcmd.
All this may have ordering issues for you of course, but I don't any other way to do it.
-15822322 0It's actually not so hard to get this to work. It's a bit hacky since you are adding code to the engine's routes.rb file that changes depending on which env it's running in. If you are using the spec/dummy site approach for testing the engine then use the following code snippet in /config/routes.rb file:
# <your_engine>/config/routes.rb if Rails.env.test? && Rails.application.class.name.to_s == 'Dummy::Application' application = Rails.application else application = YourEngine::Engine end application.routes.draw do ... end
What this is basically doing is switching out your engine for the dummy app and writing the routes to it when in test mode.
-28904878 0This isn't something you should normally be doing just to save a little typing, but here's one way you can do it:
# define some constants PI = 3.1415927 ANSWER = 42 UNLUCKY = 13 # put them into __main__ module (your interactive session) if __name__ != "__main__": import sys as _sys _sys.modules["__main__"].__dict__.update( dict((k, v) for (k, v) in globals().iteritems() if not k.startswith("_")))
-36041131 0 Mysql query for list of followers I am trying to figure out how I can obtain the list of user followers and his/her status of following to them. For example, I have 10 followers, and I need to know if I am following them or not. It's a feature like on Instagram, when you can observe people and be observed.
I have one table:
follower user_id reg_dt followed 1 2 date true
In above mentioned example user 1 is followed by user 2. If the user will unfollow, the flag will be false, but it will be in DB.
I want to achieve:
follower user_id reg_dt followed logged_user_follower 1 2 date true false
It means that user 1 is followed by user 2, but user 1 is not following user 2.
I tried 2 queries:
select follower.follower_id as follower, follower.user_id as user_id, follower.followed as followed, follower.reg_dt as reg_dt from tb_follower follower where follower.follower_id=1 and follower.followed=1;
to get list of followers (of user 1) and:
select 1 as logged_user_follower from tb_follower follower where follower.follower_id=follower.follower_id and follower.followed=1 and follower.user_id = follower.user_id limit 1
to get the status logged_user_follower.
I don't know how to merge this to queries, to do one efficient, to get list all the followers of particular user and his/her status of following to them.
Any help will be appreciated. Thanks.
-18439226 0I believe you want your MainHash with same key in MainArray.
So, you can try,
for (String item : array_items) { entity.addPart("MainHash[MyArray][]", new StringBody(item)); }
It will create,
[one,two,three]
as an array.
-34883336 0You can cast like this:
if(a2 instanceof B) System.out.println("in testmeth->" + ((B) a2).getVar2() ); else System.out.println("in testmeth->" + a2.getVar1() );
-25618225 0 set [Serializable] prpoerty to AuditMessage.
-8542622 0Make a List<JInternalFrame>
and check isSelected()
as you iterate though it.
Addendum: See also this example that uses Action
to select an internal frame from a menu.
This is first time I am using @autowiring, I have a example.
I want to use Autowiring by TYPE , SO that at Run time container injects appropriate Object and calls appropriate bean/method.
1.INTERFACE
public interface Calculator { public int add(int a,int b); }
2.First Class
public class CalculatorImpl implements Calculator { public int add(int a, int b) { // TODO Auto-generated method stub int result=a+b; return result; }
}
3.Second Class
public class CalculatorImpl2 implements Calculator{ public int add(int a, int b) { // TODO Auto-generated method stub int result=a-b; return result; }
}
4.REST CLASS
@Component @Path("/calc") public class CalculationService { @Autowired Calculator calculator; @GET @Path("/add/{a}/{b}/") @Qualifier("calculatorImpl") @Produces("text/plain") public Response serveAdd(@PathParam("a") int a, @PathParam("b") int b) { int result= calculator.add(a, b); return Response.status(200).entity(String.valueOf(result)).build(); } @GET @Path("/sub/{a}/{b}") @Qualifier("calculatorImpl2") public Response serveSub(@PathParam("a") int a, @PathParam("b") int b) { int result= calculator.add(a, b); return Response.status(200).entity(String.valueOf(result)).build(); } }
5.APPLICATION-CONTEXT.xml
<context:component-scan base-package="com.veke.rest" /> <bean id="calculatorImpl" class="com.veke.calcImpl.CalculatorImpl" autowire="byType"/> <bean id="calculatorImpl2" class="com.veke.calcImpl.CalculatorImpl2" autowire="byType"/> </beans>
ERROR:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'calculationService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.veke.calc.Calculator com.veke.rest.CalculationService.calculator; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.veke.calc.Calculator] is defined: expected single matching bean but found 2: [calculatorImpl, calculatorImpl2]
Have I done correct things? Or I am wrong.
I have done this with my understanding of @autowiring.
Many Thanks :)
Edit: @Qualifier
is solution for this problem.(As i Have two beans with same type in context). Its used to solve ambiguity problem. @Autowired
is by Type.
Doing what Francisco Presencia said with a div wrapping the text works..
new css:
#notestext { width: 500px; height: 200px; overflow-y:scroll; } #notesdisplay { position: relative; background: #E8E8E8 ; border: 3px solid #000000; display: box; max-width: 500px; max-height: 200px; padding: 25px; } #notesdisplay:after, #notesdisplay:before { bottom: 100%; border: solid transparent; content: " "; height: 0; width: 0; position: absolute; pointer-events: none; } #notesdisplay:after { border-color: rgba(255, 255, 255, 0); border-bottom-color: #E8E8E8; border-width: 10px; left: 50%; margin-left: -10px; } #notesdisplay:before { border-color: rgba(21, 83, 132, 0); border-bottom-color: #000000; border-width: 14px; left: 50%; margin-left: -14px; }
new html:
<div id="notesdisplay"><div id="notestext">TEXT</div></div>
-19976655 0 I am currently using C++ builder 6 XE4 for developing finance charts. Exception when moving to a location on the chart canvas While using a C++ builder 6 XE4 for creating a finance charts, i was trying to create, draw line feature. The Series that i had created was candle Stick Series. I tried to move to the XY co-ordinate as pointed out by the mouse pointer but whenever the below piece of code was hit, it threw an exception.
Chart1->Canvas->MoveTo(10,20); --> have given some valid values.
Is it possible to draw a line or any figures on the Chart (not on the form)? If yes, could you please let me know, how should it be done.
Thanks.
-10794153 0The problem is not with the fileuploading part, rather looks like in the initialization part. If your file upload control is dynamically created make sure you initialize the uploader after binding that in your markup.
-38588804 1 Python - What's the proper way to unittest methods in a different class?I've written a module called Consumer.py, containing a class (Consumer). This class is initialized using a configuration file thay contains different parameters it uses for computation and the name of a loq que used for logging.
I want to write unit tests for this class so i've made a script called test_Consumer.py with a class called TestConsumerMethods(unittest.TestCase).
Now, what i've done is create a new object of the Consumer class called cons, and then i use that to call on the class methods for testing. For example, Consumer has a simple method that checks if a file exists in a given directory. The test i've made looks like this
import Consumer from Consumer import Consumer cons = Consumer('mockconfig.config', 'logque1') class TestConsumerMethods(unittest.TestCase): def test_fileExists(self): self.assertEqual(cons.file_exists('./dir/', 'thisDoesntExist.config), False) self. assertEqual(cons.file_exists('./dir/', thisDoesExist.config), True)
Is this the correct way to test my class? I mean, ideally i'd like to just use the class methods without having to instantiate the class because to "isolate" the code, right?
-5660878 0This code should loop through all POST and insert them into a hidden input field. Put it inside the <form>
tags, and it should be submitted with the subsequent post.
Remember to properly escape the output.
foreach($_POST as $name => $value){ echo '<input type="hidden" name="'.$name.'" value="'.$value.'" />'; }
Or you can save away the data in the manner you choose.
-28280287 0 Image data not sending properly - Ajax, CordovaThe following code is to take picture and send to server using ajax, but the image data not properly send.
<script> var pictureSource; // picture source var destinationType; // sets the format of returned value var image = ""; document.addEventListener("deviceready", onDeviceReady, false); function onDeviceReady() { function alertDismissed() { }; pictureSource = navigator.camera.PictureSourceType; destinationType = navigator.camera.DestinationType; } function capturePhoto() { navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50, destinationType: destinationType.DATA_URL }); } function onPhotoDataSuccess(imageData) { var smallImage = document.getElementById('smallImage'); smallImage.style.display = 'block'; smallImage.src = "data:image/jpeg;base64," + imageData; image = "data:image/jpeg;base64," + imageData; alert("Image = "+image); } function onFail(message) { alert('Failed because: ' + message); } function submitFunction() { function alertDismissed() { }; var dataString = 'image='+image; $.ajax({ type: "POST", url: "url.php", data: dataString, cache: false, success: function(result){ } }); } </script> <input type="button" id="camera" class="btn btn-primary btn-large btn-block" value="Take Photo" onclick="capturePhoto();"/> <input type="submit" class="btn btn-primary btn-large btn-block" value="Next" onclick="submitFunction();" /> <img style="display:none;width:60px;height:60px;" id="smallImage" src="" />
The image is displaying properly, and alert shows "Image = data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDABALDA4M......o7cUAPFJR9KWmgP/9k=".
But, in the following php, the $_POST['image'] is not receiving the proper data, it missing somecharacters like '+' and also replacing it with space or new line. So, when I returning back from db in other page, image not displayed properly.
url.php
$con=mysql_connect('server','user','password') or die("Failed to connect to MySQL: " . mysql_error()); $db=mysql_select_db('db',$con) or die("Failed to connect to MySQL: " . mysql_error()); $retval = mysql_query( "UPDATE tablename SET photo='".$_POST['image']."' WHERE ID='".$_POST['id']."'", $con ); echo $_POST['image'];
-3309473 0 Spring-Hibernate used in a webapp,what are strategies for Thread safe session management I'm developing a web app with Spring and Hibernate and I was so obsessed by making he application thread safe and being able to support heavy load that based on my boss recommendation I end up writing my own session
and a session container
to implement a session per request pattern
. Plus I have a lot of DAOs
and me not willing to write the same save method
for all the DAOs
I copy paste this Hibernate GenericDAO
(I can't tell it's the same thing because at the time hibernate wasn't owned by jboss) and do the plumbing stuff, and under pressure, all become quickly complicated and on production, the is StaleObjectException and duplicated data right, and i have the feeling that it's time to review what I've done, simplify it and make it more robust for large data handling. One thing you should know is that one request involves many DAO's.
There is quartz running for some updates in the database.
As much as I want to tune everything for the better I lack time to do the necessary research plus Hibernate is kind of huge (learning).
So this is it, I'll like to borrow your experience and ask for few question to know what direction to take.
Question 1 : is Hibernate generated uuid safe enough for threading environment and avoiding StaleObjectException?
Question 2 what are best strategy to use hibernate getCurrentSession in threadSafe scenario (I've read about threadlocal stuff but didn't get too much understanding so didn't do it)
Question 3 : will HIbernateTemplate do for the simplest solution approach?
Question 4 : what will be your choice if you were to implement a connection pool and tuning requirement for production server?
Please do no hesitate to point me to blogs or resources online , all that I need is a approach that works for my scenario. your approach if you were to do this.
Thanks for reading this, everybody's idea is welcomed...
-26950401 0 Swift search string for any number?I'm trying to get my app to identify dates. I have an array of strings that it searches through. I'm using rangeOfString() to search for a "/", which is in the dates. However, some areas in the strings have backslashes that aren't part of dates, and that messes up the search. Can I get it to search for a backslash immediately followed by a number. In PHP, it would be preg_match("///[0-9]/"), but how is it done with Swift?
-38315194 0Another way to customize is as following:
columns: [ { command: [{ name: 'edit', click: editButtonClick, template: editButtonTemplate }], title: 'Edit', width: '40px'}..] var editButtonTemplate = '<a class="btn btn-link btn-xs k-grid-edit" href="\\#"><span class="glyphicon glyphicon-pencil"></span></a>'; editButtonClick = function (e) { /* Changes default rendering of 'update' & 'cancel' buttons * but keeps default behaviour */ var btnCancel = $('.k-grid-cancel'); btnCancel.removeClass('k-button k-button-icontext').addClass('btn btn-link btn-xs'); btnCancel.text(''); btnCancel.append('<span class="glyphicon glyphicon-ban-circle"></span>'); var btnOk = $('.k-grid-update'); btnOk.removeClass('k-button k-button-icontext k-primary').addClass('btn btn-link btn-xs'); btnOk.text(''); btnOk.append('<span class="glyphicon glyphicon-ok-circle k-update"></span>');
}
This approach handles click
event of standard edit
command and modifies rendered html, but preserves standard functionality.
Important detail - grid's update functionality is coupled to element with k-update
attribute, while cancel functionality rides on k-grid-cancel
.
I write a WindowsForms-GUI for a touchscreen and used the auto-logout Code from How can I trigger an auto-logout within a Windows Forms Application? but i'm wondering if a tochscreen can trigger a MouseMoveEvent(Dont have a touchscreen to test). I figuered out that for WPF there are extra Touchevents, does anyone knows how it works with Forms Applications??
-37851143 0 24/August/2016 12:44 AM Not valid in Safari on MacI have done quite a bit to make sure the date my date picker creates is compatible for being converted into a javascript Date object. I followed the advice on this stack overflow entry: Invalid date in safari and removed dashes from the string using: new Date('24-August-2016 12:44 AM'.replace(/-/g, "/")); That made things compatible with every other operating system and browser, except browsers on a Mac. It still seems safari does not like the full month name in the string. What is the recommended approach to getting safari to recognize the string as a date if I am forced to use that format?
-337420 0XAMPP from ApacheFriends is pretty simple to set up and use.
note the site appears to be down as at 15:02 UTC on 3rd Dec 2008
note again and it is back!
json_decode the json into an object and then loop:
<?php $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, "http://www.reddit.com/r/indie/comments/zc0lz/.json"); curl_setopt($curl, CURLOPT_HEADER, 0); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); curl_setopt($curl, CURLOPT_TIMEOUT, 30); $json = curl_exec($curl); curl_close($curl); //decode the json $json_obj = json_decode($json); //loop the result set(array) and access the data->children sub array. foreach($json_obj as $v){ foreach($v->data->children as $d){ if(isset($d->data->body)){ echo $d->data->body.'<br />'.PHP_EOL; } } } /* Is anyone else bored with this? The first album was good for the moment it existed in, but the has since passed. It just seems their sound didn't mature very well.<br /> Yeah, from the songs I had heard, this album missed it. Too similar and not as exciting.<br /> half the album is just as amazing as the first. half is kind of dull<br /> Got this album today, maybe 2 decent-ish songs, but it sounds like they have tried to copy some of the sounds from the album way too closely. Real shame. 4/10<br /> If the player doesn't work, refresh the page and try again. You can also use the NPR link!<br /> Loved the sound of the first album, and I'm kind of happy they've not strayed to much away from this. Have to agree that it seems to be missing the 'awesomeness' that made the first songs so enjoyable to listen to.<br /> */ ?>
-6658019 0 If x
needs more precision than provided by double-precision floating point numbers then the comparison will fail.
>>> int(float(10**23)) 99999999999999991611392L
-8376072 0 what's the readStream() method? i just can not find it anywhere, i searched how to use resources under the directory "assets", then i find a snippet:
AssetManager assets = getAssets(); ((TextView)findViewById(R.id.txAssets)).setText(**readStream**(assets.open("data.txt")));
i just cannot find what's the readStream method, it is not in the google apis i tried to download the newest Java api document, but still can not find it, anybody knows that?
-31038177 0 Why can't we specify a variable size when declaring a static array?Through dynamic memory allocation, the following the code works perfectly.
int *ptr; int size1; cin >> size1; ptr = new int[size1];
In static memory allocation, I get the following error: array bound is not an integer constant before ']' token
int size2; cin >> size2; int arr[size2];
Why is this so? Why can't we specify a variable size?
-26865007 0 How can I open data:image in browser from node-webkit app?I am using Node-Webkit for making an image enhancement app. I have a download button clicking on which executes the following.
document.getElementById("download").onclick = function(){ var c = Caman("canvas"); if(file.type.replace("image/","")=="jpeg"){ //save as jpeg c.save('jpeg'); } else { //saves as png by default c.save(); } } }
This function is supposed to download the image if run in browser, but the download doesn't work in the Node-Webkit app.
So, I want to make it function to open the data:image in default browser so that I can save image from the browser, but I have no idea how to do that. Can anyone help me with this?
Thanks.
-26641535 0There's a lot of discussion on whether REST URIs should have verbs or not, but that's merely a fetish. When it comes to URIs, what determines if your API is more or less RESTful isn't their design, but how your client obtains them. If you can't change your URIs anytime you want, it's not RESTful. If your clients are reading URI patterns from documentation and replacing fields like :id
with values to build the final URIs to be used, that's not RESTful, it doesn't matter what the content of the URI is. Do some research on HATEOAS for more information on that.
With that part out of the way, POST is the method used for any action that isn't standardized by HTTP, which means you can usually do almost anything you want and still say it's RESTful, as long as it's clearly documented and the URI isn't from out-of-band information. You can guess what a GET, PUT, PATCH or DELETE does based on the HTTP standard, but you can't guess what a POST does.
Just be careful that you don't make your POSTs like an RPC method. For instance, don't do something where the resource the POST is applied to is identified by the payload instead of the URI. In your case, something like:
POST /explore {"region_id": :id}
This is what's really meant by the mantra to avoid verbs or method names in the URI.
-18266548 0Here I think a user-defined conversion operator
would be more appropriate.
class rational { public: rational( int iNum, int iDen ) : num( iNum ), den( iDen ) {} // ... operator double() { return (double)num / (double)den; } private: int num; int den; }; int main() { rational r( 1, 2 ); double n = r; std::cout << r << std::endl; // output 0.5 return 0; }
Here is a little live example to illustrate this : http://ideone.com/I0Oj66
About the copy assignment operator=
:
A copy assignment operator of class
T
is a non-template non-static member function with the nameoperator=
that takes exactly one parameter of typeT
.
The operator=
is used to change an existing object.
You can use it for example to copy the state of another object :
rational &operator=( const rational &rhs ) { num = rhs.num; den = rhs.den; return *this; }
-14742738 0 You need to make your anchor to something like
<a href="2nd.html#anchor_temp">Go</a>
Because you can't prevent the default scrolling behavior of the browser
When the document is ready you need to see the hash tag value from URL then remove the _temp and then animate to it
$(document).ready(function(e){ var str= location.hash; var n=str.replace("_temp",""); $('html,body').animate({scrollTop:$(n).offset().top}, 500); });
I hope this will help :)
-12799773 0You can use animate to do the job:
$('html,body').animate( {scrollTop: $('#your-content-id').offset().top}, 'slow' );
-13407239 0 Targeting all images in a group in Actionscript with Flex Builder So I basically have this code:
<s:Group> <sImage source="assets/image1.gif"/> <sImage source="assets/image2.gif"/> <sImage source="assets/image3.gif"/> <sImage source="assets/image4.gif"/> </s:Group>
Now I need to target each of them in actionscript to do a colorTransform on, how would I do this?
-15727339 0 Change Text Object Value of Crystal Report Dynamically in VB.netI have this picture of my current format of crystal report.
My problem is, I want to set the value of fullName
field dynamically depending on the query result of my vb.net form. For example, I have this code from my vb form,
sql = "SELECT fullName FROM tblClient WHERE clientID = '" & ST-TAC-23 & "'" da = new SqlDataAdapter (sql, con) dt = new DataTable da.fill(dt)
I want the dt
value to be passed on fullName
object in my crystal report. For example the dt
value is Mark Zucker, I want the fullName
field in my cr to display Mark Zucker also. How could possibly do that?
I think Maximo will work with the java.sql package, which can be used like so:
import java.sql.* String connectionString = "Your JDBC connection string here"; Connection conn = java.sql.DriverManager.getConnection(connectionString); String sQuery = "SELECT SAMPLE_COLUMN FROM SAMPLE_TABLE"; Statement stmt= conn.createStatement(); ResultSet result = stmt.executeQuery(sQuery);
Read here how to parse through a ResultSet to get the information you want: http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html
-26631244 0You might be missing
<context:component-scan base-package="org.example">
in your applicationContext.xml file OR
@ComponentScan("com.example")
annotation if you are doing code based configuration.
-12358861 0CATransaction works on Core Animation layer animations. CATransaction is cross-platform between iOS and Mac OS.
NSAnimationContext works with an NSAnimationContext. It's Mac OS specific.
(The NS animation stuff is Mac-only, and the UIView animation stuff is iOS only.)
I work in iOS more than Mac OS these days, and I always look for cross-platform ways to do things.
CAAnimation, CALayer, CAAnimationGroup, etc, are nearly identical between Mac and iOS. There are some differences (e.g. quicktime layers are not supported in iOS, Core Image support is more limited in iOS, etc.) but CA stuff is more alike than different.
-17651165 0On this line:
scrollLeft: $(anchor.attr('href')).offset().left
You mispelled your variable $anchor
. Change it to:
scrollLeft: $($anchor.attr('href')).offset().left
Either way I recommend you to learn how to use the dev-tools of your browser and especially how to use break points so you can check yourself what variable doesn't behave as you would expect.
-1851592 0There are a few java applet ssh clients you could set up an a machine. I've used mindterm, but it's abandoned.
If the Internet cafe has Windows machines where you can install software, then you're all set. (not uncommon; I was usually able to install putty so I could check my email in Austria, Germany, and Italy on a 3-week trip in 2005.) WinSCP lets you run a text editor on remote files, which would otherwise be painful over a high-latency connection. Most version control systems have command line interfaces, so that should cover most of it.
I'm an old-school command line junkie, so I'm fine with ssh... Your needs may vary.
Just make sure your remote machine has a good UPS and will boot up ok after a power cycle. You'll be too far away to nudge it along if you haven't tested rebooting since last time you changed any config files.
-28197438 0I'm researching this subject intensively since Aug-2014. Firstly, I hope that you're familiar with some telecom knowledge and Android Open Source Project (AOSP). Well, based on my researches, I state that:
Based on the above, I suppose that:
I hope that it brings some light to you. If you have any additional information, please share it here.
-17003586 0 Simulate tap in iOS webview with buttonI am trying to build an app for people with disabilities who are unable to use gestures such as swipe and pinch. I realise there is no way to simulate taps inside iOS however is it possible to somehow send a a tap event to a webview so they could control the internet.
Perhaps this can be done with Javascript?
I have looked on this subject for some time but cannot find any answers.
Any help greatly appreciated
-35658677 0To get the value of the "first" key, you can use it
map.get(map.keySet().toArray()[0]);
-33055940 0 Swift with objective-git: Overloads for 'createCommitWithTree' exist with these partially matching parameter lists I am using objective-git with Swift and cannot compile the GTRepository.createCommitWithTree method.
The method can optionally be called without author : GTSignature and committer : GTSignature parameters.
I'm new to Swift and overloading functions. I'd like to know how to structure this so it will compile.
My code uses all the types specified in the objective-git method:
func commitTree ( tree : GTTree ) { let message : NSString let author : GTSignature let committer : GTSignature let parents : NSArray let updatingReferenceNamed : NSString var error : NSError? GTRepository.createCommitWithTree( tree, message, author, committer, parents, updatingReferenceNamed, &error ) }
In this code, compiler cannot invoke method with an argument list of these types. Compiler provides additional information: "Overloads for 'createCommitWithTree' exist with these partially matching parameter lists: (GTTree, message: String, author: GTSignature, committer: GTSignature, parents: [AnyObject]?, updatingReferenceNamed: String?), (GTTree, message: String, parents: [AnyObject]?, updatingReferenceNamed: String?)"
If I refactor to use the types suggested above, compiler won't compile with "Ambiguous reference to member 'createCommitWithTree'"
How do I write this to compile?
Thanks
-18611088 0 Wordpress High CPU UsageI received an email from my hosting provider (hostgator) telling me that: "Your account has been placed under resource restriction! Your account has exceeded our extreme usage threshold for several hours..."
Logs of the CPU usage are provided below: CPU seconds used in the past hour: 3318.56999999999, 93% CPU
Tue Sep 3 21:01:10 CDT 2013 Running Processes: user 21172 60.0 0.1 340216 50288 ? RN 21:01 0:00 /usr/bin/php /home1/user/public_html/index.php
Running Queries: ************* 1. row ************* USER: user_db DB: name_db STATE: Sorting result TIME: 0 COMMAND: Query INFO: SELECT ID, post_title, meta_value FROM wp_posts, wp_postmeta WHERE wp_posts.ID = wp_postmeta.post_id AND post_status='publish' AND post_type='post' AND meta_key='_liked' ORDER BY wp_postmeta.meta_value+0 DESC LIMIT 10
Can anyone explain me what is this and how to solve?
-8577014 0There is an overhead associated with lazyness — the compiler has to create a thunk for the value to store the computation until the result is needed. If you know that you'll always need the result sooner or later, then it can make sense to force the evaluation of the result.
-14631688 0shmat() is a typical example of same physical address being mapped as two different virtual address in two different processes. If you do pmap -x pid_A . you will you see the virtual mem map for process A similarly for Process B. Actual Phy mem is not exposed to the user-space program.
Now SayProcess A and B share a shared memory segment and shared memory pointer be sh_mem_ptr_A and Sh_mem_ptr_B. If you print these pointers their address(virtual) will be different. Because Sh_mem_ptr_A is a part of memory map of Process A, Similarly sh_mem_ptr_B for Process B.
Kernel maintains the maaping of Virtual-to- phy addr. By page table and offset. Higher bits map to the page table and offset maps to offset in the page table. So If you notice the Lower order bits of sh_mem_ptr_A and sh_mem_ptr_B they will be same(but may not be true always).
-34686824 0Use django F()
expression and update()
:
from django.db.models import F Model.objects.filter(condition=condition).update(field=F('field') * 1.5))
django doc about F() and update.
PS: Your model names are not following python class conventions. The should be capfirst with no underscores in between. Check pep8 doc for python class naming details.
-13597140 0Probably too late to be useful, but I was able to connect from Python 3.3 to a MySQL db on my Windows machine (!) using PyMySql (see https://code.google.com/p/pymysql/). Once installed, I used a variation on the code from your reference location here: Python 3 and mysql. I have a schema called "test" and a table called "users", here was the test code:
import pymysql conn = pymysql.connect(host='127.0.0.1', user='root', passwd='password', db='mysql') cur = conn.cursor() cur.execute("SELECT * FROM test.users") for r in cur: print(r) cur.close() conn.close()
-22352054 0 How can I check on a Webpage if the user is from the local network? I have to build a little tool for the browser which should block all access from outsite the Network. I checked Google for answers but i didnt find anything. The Tool is made with PHP and Javascript (jquery). How can I do this?
-10953486 0Sometimes it helps to rephrase the problem: if I read you well, you don't want users, that have a deny time with at least one specified DayID/Hour/Minute:
where !i.UserDeniedTimes.Any( p => (p.AllowedDate.AllowedTimes.Any( a1 => a1.DayID == aTime.DayID && a1.Hour == aTime.Hour && a1.Minute == aTime.Minute )) )
This should select the users you want. If not, please tell in some more words what exactly you are trying to achieve.
-13065257 0You can put the email body in a properties file and read it from there.
For substitution, you can define "placeholder" in your String like {FIRSTNAME} {LASTNAME} etc., and then do a replaceAll for the dynamic portions in your code.
I found my way around it. I noticed it installs successfully globally. So I installed psycopg2 globally and created a new virtual environment with --system-site-packages
option. Then I installed my other packages using the -I
option.
Hope this helps someone else.
OK. I later found out that I had no gcc
installed. So I had to install it first. And after that, I could pip install psycopg2
. Thank you cel for the direction.
Directly on android? No I don't think so.
However it is possible to install ubuntu on a tablet. Then you could use eclipse or any other linux IDE, I suppose. Heres a video showing you how to install ubuntu on a tablet.
http://www.youtube.com/watch?v=agYEOefFfto
UPDATE
Terminal IDE allows for full java/android development on your android device (no root required). I believe C and C++ support is in the works as well. Project is open source and includes the following executable's:
javac, java, dx, proguard, aapt, apkbuilder, signer, ssh, sshd, telnetd, bash 4.2, busybox 1.19.2, vim 7.3, nano 2.2.6, midnight commander 4.8, htop 1.0, TMUX 1.5, rsync 3.0.8, git 1.7.8, BitchX 1.1.
You'll definitely need a bluetooth keyboard to get any real productivity out of it, but its a great app.
-4292443 0 .gemrc file specificationI searched everywhere to find the .gemrc
file specification but I haven't succeed.
Does anyone know where I can find it?
-30866894 0I would create a helper class that takes an input operation, starting it, and cancelling the existing one, and overwriting its internal variable. As you cant perform a Cancel()
explicitly and directly on a Task<T>
, you will need to keep your own TaskCancellationSource
handy. If you want to provide an external token, you can combine them with CancellationTokenSource.CreateLinkedTokenSource(...)
If you need to keep an eye on the result, that would make a good opportunity for TaskCompletionSource.
public class OverwriteTaskHandler<T> { private Task<T> _task; private TaskCompletionSource<T> _tcs; private CancellationTokenSource _cts; public OverwriteTaskHandler(Func<T> operation) { _tcs = new TaskCompletionSource<T>(); _cts = new CancellationTokenSource(); TryPushTask(operation); } public bool TryPushTask(Func<T> operation) { if (_tcs.Task.IsCompleted) return false; //It would be unsafe to use this instance as it is already "finished" _cts.Cancel(); _cts = new CancellationTokenSource(); _task = Task.Run(operation, _cts.Token); _task.ContinueWith(task => _tcs.SetResult(task.Result)); return true; } public void Cancel() { _cts.Cancel(); } public Task<T> WrappedTask { get { return _tcs.Task; } } }
Discalimer: I haven't tested this, so just double check!
-24002303 0You do not need globals for this. A simpler version might be something like:
Function mkArray() Const COLR_GREEN As Long = 11 Const COLR_RED As Long = 2 Dim areaArr As Variant, i As Long areaArr = ActiveSheet.Range("I1:J16").Value For i = 1 To UBound(areaArr, 1) Debug.Print areaArr(i, 1), areaArr(i, 2) Sheets("Sheet1").Shapes(areaArr(i, 1)).Fill.ForeColor.SchemeColor = _ IIf(areaArr(i, 2) > 500, COLR_GREEN, COLR_RED) Next i End Function
If you really want to split into separate subs then you should use parameters in place of globals:
E.g.
Function mkArray() Dim areaArr As Variant, i As Long areaArr = ActiveSheet.Range("I1:J16").Value For i = 1 To UBound(areaArr, 1) ColorShape Cstr(areaArr(i, 1)), areaArr(i, 2) Next i End Function Sub ColorShape(shpName as string, shpVal) Const COLR_GREEN As Long = 11 Const COLR_RED As Long = 2 Sheets("Sheet1").Shapes(shpName).Fill.ForeColor.SchemeColor = _ IIf(shpVal > 500, COLR_GREEN, COLR_RED) End Sub
-24052850 0 Its is just because of Class.forName()
is dynamically loaded at run time your class into memory(RAM). and it will execute all static block within this class without creating reference of that class,
From offical doc:
A call to Class.forName("X") causes the class named X to be dynamically loaded (at runtime). A call to forName("X") causes the class named X to be initialized (i.e., JVM executes all its static block after class loading). Class.forName("X") returns the Class object associated with the "X" class. The returned Class object is not an instance of the "x" class itself.
Class.forName("X") loads the class if it not already loaded. The JVM keeps track of all the classes that have been previously loaded. This method uses the classloader of the class that invokes it. The "X" is the fully qualified name of the desired class.
here is more information about it: http://www.xyzws.com/Javafaq/what-does-classforname-method-do/17
-35573235 1 Why some part of code is not participate in execution processI am trying to split network into two groups (g1 and g2) according to the degree of nodes (if degree of node d>=691 then node is add in g1 otherwise node is add in g2)
import networkx as nx import random import numpy as np import os import sys from networkx.algorithms.assortativity.mixing import degree_mixing_matrix # \attribute_mixing_matrix, numeric_mixing_matrix from networkx.algorithms.assortativity.pairs import node_degree_xy #, \node_attribute_xy from operator import itemgetter from networkx.exception import NetworkXError import networkx.convert as convert g = nx.read_edgelist('/home/suman/Desktop/dataset/Email-Enron.txt',create_using=None,nodetype=int,edgetype=int) s=sorted(g.degree_iter(),key= itemgetter(1),reverse=True) perc=1 def modify_nw_random(g,perc): while(perc<=100): ntm = round((float(perc)/100)*len(g)) #print ntm while(ntm != 0): v = random.randrange(1,len(g)) print"node:", v d=g.degree(v) print"degree:", d g1=nx.Graph() g2=nx.Graph() if g.has_node(v) and (d>=691): g1.add_node(v) else: g2.add_node(v) g.remove_node(v) ntm = ntm-1 if(ntm<=0):break perc=perc+1 print "perc:",perc if(perc>100):break N1=nx.number_of_nodes(g1) print N1 r2=nx.degree_assortativity_coefficient(g1) print ("%f"%r2) N2=nx.number_of_nodes(g2) print N2 r3=nx.degree_assortativity_coefficient(g2) print ("%f"%r3) modify_nw_random(g,perc)
here first loop are executed when perc = 1 and then perc is increase by 1 (perc=perc+1) this is not execute .it means following part of code is not participating in execution process
perc=perc+1 print "perc:",perc if(perc>100):break print "node in g1:", g1.nodes() print "node in g2:", g2.nodes() N1=nx.number_of_nodes(g1) print N1 r2=nx.degree_assortativity_coefficient(g1) print ("%f"%r2) N2=nx.number_of_nodes(g2) print N2 r3=nx.degree_assortativity_coefficient(g2) print ("%f"%r3)
can any one help me that, for solving my mistakes in this code
-31242924 0 jQuery hide the divs based on the classes getting from serverI have 3 div
blocks. Based on the response getting from my AJAX request, I want to show or hide the specific block. Suppose I have gotten the response in JSON format like this:
var response = [{ "class":[ "firstBlock", "secondBlock" ] }]
<div class="mianBlock"> <div class="firstBlock"> div content goes here </div> <div class="secondBlock"> div content goes here </div> <div class="thirdBlock"> div content goes here </div> </div>
Using jQuery, how do I hide the 2 blocks?
-13725983 0 use the css3 transform-origin to center and zoomI have a series of divs on my page. Each div has a background image and is arranged in a grid formation. There are an abitrary number of divs on my page. The page is constrained to a size using <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
I want to be able to click on a div, have it scale to a specific scale, and center.
My markup:
<body id="body"> <div id="container" style="position: relative"> <div id="pack1" class="screenItem cardPack"></div> <div id="pack2" class="screenItem cardPack"></div> <div id="pack3" class="screenItem cardPack"></div> <div id="pack4" class="screenItem cardPack"></div> </div> </body>
my css:
#pack1{ margin-left: 20px; margin-top: 20px; height: 193px; width: 127px; background-image: url(../images/image1.png); background-size: 100% 100%; float: left; clear: both; -webkit-transition: all 1s ease-in-out; -moz-transition: all 1s ease-in-out; -o-transition: all 1s ease-in-out; -ms-transition: all 1s ease-in-out; transition: all 1s ease-in-out; } #pack2{ margin-right: 20px; margin-top: 20px; height: 193px; width: 127px; background-image: url(../images/image2.png); background-size: 100% 100%; float: right; -webkit-transition: all 1s ease-in-out; -moz-transition: all 1s ease-in-out; -o-transition: all 1s ease-in-out; -ms-transition: all 1s ease-in-out; transition: all 1s ease-in-out; } #pack3{ margin-left: 20px; margin-top: 20px; height: 193px; width: 127px; background-image: url(../images/image3.png); background-size: 100% 100%; float: left; clear: both; -webkit-transition: all 1s ease-in-out; -moz-transition: all 1s ease-in-out; -o-transition: all 1s ease-in-out; -ms-transition: all 1s ease-in-out; transition: all 1s ease-in-out; } #pack4{ margin-right: 20px; margin-top: 20px; height: 193px; width: 127px; background-image: url(../images/comingSoon.png); background-size: 100% 100%; float: right; -webkit-transition: all 1s ease-in-out; -moz-transition: all 1s ease-in-out; -o-transition: all 1s ease-in-out; -ms-transition: all 1s ease-in-out; transition: all 1s ease-in-out; } #body, .ui-page { background-image: url(../images/bg.png); background-size: auto 100%; background-repeat: repeat-x; } #container { margin: auto; width: 310px; height: 568px; }
I have a fudge which almost works:
$(cardPack).click(function() { var left = $(cardPack).position().left; var top = $(cardPack).position().top; $(cardPack).css("-webkit-transform", "scale(2.5,2.5)"); $(cardPack).css("-webkit-transform-origin", (3*(left/4)) + " " + (3*(top/4))); });
But I think that's more of a coincidence and luck. My brain is not working to the point where I can workout where to set the transform-origin
so that the image will end up in the center of the screen, regardless of its start point.
I am happy to consider alternatives to transform-origin
to make this happen.
EDIT: A "not quite acting the same as it does locally" jsfiddle: http://jsfiddle.net/a7Cks/9/
-17241731 0Try mapping the Option[java.util.Date]
to an Option[java.sql.Date]
like this:
(success._6).map(d => new java.sql.Date(d.getTime))
One more word of advice, you might want to actually map this to a java.sql.Timestamp
so you don't lose any time precision when writing it to the DB as I believe will be the case with java.sql.Date
. So the code would be:
(success._6).map(d => new java.sql.Timestamp(d.getTime))
-2792309 0 What you're talking about is called a callback and is implemented with function pointers in C and C++.
Since you mentioned glut, let's take a real example directly from the freeglut source code. I'll use glutIdleFunc instead of glutTimerFunc because the code is simpler.
In glut, the idle function callback (what you supply to glutIdleFunc) is a pointer to a function that takes no parameters and returns nothing. A typedef is used to give such a function type a name:
typedef void (* FGCBIdle)( void );
Here, FGCBIdle (short for FreeGlut CallBack Idle) is defined as a pointer to a function that takes no parameters and whose return type is void. This is just a type definition that makes writing expression easier, it doesn't allocate any storage.
Freeglut has a structure called SFG_State that holds various settings. Part of the definition of that structure is:
struct tagSFG_State { /* stuff */ FGCBIdle IdleCallback; /* The global idle callback */ /* stuff */ };
The struct holds a variable of type FGCBIdle, which we established is another name for a specific function pointer. You can set the IdleCallback field to point to the address of a function that is supplied by the user using the glutIdleFunc function. The (simplified) definition of that function is:
void glutIdleFunc( void (* callback)( void ) ) { fgState.IdleCallback = callback; }
Here, fgState is a SFG_State variable. As you can see, the glutIdleFunc takes one parameter which is a function pointer to a function that takes no parameters and returns nothing, this parameter's name is callback. Inside the function, the IdleCallback inside the global fgState variable is set to the user supplied callback. When you call the glutIdleFunc function, you pass the name of your own function (e.g. glutIdleFunc(myIdle)), but what you're really passing is the address of the function.
Later, inside the big glut event processing loop initiated by glutMainLoop, you'll find this code:
if( fgState.IdleCallback ) { /* stuff */ fgState.IdleCallback( ); }
If a user supplied idle callback is available, it is called in the loop. If you check the function pointer tutorial at the beginning of my post you will understand the syntax better, but I hope the general concept makes more sense now.
-33883397 0I wouldn't go for a switch
at all.
There is no reason to use chaining at all here. Just do
// if (!/^(original|large|medium|small)$/.test(style.name)) throw new Error(…); var x = gm(response.Body) .setFormat('jpg') .autoOrient() .resize(style.w, style.h, style.option); if (style.name == "medium" || style.name == "small") x = x.crop(style.w, style.h, style.crop.x_offset, style.crop.y_offset) .repage('+'); if (style.name == "large" || style.name == "small") x = x.quality(style.quality); if (style.name == "large" || style.name == "medium" || style.name == "small") // possibly better than if (style.name != "original") x = x.strip() .interlace('Plane'); x.toBuffer(next);
But if you're having a large set of options so that it gets unreadable, better factor out each transformation in a function:
function resizedJpg(x) { return x.setFormat('jpg').autoOrient().resize(style.w, style.h, style.option); } function cropped(x) { return x.crop(style.w, style.h, style.crop.x_offset, style.crop.y_offset).repage('+'); } function withQuality(x) { return x.quality(style.quality); } function stripped(x) { return x.strip().interlace('Plane'); }
And then apply them separately:
({ original: [resizedJpg], large: [resizedJpg, withQuality, stripped], medium: [resizedJpg, cropped, stripped], small: [resizedJpg, cropped, withQuality, stripped] }[style.name]).reduce(function(x, trans) { return trans(x); }, gm(response.Body)).toBuffer(next);
-3307018 0 IIRC, you need to decorate the delegate signature with a calling convention. Unfortunately, this can only be done via IL or generating the stub with Reflection.Emit.
You can try this:
protected static Type MakeDelegateType(Type returntype, List<Type> paramtypes) { ModuleBuilder dynamicMod = ... ; // supply this TypeBuilder tb = dynamicMod.DefineType("delegate-maker" + Guid.NewGuid(), TypeAttributes.Public | TypeAttributes.Sealed, typeof(MulticastDelegate)); tb.DefineConstructor(MethodAttributes.RTSpecialName | MethodAttributes.SpecialName | MethodAttributes.Public | MethodAttributes.HideBySig, CallingConventions.Standard, new Type[] { typeof(object), typeof(IntPtr) }). SetImplementationFlags(MethodImplAttributes.Runtime); var inv = tb.DefineMethod("Invoke", MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.NewSlot | MethodAttributes.HideBySig, CallingConventions.Standard ,returntype,null, new Type[] { // this is the important bit typeof(System.Runtime.CompilerServices.CallConvCdecl) }, paramtypes.ToArray(), null, null); inv.SetImplementationFlags(MethodImplAttributes.Runtime); var t = tb.CreateType(); return t; }
-18176980 0 You would have to have the @interface and @implementation have the same class name. Aside from that, it does not matter what file the @interface or @implementation is in as long as the @interface is accessable from the file the @implementation is in (in the same file or #import
ed.
So in your case, if you did @interface ReceiverViewController...
you would be fine.
I was wondering if it practicable to have an C++ standard library compliant allocator
that uses a (fixed sized) buffer that lives on the stack.
Somehow, it seems this question has not been ask this way yet on SO, although it may have been implicitly answered elsewhere.
So basically, it seems, as far as my searches go, that it should be possible to create an allocator that uses a fixed size buffer. Now, on first glance, this should mean that it should also be possible to have an allocator that uses a fixed size buffer that "lives" on the stack, but it does appear, that there is no widespread such implementation around.
Let me give an example of what I mean:
{ ... char buf[512]; typedef ...hmm?... local_allocator; // should use buf typedef std::basic_string<char, std::char_traits<char>, local_allocator> lstring; lstring str; // string object of max. 512 char }
How would this be implementable?
The answer to this other question (thanks to R. Martinho Fernandes) links to a stack based allocator from the chromium sources: http://src.chromium.org/viewvc/chrome/trunk/src/base/stack_container.h
However, this class seems extremely peculiar, especially since this StackAllocator
does not have a default ctor -- and there I was thinking that every allocator class needs a default ctor.
You have to execute the stored procedure as a data set:
var stuffProcedure = db.UspSelectStuff(0, 1).GetDataSet();
-31776485 0 bootstrap dropdown button is not working inside of the collapsed navbar I'm building a website that has a dropdown button with two categories. The dropdown works perfectly on a desktop but when the navbar is collapsed on a small screen, it doesnt work. I've looked for an answer here on stack overflow but nothing has my exact same problem. I need the dropdown to show the two links when I touch the dropdown button. This is a bootstrap website that uses a scroll spy to navigate to different sections of a single index.html page. Jquery is embedded properly as well as bootstrap.min.css, bootstrap.js, and bootstrap.css. And also the navbar is fixed to the top of the page. The navbar collapses perfectly on a small screen but its the dropdown that is not working when the navbar is collapsed. To clarify I should say that it is not the navbar toggle button that I am referring to, only the dropdown button inside of the navbar. It will not open to reveal the links when the navbar is collapsed. When i click the caret, the navbar closes.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"></script> </head> <body id="home" data-spy="scroll" data-target=".navbar-collapse"> <nav class="navbar navbar-default navbar-fixed-top"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar" aria-expanded="true" aria-controls="navbar"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a href="#home" class="navbar-brand smoothScroll"><strong>Third Base</strong></a> </div> <div> <div class="collapse navbar-collapse" id="myNavbar"> <ul class="nav navbar-nav"> <li><a href="#home" class="smoothScroll">HOME</a></li> <li><a href="#about" class="smoothScroll">ABOUT</a></li> <li><a href="#contact" class="smoothScroll">CONTACT</a></li> <li><a href="#gallery" class="smoothScroll">MENU</a></li> <li class="dropdown"><a class="dropdown-toggle" data-toggle="dropdown" href="#">TEAMS <span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="#roster1" class="smoothScroll">DARTS</a></li> <li><a href="#roster2" class="smoothScroll">SOFTBALL</a></li> </ul> </li> </ul> </div> </div> </div> </nav> </tbody> </table> </div> </div> </div> </section> <!-- end about --> <!-- start footer --> <footer> <div class="container"> <div class="row"> <div class="col-md-12"> <p>Copyright © 2015 Third Base Sports Bar & Grill</p> <hr> <ul class="social-icon"> <li><a href="#" class="fa fa-facebook"></a></li> <li><a href="#" class="fa fa-twitter"></a></li> <li><a href="#" class="fa fa-instagram"></a></li> <li><a href="#" class="fa fa-pinterest"></a></li> <li><a href="#" class="fa fa-google"></a></li> <li><a href="#" class="fa fa-github"></a></li> <li><a href="#" class="fa fa-apple"></a></li> </ul> </div> </div> </div> </footer> <!-- end footer --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script src="js/bootstrap.min.js"></script> <script src="js/plugins.js"></script> <script src="js/smoothscroll.js"></script> <script src="js/custom.js"></script> </body> </html>
The problem is that LiveOperationResult.Result
isn't necessarily guaranteed to be a Dictionary<string, object>
. It is however defined as an IDictionary<string, object>
.
Mind you, you don't appear to even need to cast the Result
property to a dictionary of any sort; you should be able to use the dynamic
variable to directly access the list you want to iterate.
List<object> folders = (List<object>)result.data;
-2778184 0 If performance is a concern, it's unclear to me why you'd be bothering to construct an entire array in the first place. Why not just this?
foreach (var item in myItems.Where(FILTER-IT-HERE)) MY-ACTION;
Or:
foreach (var item in myItems) MY-ACTION-WITH-FILTER;
I ask because, while the others are right that you can't really know without testing, I wouldn't expect there to be much difference between the above two options. I would expect there to be a difference, on the other hand, between creating/populating an array (seemingly for no reason) and not creating an array.
-29507406 0 I don't understand how this Integration test is failing in GrailsThis is a basic mock of a web service where a Patient object is checked for eligibility. I have included the console output to show the test failing.
When I run this test in the groovyConsole it passes.
Basic Patient Class:
class Patient { String firstName, lastName Date dateOfBirth }
Create the patient object:
Patient p1 = new Patient( firstName: 'Mike', lastName: 'Smith', dateOfBirth: new GregorianCalendar(1968, Calendar.AUGUST, 23).time ).save(flush: true, failOnError: true)
Mock setup:
This test normally queries a web service. I need to mock the service due to firewall issues. I build a tree that replicates the service call.
def eligibilityMock(Patient pat) { def tree = { -> return [:].withDefault{ tree() } } def member = tree() if (pat.firstName == "Mike" && pat.lastName == "Smith") { member.memberInfo.memberDetails.value.memberFirstName.value = 'Mike' } member }
I call the mocked service
//def memberInfo = eligibilityMock(p1) def member = humanaEligibilityMock(p1).memberInfo
I expect the firstName to match
assert p1.firstName == memberInfo.memberDetails?.value?.memberFirstName?.value
It seem the values match up, however the assertion fails.
p1.firstName == memberInfo.memberDetails?.value?.memberFirstName?.value | | | | | | | Mike | | | | [value:[:]] [:] | | | [memberFirstName:[value:[:]]] | | [value:[memberFirstName:[value:[:]]]] | [memberInfo:[memberDetails:[value:[memberFirstName:[value:Mike] false
-14340854 0 The problem is that your never adding player to the stage before checking to see what it's x value is.
-36911247 0 changing cell template property in Angular UI GridI am working on Angular UI grid
and I am trying to change the cell template property on button click but it is not affecting the UI grid
.
Here is the punker and when I click on toggleDisplay name it is not getting changed.
check link:-
plnkr.co/edit/Q0WcJC37bSGF7Huet39Q?p=preview
-37211720 0 creates sheets based on a list and populate only with data where a column matches the sheet nameI've been working on having a workbook create sheets and populate those sheets based on values in a pivot table. Through my various searches, I've been able to create sheets based on the list using something similar to this (credit to rizvisa1 on ccm.net):
`Sub CreateSheetsFromAList() Dim nameSource As String 'sheet name where to read names Dim nameColumn As String 'column where the names are located Dim nameStartRow As Long 'row from where name starts Dim detailSheet As String 'sales detail sheet name Dim detailRange As String 'range to copy from sales detail sheet Dim nameEndRow As Long 'row where name ends Dim employeeName As String 'employee name Dim newSheet As Worksheet nameSource = "Pivot" nameColumn = "A" nameStartRow = 5 detailSheet = "Pivot" 'this is the range where I want to only copy and paste the rows/records that match the new sheet name detailRange = "A5:D463" 'find the last cell in use nameEndRow = Sheets(nameSource).Cells(Rows.Count, nameColumn).End(xlUp).Row 'loop till last row Do While (nameStartRow <= nameEndRow) 'get the name employeeName = Sheets(nameSource).Cells(nameStartRow, nameColumn) 'remove any white space employeeName = Trim(employeeName) ' if name is not equal to "" If (employeeName <> vbNullString) Then On Error Resume Next 'do not throw error Err.Clear 'clear any existing error 'if sheet name is not present this will cause error to leverage Sheets(employeeName).Name = employeeName If (Err.Number > 0) Then 'sheet was not there, so it create error, so we can create this sheet Err.Clear On Error GoTo -1 'disable exception so to reuse in loop 'add new sheet Set newSheet = Sheets.Add(After:=Sheets(Sheets.Count)) 'rename sheet newSheet.Name = employeeName Application.CutCopyMode = False 'clear clipboard 'copy sales detail Sheets(detailSheet).Range(detailRange).Copy 'paste training material Sheets(employeeName).Cells(1, "A").PasteSpecial Application.CutCopyMode = False End If End If nameStartRow = nameStartRow + 1 'increment row Loop End Sub`
The only problem here is that it I've only been copying a static range.
My issue is selecting the range where the first column matches the sheet name in order to copy and paste into the newly created sheet. I've tried using For Each
where a cell matches the sheet name and copying the entire row, but haven't been able to get the results I need.
Here's what I'm trying to do:
Take a sheet with the following data in a pivot table: Pivot
And turn it into new sheets with the sheet names from column A, populated with only the data that matches the sheet name like this:
Any help you can provide would be greatly appreciated.
-11676494 0 Jquery ui Dialogue close event to refresh windowI need a way to reload my parent page when I close my jqUI modal window. Somehow or the other, what I am currently doing is not working (imagine that)...
$('div#addPat').live('dialogclose', function (event) { debugger; location.reload(true); });
I never get to the debugger statement so I assume just assume that my event is wrong...
How do I get the close dialog event and how can I use it to reload the page... I think I have the second part figured out.
-28876350 0If it's not a student assignment and you truly are using C++(as your tag says) you should use strings. Now you're using arrays and comparing arrays addresses instead of real strings. In a C++ way your code might look like:
#include <iostream> #include <string> int main() { std::string a ="wasd"; std::string b ="asd"; if(a.substr(1) == b) std::cout << "Yes!\n"; }
Well, there is a better way to find if one string contains another but the code is a direct mapping of your C code to the C++-ish one.
-10380749 0Hey try this one Just defined color to all links. Change the link color to your desire one.
-21220687 0How to use ShellExecuteEx to undelete a file in the Recycling Bin given its parsing name:
' some file we got from the recycle bin iterating through the IShellItems: Dim sParsing As String = _ "E:\$RECYCLE.BIN\S-1-5-21-2546332361-822210090-45395533-1001\$RTD2G1Z.PNG" Dim shex As New SHELLEXECUTEINFO shex.cbSize = Marshal.SizeOf(shex) ' Here we want ONLY the file name. shex.lpFile = Path.GetFileName(sParsing) ' Here we want the exact directory from the parsing name shex.lpDirectory = Path.GetDirectoryName(sParsing) shex.nShow = SW_SHOW ' = 5 '' here the verb is undelete, not restore. shex.lpVerb = "undelete" ShellExecuteEx(shex)
-13391025 0 def switch_ext f, new_ext "#{f.sub(/\.[^.]+\z/, "")}.#{new_ext}" end
-26313269 0 I guess you pass the wrong CGPoint
coordinate to the hitTest:withEvent:
method causing wrong behavior if the scroll view is scrolled.
The coordinate you pass to this method must be in the target views coordinate system. I guess your coordinate is in the UIScrollView
's superview's coordinate system.
You can convert the coordinate prior to using it for the hit test using CGPoint hitPoint = [scrollView convertPoint:yourPoint fromView:scrollView.superview]
.
In your example you let the container view perform the hit testing, but the container can only see & hit the visible portion of the scroll view and thus your hit fails.
In order to hit subviews of the scroll view which are outside of the visible area you have to perform the hit test on the scroll view directly:
UIView *firstSubview = [_scrollView hitTest:number1RectanglePoint withEvent:nil]; UIView *fifthSubview = [_scrollView hitTest:number5RectanglePoint withEvent:nil];
-30948291 0 You can write some custom validation
validate do valid_phone_codes = [ "007", "042", ...] valid_phone_codes.each do |valid_code| # Also handle optional parenthesis return true if self.phone_number.starts_with?(valid_code, "(#{valid_code})") end errors.add(:phone_numbers, "Must start with a valid country code (one of #{valid_phone_codes.join(', ')}") false end
Or if you prefer, you can declare this code in a function def valid_country_codes
, and then add a line
validate :valid_country_codes
-32486198 0 Sending a sequence of commands and wait for response I have to update firmware and settings on a device connected to a serial port. Since this is done by a sequence of commands, I send a command and wait until I recive an answer. Inside the answere (many lines) I search for a string that indicates if the operation is finished successfully.
Serial->write(“boot”, 1000); Serial->waitForKeyword(“boot successful”); Serial->sendFile(“image.dat”); …
So I’ve created a new Thread for this blocking read/write method. Inside the thread I make use of the waitForX() functions. If I call watiForKeyword() it will call readLines() until it detects the keyword or timesout
bool waitForKeyword(const QString &keyword) { QString str; // read all lines while(serial->readLines(10000)) { // check each line while((str = serial->getLine()) != "") { // found! if(str.contains(keyword)) return true; } } // timeout return false; }
readLines() reads everything available and separates it into lines , each line is placed inside a QStringList and to get a string I call getLine() which returns the first string in the list and deletes it.
bool SerialPort::readLines(int waitTimeout) { if(!waitForReadyRead(waitTimeout)) { qDebug() << "Timeout reading" << endl; return false; } QByteArray data = readAll(); while (waitForReadyRead(100)) data += readAll(); char* begin = data.data(); char* ptr = strstr(data, "\r\n"); while(ptr != NULL) { ptr+=2; buffer.append(begin, ptr - begin); emit readyReadLine(buffer); lineBuffer.append(QString(buffer)); // store line in Qstringlist buffer.clear(); begin = ptr; ptr = strstr(begin, "\r\n"); } // rest buffer.append(begin, -1); return true; }
The problem is if I send a file via terminal to test the app readLines() will only read a smale part of the file ( 5 Lines or so). Since these lines do not contain the keyword. the function will run once again, but this time it dosnt wait for timeout, readLines just return false immediately. Whats wrong ? Also I'm not shure if this is the right approach... Does anyone know how to send a sequenze of commands and wait for a response each time?
-1077098 0One answer is to hackishly add some get query parameter like has been suggested.
A better answer is to emit a couple of extra options in your HTTP header.
Pragma: no-cache Expires: Fri, 30 Oct 1998 14:19:41 GMT Cache-Control: no-cache, must-revalidate
By providing a date in the past, it won't be cached by the browser. Cache-Control
was added in HTTP/1.1 and the must-revalidate tag indicates that proxies should never serve up an old image even under extenuating circumstances, and the Pragma: no-cache
isn't really necessary for current modern browsers/caches but may help with some crufty broken old implementations.
What is the value in the cell?
It looks like it is 19240, which means that formatting it to 2DP will return 19240.00, as you are seeing. If you want 192.40, then you'll need to divide by 100 first - you'll not be able to do this with string formats.
-8730788 0I did some of your work for you and found this date:duration function, which you seem to be trying to use. However, date:duration converts a number of seconds into a duration formatted string, whereas you want to find the difference (duration) between two datetime strings.
You probably want date:difference instead. If you read the documentation for this function/template, you'll find this about the arguments:
The two dates must both be right-truncated date/time strings in one of the formats defined in [XML Schema Part 2: Datatypes]. ... The permitted formats are as follows...
xs:dateTime (CCYY-MM-DDThh:mm:ss) ...
There are italics there in the original: CCYY-MM-DDThh:mm:ss except the T is not italicized. In other words, the time strings need a literal T
between the date and the time, whereas yours have a space.
So I would suggest fixing that:
<start>2011-12-13T16:15:26</start> <end>2011-12-13T16:17:27</end>
Pass the start
and end
strings as parameters to the template. You can do this by just passing the start
and end
element nodes, which will be automatically converted to strings based on their text content:
<xsl:variable name="time-diff-dur"> <xsl:call-template name="date:difference"> <xsl:with-param name="start" select="start" /> <xsl:with-param name="end" select="end" /> </xsl:call-template> </xsl:variable> <!-- The above returns a duration formatted string, so convert that to seconds: --> <xsl:variable name="time-diff-sec"> <xsl:call-template name="date:seconds"> <xsl:with-param name="seconds" select="$time-diff-dur" />? </xsl:call-template> </xsl:variable>
This code assumes that the context node is the parent of the <start>
and <end>
elements. After the above code, the variable $time-diff-sec
will contain a result tree fragment, which can be converted to a number using number($time-diff-sec)
if necessary.
Let us know whether that works. If not, state specifically what the result was and how it differs from what you expected.
Update:
I just noticed that you are using xsltproc (which uses libxslt). According to this documentation, libxslt supports date:difference
(and date:seconds
) natively. So you can call these functions as functions instead of defining a named template and calling it as a template. That would be a lot less code for you, albeit less portable:
<xsl:variable name="time-diff-sec" select="date:seconds(date:difference(start, end))" />
As before, you will need to declare the date
namespace prefix somewhere, usually on your xsl:stylesheet
element:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:date="http://exslt.org/dates-and-times" extension-element-prefixes="date">
-34376682 0 You want to get an ISO 7185 compliant compiler to compile that. It is true that Pascal-P4 (the proper name) was written prior to the ISO 7185 standard. However, the adaption to the standard is generally less of a change set than adaption to a dielect.
You will find that work already done and documented at:
http://sourceforge.net/projects/pascalp4/
It specifies use of GPC. However, as Marco said, it is possible with more work to adapt to FPC, and I believe the FPC folks are improving the ISO 7185 capability of their compiler.
Having said that, I'm not sure why Pascal-P4 would be an interesting target. Pascal-P4 was a subset compiler, meaning an incomplete implementation of Pascal. You will find a complete implementation as Pascal-P5:
http://sourceforge.net/projects/pascalp5/
And I believe it has less portability issues as well.
Good luck.
-4770809 0byte[] temp1 = BitConvert.GetBytes(num1); byte[] temp2 = BitConvert.GetBytes(num2); Array.Copy(temp1, 0, buf, 0, 4); Array.Copy(temp2, 0, buf, 4, 4); Array.Copy(buf, 8, headers.key3, 0, 8) buf[16] = 0; Array.Copy(buf, target, 16) target[16] = 0; Using MD5 hasher = new MD5CryptoServiceProvider() target = hasher.ComputeHash(buf); End Using
-20998810 0 You can use .siblings()
this way:
$('.image, .icon').hover(function(e) { if(e.type === 'mouseenter' && $(e.target).is('.image')){ $('.icon').stop().animate({"opacity": 0}); $(this).siblings('.icon').stop().animate({"opacity": 1}); } if(e.type === 'mouseleave' && $(e.target).is('.icon')){ $('.icon').stop().animate({"opacity": 0}); } });
and change your context to current selector with $(this)
Is there an error of some sorts, or you just don't understand how that works?
navigator.webkitGetUserMedia
expects 3 arguments. One for configuration data, one for a function to call on success (a success callback) and one to call on error.
Note that it expects a function. This code passes a reference to the function by name; it will be called with the appropriate parameter (from within webkitGetUserMedia
).
Consider this code, it works in the same manner:
function hello(subject) { alert("Hello, " + subject + "!"); } function passWorldTo(callback) { callback("world"); } passWorldTo(hello);
Lets say I have two controllers and two actions.
Controller - > AController Action -> MethodA()
.
Controller - > BController Action -> MethodB()
Both of these return xml data by a View(typedObject).
I want to add base 64 encoding before returning this output to the client. On MethodA and MethodB. And there might be some other methods that should be included in this encoding aswell.
Would there be any good way of accomplish an behavoir / treatment of the action result ?
Would it be best to add a custom Action Result for this ?
-7016100 0 WPF Border Object Border CornerRadius different from Border Background CornerRadiusI have two Borders on top of each other. One with a BorderThickness but no background, the other one without a border thickness, but with a background. Both Borders have a CornerRadius of 3. The problem is that the corner of the Background of one of the Borders sticks out from behind the corner of the other Border.
Here is the XAML with the first border element having the background and the Border named FocusVisual having the BorderThickness.
<Grid x:Name="grid"> <Border Background="{TemplateBinding Background}" CornerRadius="3"> <Grid> <Border x:Name="MouseOverVisual" Opacity="0" Background="{StaticResource NuiFieldHoverBrush}" CornerRadius="3" /> <Border> <Grid> <ScrollViewer x:Name="PART_ContentHost" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" /> <ContentPresenter x:Name="PART_WatermarkHost" Content="{TemplateBinding Watermark}" ContentTemplate="{TemplateBinding WatermarkTemplate}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" IsHitTestVisible="False" Margin="{TemplateBinding Padding}" Visibility="Collapsed"/> </Grid> </Border> </Grid> </Border> <Border x:Name="FocusVisual" Opacity="0" BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{StaticResource NuiFocusBrush}" CornerRadius="3" /> </Grid>
CornerRadius having a different effect on the Background and Border of a Border object seems like a bug in WPF.
I could add a BorderThickness to the Border with the Background and set the BorderBrush to the Background color, but this causes the child elements of that border to be pushed in by the BorderThickness. I can probably get around this by rearranging elements, but it is kind of a pain so I thought I would see if anybody has a better workaround.
-8247155 0I assume neither stream is a backing stream for the other; if it was you could just promote or update the files up/down the stream hierarchy.
Otherwise, you could try to Change Palette, though I'm not sure you can do that without a workspace.
See here: http://www.accurev.com/download/docs/4.6.1_books/WebHelp/Change_Palette.htm
-23290347 0 How to get a list which contains at least all the values of another list?I have the situation where a list must contains at least the values of another list. So imagine we have list A with values 1, 2, 3. This is the list with the required values.
List B has the values 1, 5, 6, 7
List C has the values 1, 2, 3, 4, 7
List D has the values 2, 5, 6
In this situation I only want List C, since this is the only list which contains the values 1, 2 end 3.
I've tried this, but this doesn't work since it is always true:
query = from doc in query let tagIds = from t in doc.Tags select t.Id where parameters.TagIds.Except(tagIds).Count() <= parameters.TagIds.Count() select doc;
And when using this:
query = from doc in query let tagIds = from t in doc.Tags select t.Id where !parameters.TagIds.Except(tagIds).Any<int>() select doc;
I only get the lists where the list matches exactly the 'required' list.
My question is, how can I solve my situation in a Linq 2 SQL query?
-16569293 0 MySQL: Limit by a group of rows, not by a rowI have a MySQL table like the following. The id
and name
fields are just here to help identify the row, l
represents many other fields whit not relevant data, and lat
and lng
are used to find duplicated entries.
CREATE TABLE v (`id` int, `lat` int, `lng` int, `l` varchar(3), `name` varchar(8)) ; INSERT INTO v (`id`, `lat`, `lng`, `l`, `name`) VALUES ( 1, 12, 12, 'a', 'group1-1'), ( 2, 12, 12, 'b', 'group1-2'), ( 3, 13, 12, 'c', 'single1'), ( 4, 13, 13, 'd', 'group2-1'), ( 5, 13, 13, 'e', 'group2-2'), ( 6, 13, 13, 'f', 'group2-3'), ( 7, 10, 13, 'g', 'group3-1'), ( 8, 10, 13, 'h', 'group3-2'), ( 9, 11, 12, 'h', 'group4-1'), (10, 11, 12, 'h', 'group4-2'), (11, 10, 14, 'i', 'group5-1'), (12, 10, 14, 'j', 'group5-2'), (13, 10, 14, 'j', 'group5-3') ;
Now I want to get all rows where there is more than one row with the same lat and lng values (let's call that a group):
SELECT v.* FROM v INNER JOIN ( SELECT lat, lng FROM v GROUP BY lat, lng HAVING COUNT(*) > 1 ) AS vg USING (lat, lng) ORDER BY name ;
Outputs:
ID LAT LNG L NAME 1 12 12 a group1-1 2 12 12 b group1-2 4 13 13 d group2-1 5 13 13 e group2-2 6 13 13 f group2-3 7 10 13 g group3-1 8 10 13 h group3-2 9 11 12 h group4-1 10 11 12 h group4-2 11 10 14 i group5-1 12 10 14 j group5-2 13 10 14 j group5-3
Works well so far, all but the "single1" rows are selected and ordered by group.
Now I want to add a limit to form different pages of this data. But all rows of the same group need to be on the same page (but not one page per group and it doesn't matter how many rows actually are on one page - just not too many). I don't see this done with a LIMIT statement, so I started to write my own:
SET @grp := 0, @last_lat := '', @last_lng := ''; SELECT * FROM ( SELECT v.*, @grp := IF((@last_lat = lat) && (@last_lng = lng), @grp, @grp + 1) AS grp, @last_lat := lat AS llat, @last_lng := lng AS llng FROM v INNER JOIN ( SELECT lat, lng FROM v GROUP BY lat, lng HAVING COUNT(*) > 1 ) AS vg USING (lat, lng) ORDER BY lat, lng ) AS vv WHERE grp BETWEEN 0 AND 7 ORDER BY grp ;
This query whit out the WHERE part outputs this data:
ID LAT LNG L NAME GRP LLAT LLNG 1 12 12 a group1-1 6 12 12 2 12 12 b group1-2 6 12 12 5 13 13 e group2-2 7 13 13 6 13 13 f group2-3 7 13 13 4 13 13 d group2-1 7 13 13 7 10 13 g group3-1 8 10 13 8 10 13 h group3-2 8 10 13 10 11 12 h group4-2 9 11 12 9 11 12 h group4-1 9 11 12 13 10 14 j group5-3 10 10 14 11 10 14 i group5-1 10 10 14 12 10 14 j group5-2 10 10 14
The idea is to change the values in the line WHERE grp BETWEEN 0 AND 7 for each page. But the numbers from the group don't start at 1 and I can't see why (and that makes it unusable for the first page). The Start number is different depending on how many group are in the whole data. So what I need to have, is that the grp column start whit 1 and then continues whit always +1.
What is wrong with this query and are there any better ways to do this?
You can play whit this query here: http://sqlfiddle.com/#!8/86d3c/2
-19140469 0 Run non GUI Java program on ServerI'm really experienced when it comes to Java SE, but aside from helping out on a Java EE program running on a application server like JBoss i have no experience in running Java server side, only PHP applications.
I want to do the following:
I just want to write a Java program, that listens on a port (if there are incoming connections) which has to run on a server. It's no web application, there's no GUI or any stuff like that. It just needs to be approachable via the net from for example a desktop application.
What do i need to run a simple Java program server side which can accept requests as simple as possible? (Server recommendations for this simple task appreciated).
-4867905 0Minimax with Alpha-beta pruning that Lirik mentioned is a good place to start, but it takes some time to wrap your mind around if you're not familiar with it.
Alternatively you can think about how you would play the game if you had a perfect memory and could do fast calculations and try to implement that. The upside is that's usually easier to understand.
Minimax would probably result in shorter but more difficult to understand (for those unfamiliar with it) code that depending on the game, could result in playing a perfect game if the game is simple enough (however it also has the disadvantage of favoring not losing to winning because it assumes the opponent will be playing perfectly as well)
Since it sounds like it's a game of complete information (the whole board is visible to all players at all times) a properly implemented Minimax with infinite look-ahead could give an AI that would never lose (assuming infinite computation time). In games using Minimax the difficulty level is often determined by how many moves ahead the algorithm looks at. It gets exponentially slower the more steps there are, so you will run into a hardware limitation if the game isn't super simple (which is why there isn't a perfect Chess playing AI yet, I think last I checked it would take a couple thousand years on the fastest computer at the time of the article I read, sorry no citations)
-16130820 0 Changing color of fetched amino acidsI want to write a PyMOL script to change a color of an amino acid in the XYZ position (or somehow put some marker with label in the XYZ position).
Does any body know how to do this ?
Thanks
-34320562 0While I have not managed to figure out why there were so many ReaderWriterLock
instances in the finalizer queue, I did find a solution to my problem and got rid of them.
Calling DataSet.Dispose
did not help. Therefore I have started reusing existing DataSet
instances instead of keep creating new ones because 'someone said that DataSet.Clear
is slow' - it is not (if at all) in a long run. This approach completely removed the issue with the finalizer queue instances.
head(df) SparkR error
Error in invokeJava(isStatic = TRUE, className, methodName, ...) : org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 6.0 failed 1 times, most recent failure: Lost task 0.0 in stage 6.0 (TID 6, localhost): java.io.IOException: Cannot run program "Rscript": CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessBuilder.start(Unknown Source) at org.apache.spark.api.r.RRDD$.createRProcess(RRDD.scala:407) at org.apache.spark.api.r.RRDD$.createRWorker(RRDD.scala:445) at org.apache.spark.api.r.BaseRRDD.compute(RRDD.scala:62) at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:300) at org.apache.spark.rdd.RDD.iterator(RDD.scala:264) at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38) at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:300) at org.apache.spark.rdd.RDD.iterator(RDD.scala:264) at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38) at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.sc
-38976399 0 Answering question 2, with pandas 0.18.0 you can do:
store = pd.HDFStore('compiled_measurements.h5') for filepath in file_iterator: raw = pd.read_csv(filepath) store.append('measurements', raw, index=False) store.create_table_index('measurements', columns=['a', 'b', 'c'], optlevel=9, kind='full') store.close()
Based on this part of the docs.
Depending on how much data you have, the index creation can consume enormous amounts of memory. The PyTables docs describes the values of optlevel.
-11384726 0Use EXPLAIN
to see how MySQL handles the queries, it might give you a clue.
Also, try some other characters. Maybe MySQL is misinterpreting one of those as having a percent sign in it.
-17655183 0 DNSServiceNATPortMappingCreate always returning error code -65540I'm doing an ios application, it starts a server and listen for incoming connections, the device running the application may be behind a router so I need to make a port forward. I'm trying to make a port forward using DNSServiceNATPortMappingCreate but its always returning error code -65540
DNSServiceRef *sdRef = NULL ; void ( *DNSServiceNATPortMappingReply) (DNSServiceRef sdRef, DNSServiceFlags flags, uint32_t interfaceIndex, DNSServiceErrorType errorCode, uint32_t externalAddress, DNSServiceProtocol protocol, uint16_t internalPort, uint16_t externalPort, uint32_t ttl, void *context ); DNSServiceNATPortMappingReply = &DNSServiceNATPortMappingCreate_callback ; DNSServiceErrorType error = DNSServiceNATPortMappingCreate(sdRef, 0, 0, kDNSServiceProtocol_TCP, htons(2000), htons(5000), 0, DNSServiceNATPortMappingReply, NULL ) ;
and this is the callback
void DNSServiceNATPortMappingCreate_callback( DNSServiceRef sdRef, DNSServiceFlags flags, uint32_t interfaceIndex, DNSServiceErrorType errorCode, uint32_t externalAddress, DNSServiceProtocol protocol, uint16_t internalPort, uint16_t externalPort, uint32_t ttl, void *context ) { printf("in callback\n") ; }
-38889581 0 How to get the root url at startup in an OWIN asp.net Web API I have found many posts very similar to this, but I didn't find any that worked for me.
I have an asp.net Web Api2 (not vnext) application, running under IIS, and using the Owin Startup class.
When installed, the root url to this will be something like
http://localhost/appvirtualdirectory
where appvirtualdirectory
is the name of the virtual directory it is configured to run under in IIS.
IS there a way at startup where I have no Request property, ie in the Startup.Configure
method, to get the root URL including the virtual directory being used?
You can reverse the query on the secondary categories:
(SELECT articles.* FROM articles WHERE primary_category_id = 1) UNION DISTINCT (SELECT articles.* FROM articles_secondary_categories AS categories JOIN articles ON (categories.article_id = articles.id) WHERE categories.category_id = 1 GROUP BY articles_id) ORDER BY publish_at DESC LIMIT 10;
It should give you a decent speed boost - just make sure you index categories.articles_id
-4952272 0Make sure it works fine in Opera Mobile. (Download the Mobile emulator from here - http://www.opera.com/developer/tools/)
Understand OBML to get an idea of what javascript will / won't work.
I have a problem with my winform c# project.
I want to move new button that I made at run time around the form. How can I do that?
Button[] buttons = new Button[1000]; int counter = 0; Button myText = new Button(); private void button2_Click(object sender, EventArgs e) { Button myText = new Button(); myText.Tag = counter; myText.Location = new Point(x2,y2); myText.Text = Convert.ToString(textBox3.Text); this.Controls.Add(myText); myText.MouseMove += new MouseEventHandler(myText_MouseMove); myText.MouseDown += new MouseEventHandler(myText_MouseDown); buttons[counter] = myText; counter++; } public void myText_MouseMove(object sender, MouseEventArgs e) { int s = e.GetHashCode(); int check = 0; for (int i = 0; i < counter; i++) { if (buttons[i].GetHashCode() == s) check = i; } if (e.Button == MouseButtons.Left) { buttons[check].Left += e.X - move.X; buttons[check].Top += e.Y - move.Y; } } void myText_MouseDown(object sender, MouseEventArgs e) { move = e.Location; }
I use that code to make the new button and tring move him. Now I want to move it around the form.
If i do that just to one button, I can move it, but if it's more then one, that is a problem.
If someone could give the code,fix him or just help me it will be very good for me! tnx :)
-8570011 0Under VS2010 it is a little different. Right click the Project and select Properties. Select the "Application" tab and then click "View Windows Settings". This opens the manifest. Then make the changes you need.
-36071414 0Check web.config file for invalid entries. For example, having "entityFramework" tag there causes this problem for me.
-36369918 0 Resizing C# Windows FormNot sure if this is the standard way of creating a form and opening, but the code the below does display the form properly. My problem is that I can't programatically change it's size. I'm guessing it has to do with the scope, "main" creates the form object, but I'd like to be resize it in the scope where it actually gets initialized (instead of in the [Design] tab of MS Studio) but I can't find the object/handle to it!
main.cs: class MainProgram { static void Main(string[] args) { // Create Form Object and Open Gui for user MainForm newFrm = new MainForm(); // Mainform is type Systems.Windows.Forms.Form Application.Run(newFrm); } } formFile.cs: public partial class MainForm : Form { public MainForm() { InitializeComponent(); //TODO: How to Resize Form from here? //this.Size.Height = 100; // ERROR! } }
-16747417 0 Have you downloaded the "Moxie Manager" plugin. Check the folder tinymce/plugins/moxiemanager to see if you have the file plugin.min.js
If you do not have the file or the folder moxiemanager itself, then modify the following line
"emoticons template paste moxiemanager"
to
"emoticons template paste"
Hope this helps
-14938323 0You can use subqueries to get what you want, for example:
SELECT * FROM (SELECT INs.catid AS CategoryID, INs.subcatid AS SubcategoryID, SUM(INs.quantity) AS QuantityIN FROM in_stock INs GROUP BY INs.catid, INs.subcatid) AS a LEFT JOIN (SELECT OUTs.catid AS CategoryID, OUTs.subcatid AS SubcategoryID, SUM(OUTs.quantity) AS QuantityOUT FROM out_stock OUTs GROUP BY OUTs.catid, OUTs.subcatid) AS b ON ( a.subcategoryid = b.subcategoryid ) AND ( a.categoryid = b.categoryid );
From this, it is very easy indeed to edit and modify the query using the Query Design Window in MS Access
SELECT a.categoryid, a.subcategoryid, a.quantityin, b.quantityout, [quantityin] - [quantityout] AS RemainingQuantity FROM (SELECT INs.catid AS CategoryID, INs.subcatid AS SubcategoryID, SUM(INs.quantity) AS QuantityIN FROM in_stock INs GROUP BY INs.catid, INs.subcatid) AS a LEFT JOIN (SELECT OUTs.catid AS CategoryID, OUTs.subcatid AS SubcategoryID, SUM(OUTs.quantity) AS QuantityOUT FROM out_stock OUTs GROUP BY OUTs.catid, OUTs.subcatid) AS b ON ( a.subcategoryid = b.subcategoryid ) AND ( a.categoryid = b.categoryid );
-8148490 0 Install the New Relic Standard addon - that will give you insight into your application and what's going on. The 'Dynos' tab will show you memory utilisation of your application, it sounds like an awfully high memory utilisation for the level of traffic you're reporting but it depends on your application - if you're seeing memory errors in the log then performance will be suffering see http://devcenter.heroku.com/articles/error-codes#r14__memory_quota_exceeded
Are you using any kind of error handling? You could install the Airbrake addon so you get notification of errors or use the Exception Notifier gem which will email you errors as they occur. Once you have these in place you'll know what's occuring - whether it's in the application or if you don't receive any then it's outside factors, like the visitors internet connection etc.
-30336450 0vagrant destroy
does not remove plugins. As per https://docs.vagrantup.com/v2/cli/destroy.html, it "stops the running machine Vagrant is managing and destroys all resources that were created during the machine creation process".
You can uninstall plugins with vagrant plugin uninstall <name>
(documented at https://docs.vagrantup.com/v2/cli/plugin.html)
I'm not sure if I make sense, maybe there are easier ways.
I am building a web app, which will be based in Bootstrap models, what I want is to display a model to make CRUD operations to my database.
For example I will have a models like these:
public class Author { public int id { get; set; } public string Name { get; set; } } public class Book { public int id { get; set; } public string Name { get; set; } }
What I want is to make a partial view that will display a dialog (modal) to add a new author to my app, same with books, and my 'n' classes my app will have, I want to render these partials wherever I need them. So I can add an author from any view of my page.
That part is ok, now I am having some 'troubles' because when I make an ajax post call to save my author in my data base I am facing that I already had a #Name field which was the one rendered for my books modal now when I call my field with jQuery, like this: $('#Name').val()
it will grab the first #name.
That is easy to solve I will make a #AuthorName and a #BookName.
Now I am scared that my application will not be stable if my name system is not.
So is there any way to make an name system?
I am not sure how to do this but I would like to write my id's like this:
@Html.TextBoxFor(u => u.Id, new { @id = "@MyDialogs.Authors.Add.Name" })
that will return something like this: dialogs-authors-add-namefield
Is this possible or I am being too lazy?
-15129649 0Why don't you query the database once to catch all information? Take a look at this:
connect(); $sql = 'SELECT gameid, mizbanid, mihmanid, score1, score2, gamedavar, gamestadium, now FROM games WHERE gameweek = ' . $site_week . ' ORDER BY now ASC LIMIT 9'; $query = mysql_query($sql); if(mysql_num_rows($query)) { while($Result = mysql_fetch_object($query)) { //loop trough results print_r($Result); //prints the results. echo $Result->gameid; //this is how you echo the data } }
Be aware that the mysql_query function is deprecated and needs to be replaced by mysqli :) .
-10008125 0 SSRS Report, How do I have Group By on the ColumnsIn MS SQL 2008 R2 DB, I have a table:
Name, Value, Type A, 1, T1 B, 2, T1 C, 3, T1 D, 4, T1 A, 10, T2 B, 20, T2 C, 13, T2 D, 45, T2 A, 11, T3 B, 22, T3 C, 33, T3 D, 44, T3
What I want to do is to get this:
Name, Type T1, T2, T3 A, 1, 10, 11 B, 2, 20, 22 C, 3, 13, 33 D, 4, 45, 44
From the query, I can return this: Name, Value, Type A, 1, T1 B, 2, T1 C, 3, T1 D, 4, T1
A, 10, T2 B, 20, T2 C, 13, T2 D, 45, T2 A, 11, T3 B, 22, T3 C, 33, T3 D, 44, T3
Now I want to take this data and in SSRS, transform it into this form:
Name, Type T1, T2, T3 A, 1, 10, 11 B, 2, 20, 22 C, 3, 13, 33 D, 4, 45, 44
Types can change from one execution to another.
-14141043 0 Resolving an ambiguous referenceI'm trying to create a manager class to use with my charting tool, the problem is the tool I use, uses the same names for both a 3d and 2d charts which is resulting in ambiguous reference when I try to add the 2d library.. any ideas how best to resolve this?
For example,
using tool.2dChartLib; using tool.3dChartLib;
BorderStyle is a member of both of these
I've tried casting the areas where I use BorderStyle. I suppose it could work if i just reference tool
but then that would mean I'd have hundreds of tool.class
lines instead of class
I am working on a Wordpress site where 100,000+ spam accounts have been made. Although there are other types as well but many of them seem to have a user name that starts with a number.
So I wanted to ask whether there can be a MYSQL
query to select/delete
all users whose username starts with a number.
An extension to this question is that whether those users need to be deleted from the users table only or also the user-meta or other tables.
Any help appreciated.
-521045 0Try escaping the .. with something like:
Uri target = new Uri("ftp://ftpserver.com/%2E%2E/AB00000/incoming/files");
That works according to this blog which I found in this discussion.
-33885597 0You must use string formatting to substitute variable for its value
cursor.execute("UPDATE `ISEF_DB`.`attendance` SET `present`='1' WHERE `id` = '%s'" % data)
Although be warned that this leaves you susceptible to SQL Injection. To prevent that you can use exceute like so (from the docs)
cursor.execute("UPDATE `ISEF_DB`.`attendance` SET `present`='1' WHERE `id` = '%s'", (data,))
i.e. pass the values as tuples to execute
. More information about avoiding SQL injection when using MySQLDB can be found in this question
Update:
Just realized that I've misread your question as you are looking for methods defined via the Flex ExternalInterface class
rather than those of the Shockwave ActiveX control
itself; I'm gonna keep my original answer below as it might still be helpful regarding SWF
usage via C# in general.
Concerning ExternalInterface
I don't have an answer right now, but you might look into Fun with C# and the Flash Player 8 External API to get an idea on how to use this API via C# in the first place. (Another helpful sample might be Use External Interface of Flash 8 in Python and C# Applications.)
From what I'm reading in the former article there is likely no straight forward solution and the calling conventions via passing crafted XML fragments to CallFunction()
are somewhat quirky, still you should be able to translate Georges solution to this in principle (as I said, it's likely not gonna be pretty ;)
Good luck!
How to access a SWF from .NET via COM Interoperability:
SWF
for Windows is implemented by means of the Adobe Flash Player ActiveX control, consequently you would use it from .NET via COM Interoperability.
You can find a (legacy) article/sample regarding this on Adobes site, see Embedding Macromedia Flash Player in a C# Application to Display Stock Information for an overview (please note the introductory note of the article regarding unavailability of the sample code), but see below.
More specifically you can find the initial steps you need to take to achieve your goal on another page of this article, see Embedding and Communicating with the Macromedia Flash Player in C# Windows Applications - in particular please follow the article/steps up to and including section Making the Macromedia Flash Player ActiveX Control Available Within Visual Studio .NET.
Once you have completed the outlined steps to add the Shockwave ActiveX control
to your toolbox and to a particular projects references you can simply double click this reference (named ShockwaveFlashObjects
in Visual Studio 2008), which will open the Visual Studio object browser highlighting the assembly Interop.ShockwaveFlashObjects
; then navigate down into the namespace ShockwaveFlashObjects
, where you'll find, amongst others, the interface IShockwaveFlash
, exposing (depending on your view filter) all its members, including the desired external methods with their respective C# signatures.
You can try using AttachAware and it's attach method. You should implement AttachAware interface in your decorator and/or component.
Here's link to Angular.dart docs - https://docs.angulardart.org/#angular-core-annotation.AttachAware
To change the styling of a ShadowDom component you can use element.shadowRoot to get the root of your web component. Shadow root is almost like 'document' object. You can use shadow root to get reference to any element and then you can easily modify it by applying styles as needed.
You could use something like this.element.shadowRoot.querySelector('[some-attr]').innerHtml = "Modified by decorator" // disclaimer: not tested, but I hope you get the idea.
-22458951 0In Pentaho EE 5.1 due out sometime this half of the year analyzer will have native mongo support - but that is only EE.
Your other option is indeed to use a SQL layer, and optiq is a good choice for that. The Saiku guys have got mondrian running via optiq to Mongo - and have even built support for aggregations. Note: The native Pentaho support mentioned above does NOT use optiq.
Unfortunately there's few other options at this stage!
-26486963 0The m//
and print
commands are separate commands joined by an &&
.
Within a regex \2
is a backreference to the second capture, which will be assigned to the $2
variable after the regex has finished matching. Outside the regex \2
is meaningless; only $2
is a variable that can be accessed. See here for more info: http://perldoc.perl.org/perlretut.html#Backreferences
When reading that link, note that after Perl 5.10 \2
is still recognized but \g2
is encouraged. This is because \11
is ambiguous.
I have a wellformatted excel file with a lot of macros and styling in it that I want to keep. Then i have this information I want to enter in the file. And I want to do it with ruby.
I've tried roo and spreadsheet but they don't seem able to actually edit the file, just create a new one and loosing all the formattin in the process.
It feels it should be simple to just edit the cells I want and save the file again but obviously it's more complex that I originally though(or I'm completely blind)
Any help is appreciated.
I'm learning ruby at the moment so that's why I would prefer a solution in ruby. If you know there are better suited laguages for this feel free to point me in the right direction and I'll check it out.
Thanks in advance
-31665095 0 Xcode error compiling c++ Expected member name or ';' after declaration specifiersI'm having issues with the checking methods in a c++ library (openNN) i'm trying to compile in Xcode. I'll use an example of one of the methods as i suspect they are all caused by the same issue.
Header declaration where i get the error:
Expected member name or ';' after declaration specifiers.
void check(void) const;
Function definition:
void InverseSumSquaredError::check(void) const { std::ostringstream buffer; // Neural network stuff if(!neural_network_pointer) { buffer << "OpenNN Exception: InverseSumSquaredError class.\n" << "void check(void) const method.\n" << "Pointer to neural network is NULL.\n"; throw std::logic_error(buffer.str().c_str()); } const MultilayerPerceptron* multilayer_perceptron_pointer = neural_network_pointer->get_multilayer_perceptron_pointer(); if(!multilayer_perceptron_pointer) { buffer << "OpenNN Exception: InverseSumSquaredError class.\n" << "void check(void) const method.\n" << "Pointer to multilayer perceptron is NULL.\n"; throw std::logic_error(buffer.str().c_str()); } const unsigned int inputs_number = multilayer_perceptron_pointer->count_inputs_number(); const unsigned int outputs_number = multilayer_perceptron_pointer->count_outputs_number(); if(inputs_number == 0) { buffer << "OpenNN Exception: InverseSumSquaredError class.\n" << "void check(void) const method.\n" << "Number of inputs in multilayer perceptron object is zero.\n"; throw std::logic_error(buffer.str().c_str()); } if(outputs_number == 0) { buffer << "OpenNN Exception: InverseSumSquaredError class.\n" << "void check(void) const method.\n" << "Number of outputs in multilayer perceptron object is zero.\n"; throw std::logic_error(buffer.str().c_str()); } // Mathematical model stuff if(!mathematical_model_pointer) { buffer << "OpenNN Exception: InverseSumSquaredError class.\n" << "void check(void) const method.\n" << "Pointer to mathematical model is NULL.\n"; throw std::logic_error(buffer.str().c_str()); } // Data set stuff if(!data_set_pointer) { buffer << "OpenNN Exception: InverseSumSquaredError class.\n" << "void check(void) const method.\n" << "Pointer to data set is NULL.\n"; throw std::logic_error(buffer.str().c_str()); } // Final solutions error stuff }
If i change the definition in the header to
void InverseSumSquaredError::check(void) const;
I end up with the error:
Extra qualification on member 'check'
I'm currently using the dialect C++98 and Library libc++. Xcode is set to compile sources as Objective-C++ which takes care of most of the other errors.
I can't think of anything else relevant to this issue, it's had me stumped for hours, so any type of help is much appreciated.
-1900283 0I'm not sure, but is the pdf not automaticly downloaded when Adobe or a similar plugin is not available?
-26245745 0The most precise selector you can use here is xPath:
a = Watir::Browser.new :chrome a.goto 'http://THEPAGEURLGOESHERE.COM' descriptions = a.dts(xpath: "//table[@class='tabbed_table']//dl[@class='table-display']/dt[@class='wide']").map { |element| element.text } values = a.dds(xpath: "//table[@class='tabbed_table']//dl[@class='table-display']/dd[@class='wide']").map { |element| element.text } p descriptions.zip(values) #=> # [["Product version:", "1.0"], ["Serial number:", "D00005"], ["System Time:", "Tuesday, October 07, 2014 04:04PM CDT"], ["Uptime:", "16:04:17 up 1 day, 3:32, 1 user, load average: 0.00, 0.04, 0.00"]] a.close
-38752423 0 POSTMAN returns "Could not get any response" on Laravel backend - XAMPP on Mac OSX So I'm running a Laravel backend for my app, and for the last year Postman has been working like a charm, suddenly a couple days ago it just stopped working. I updated the app and nothing changed. It's the standalone app, not the Chrome browser extension. I turned off the SSL verification in the settings pane, but still no changes. Any API request through Postman only doesn't return anything, works fine in the actual website in Chrome. Any suggestions would be greatly appreciated!
Thanks
-10259939 0 Why do I see redefinition error in C?Following is my code, I am trying to run it in Visual Studio.
#include <stdio.h> #include <conio.h> int main() { //int i; //char j = 'g',k= 'c'; struct book { char name[10]; char author[10]; int callno; }; struct book b1 = {"Basic", "there", 550}; display ("Basic", "Basic", 550); printf("Press any key to coninute.."); getch(); return 0; } void display(char *s, char *t, int n) { printf("%s %s %d \n", s, t, n); }
It gives an error of redefinition on the line where opening brace of function is typed.
-25707917 0alarm()
is not a good way to implement periodic events in a server. It functions as an asynchronous signal, and as such is difficult to handle appropriately while something else is going on. For instance, if your server is in the middle of sending a message to a client, having the alarm go off and start generating output would be likely to disrupt the message. Bottom line is, it's not the right way of going about this.
Most client/server applications use the select()
or poll()
system calls at their core. These system calls allow your application to wait for an event to occur (e.g, data arriving) on any number of file descriptors, with an optional timeout. This is how most server applications handle connections with multiple clients at a time.
Using these system calls is likely to require you to restructure your application around a "state machine" model, rather than using program flow to represent state. Explaining how to do this effectively is a larger task than is reasonable for a short answer such as this; prepare to do some research!
-29394253 0Approach #1: Generic case
One approach with bsxfun
and matrix-multiplication
-
mask = bsxfun(@ge,indx_pos,event_start.') & bsxfun(@le,indx_pos,event_end.') Etotal = energy.'*mask
This could be a bit memory-hungry
if indx_pos
has lots of elements in it.
Approach #2: Non-overlapping start/end ranges case
One can use accumarray
for this special case like so -
%// Setup ID array for use in accumarray later on loc(numel(pos))=0; %// Fast pre-allocation scheme valids = event_end+1<=numel(pos); loc(event_end(valids)+1) = -1*(1:sum(valids)); loc(event_start) = loc(event_start)+(1:numel(event_end)); id = cumsum(loc); %// Set elements as zeros in HitEnergy that do not satisfy the criteria: %// pos>0.7 & pos<2.0 HitEnergy_select = (pos>0.7 & pos<2.0).*HitEnergy(:); %// Discard elments in HitEnergy_select & id that have IDs as zeros HitEnergy_select = HitEnergy_select(id~=0); id = id(id~=0); %// Accumulate summations as done inside the loop in the original code Etotal = accumarray(id(:),HitEnergy_select);
-4553312 0 Use String.valueOf(floatNumber)
Suggest use double instead of float
Basically, if I have one component that signals a child routing component, like:
@RouteConfig([ { path: '/users/...', //CHILD ROUTING COMPONENT name: 'Users', component: UsersComponent, useAsDefault: true } ]) export class App { constructor(private _router: Router) {} ucFirst(str:string){ var parts = str.split(' '); for(var i = 0, ilen = parts.length; i < ilen; i++){ parts[i] = parts[i].charAt(0).toUpperCase() + parts[i].slice(1); } return parts.join(' '); } ngOnInit() { //Handle deep links if exist var baseHref = document.getElementsByTagName('base')[0].href; var path = location.href.replace(baseHref, ''); if(path.length){ let slugs = path.split('/'); for(let i = 0, ilen = slugs.length; i < ilen; i++){ slugs[i] = this.ucFirst(slugs[i]); } this._router.navigate(slugs); } } }
And then the child router uses some kind of parameter in one of the paths, like:
@RouteConfig([{ path: '/', name: 'UserList', component: UserListComponent, useAsDefault: true },{ path: '/:id', name: 'UserView', component: UserViewComponent }])
How do I make deep links work? I can use the code to get to the grandchild view, but deep links fail (Error No route 'users/1' where 1 is the :id). Basically I need to handle half of the path in the parent router and half in the child router but I have not found the way to do so. I can make deep links work as long as they exist completely in the parent but I am working on a larger project and want to make the set up more modular.
I have put my code in this plunker: https://plnkr.co/edit/7cKBEwQmFSJrDFWhL4EV?p=preview It works locally (minus the deep links) but not on plunker, which I've never used before so I imagine this is kind of simple configuration issue on my part. But it at least gives you an idea of the attempt at modularization.
-34976548 0This can do it:
$root = "serves/registered.php"; $folder = mkdir($_POST['username']); if($folder) { $reg = "registered.php"; if (!copy($root, $_POST['username']."/".$reg)) { echo "failed to copy $root...\n"; } else { echo "Account was successfuly created."; } } else { echo "Could not create folder"; }
-19440344 0 Html5 Fullscreen Browser Toogle Button I was reading about the HTML5 Fullscreen API. Now I came across a code which lets your browser go full screen.
Now I want to add the functionality to do a toggle on full screen and normal screen. I am not able to understand the code fully.
The button allows us to go full screen for browser. How come I can revert it to normal on click again?
CSS
<style> body { margin: 0px; background-color: brown; } #contento:-webkit-full-screen { width: 100%; height: 100%; } #contento:-moz-full-screen { width: 100%; height: 100%; } </style>
Javascript
<script type="text/javascript"> function goFullscreen(id) { // Get the element that we want to take into fullscreen mode var element = document.getElementById(id); // These function will not exist in the browsers that don't support fullscreen mode yet, // so we'll have to check to see if they're available before calling them. if (element.mozRequestFullScreen) { // This is how to go into fullscren mode in Firefox // Note the "moz" prefix, which is short for Mozilla. element.mozRequestFullScreen(); } else if (element.webkitRequestFullScreen) { // This is how to go into fullscreen mode in Chrome and Safari // Both of those browsers are based on the Webkit project, hence the same prefix. element.webkitRequestFullScreen(); } // Hooray, now we're in fullscreen mode! } </script>
HTML
<body id="contento"> Hello <button onclick="goFullscreen('contento'); return false"> Click Me To Go Fullscreen! (For real) </button>
-14890984 0 I would recommend you to use
editoptions: { maxlength: 8}
instead of the custom validation which you use. In the case the input element will be created with the maxlength attribute directly. So the user will not able to type more as characters as specified by maxlength
.
UPDATED: You can't change the interface of any callback function, but you can do share common code of different custom_func
in the following way. You define your custom validation function having three parameters like
function validLen (value, colName, valueLength) { if (value.length === valueLength) { return [true, ""]; } else { return [false, "fail"]; } }
and use it in the following way
{ name: 'cntrct_id', editrules: { custom: true, custom_func: function (value, colName) { return validLen(value, colName, 8); } }
If you need to use this
inside of custom_func
then you can change return validLen(value, colName, 8);
to return validLen.call(this, value, colName, 8);
.
For some reason I get a javascript on the following code:
var teamOne = ""; var teamTwo = ""; var children = $(this).find(".team-url"); if (children.length === 2) { teamOne = children[0].val(); teamTwo = children[1].val(); } alert(teamOne + " - " + teamTwo);
The error is on .val()
The code finds 2 elements and then it can't take the value. If I remove .val()
I get it saying it is an [Object HTMLInputElement]
The error is
Uncaught TypeError: children[0].val is not a function
Note:
I Know that I can get this code to work by doing the following:
var teamOne = ""; var teamTwo = ""; var children = $(this).find(".team-url"); if (children.length === 2) { teamOne = children.first().val(); teamTwo = children.last().val(); } alert(teamOne + " - " + teamTwo);
However, I am trying to understand why my first version doesn't work so that I can have a better understanding of these functions.
EDIT:
HTML
<div class="col-md-12 game" style="margin-top: 10px"> <div class="team-details">Team Saturn <input type="hidden" class="team-url" value="TeamSaturn"> </div> <div class="team-details">Team Datarnan <input type="hidden" class="team-url" value="TeamDatarnan"> </div> </div>
-15520299 0 You can have multiple http inbound-endpoints with the same hostname and port, but different paths. Here's a simple example I tested:
<flow name="Flow" doc:name="EchoFlow"> <http:inbound-endpoint exchange-pattern="request-response" host="localhost" port="8084" path="services/hello" /> <cxf:jaxws-service port="80" serviceClass="mypackage.ServiceInterface" /> <component class="mypackage.ServiceClass" /> </flow> <flow name="Flow2" doc:name="EchoFlow2"> <http:inbound-endpoint exchange-pattern="request-response" host="localhost" port="8084" path="services/goodbye" /> <cxf:jaxws-service port="80" serviceClass="mypackage.ServiceInterfaceTwo" /> <component class="mypackage.ServiceClassTwo" /> </flow>
Here we're hosting two web services; both endpoint URLs start
http://localhost:8084/services/
but have different endings (hello and goodbye). The ServiceInterface class looks like this:
package mypackage; import javax.jws.WebMethod; import javax.jws.WebService; @WebService public interface ServiceInterface { @WebMethod String sayHello(String name); }
And the ServiceClass looks like this:
package mypackage; import javax.jws.WebService; @WebService(endpointInterface = "mypackage.ServiceInterface") public class ServiceClass implements ServiceInterface { public String sayHello(String name) { return "Hello "+name; } }
ServiceInterfaceTwo and ServiceClassTwo are the same, but instead of sayHello() it has sayGoodbye().
-20376993 0 Linux Websocket protocol version 8 vs 13I have strange problem with websocket application in flash and Java server on jetty. From some moment client have started to open connection with version 8, but server supports only 13 version.
I really does not catch what is the problem and where is the source of this problem.
-30727418 0if personnel_id!='' mean NOT NULL use personnel_id IS NOT NULL instead and having use numberpid > 1 so query after edited below
SELECT COUNT(DISTINCT personnel_id) AS numberpid FROM planning WHERE personnel_id IS NOT NULL GROUP BY personnel_id HAVING numberpid > 1
-37299924 0 Send email with Twisted on Python3 I see several examples here about sending email with Twisted. However, I've read that twisted-mail isn't going to be ported on Python 3.
Has Twisted got any alternative in Python3 or manipulation with e-mail is away?
I manually added the GLKit framework in build phases settings. (Interesting question though - why didn't the app require it when no C++ source was involved -- how could it possibly compile and run?)
-358287 0I just went through this myself.
My number one tip is to not try and change everything on day one. You need friends if you really want to be able to fix this thing. You need your colleagues respect before you suggest how to change everything they've been working on for months (years?).
First, get the code under version control as soon as possible. If that's not going to be easy for you, at least start making daily backups, even if it means just zipping up the files and naming the zip file with the date. If nobody there knows about version control, buy a Pragmatic Programmer's book on CVS or SVN, and set it up yourself. The books can be read in a day, and you can be up and running quickly. If nobody else wants to use version control, you can use it yourself... then when somebody loses a file you can save the day with a copy from your repo. Sooner or later the others will see the wisdom that is version control.
Second, dive into the code as hard as you possibly can. Live it and breathe it for a month. Show the people who are there that you are going to learn their code.
Third, as you go through the code, take copious notes. Write down every thing that bothers you about the code. Just get your thoughts on paper. You can organize it later, after Month One.
Fourth, install a code profiler (such as xdebug). That'll tell you what files & functions are being called on each page, and how long each piece of code takes to run. You can use this to figure out your includes issues, and find slow bits of code. Optimize those first.
After your month of hard work, sifting through the code, and taking notes, turn your notes into a proper document. The different sections could range from security, to caching, to architecture, to whatever else is bothering you. For every criticism you make, offer a better solution, and an estimate on how long it would take to fix. This is where you get rid of all the competing javascript frameworks etc.
Revise this document as much as possible. I cannot stress that enough.
Make sure your audience can tell you're doing it for the good of the company, not just your personal preferences.
Present it to your boss, in person. Set-up a time to discuss it.
They could fire you for having written it. If they do, you're better off without them, because they don't want to improve, and your career will stagnate.
They might want to implement all of your recommendations. It's not likely, but it is possible. Then you'd be happy (unless your recommendations fail).
Most likely they'll want to implement a few of your recommendations, and that's better than nothing. At the very least, it'll help ease your concerns.
As for testing, setup another "virtual host" in Apache (supported on both Windows & Linux). Virtual Hosts let you run multiple sites on a single server. Most larger sites have at least 3 virtual hosts (or actual servers): dev.domain.com (for daily development), staging.domain.com (for QA people to do testing on just before a release), and www.domain.com (your production server). You should also setup dev, staging, and production versions of the database, with different logins & passwords so you don't accidentally confuse them.
An alternate solution would be to give each developer their own virtual host on the Linux server, and they can work via FTP/SCP or network share using samba.
Good luck!
-28475663 0If you run your application in debug mode you can find it by this path:
"%PARTITION%:\\...PATH TO YOUR APP...\bin\Debug\\...
-19524400 0 network sync a looping gstreamer videos I am trying to frame sync two looping videos over a lan. Both videos have the same length but the resolution might differ. The following code works already for the first run:
As soon as the video reaches GST_MESSAGE_EOS it starts over which is fine. But the client however will keep on reaching EOS all the time. I think this is because the servers clock is already past the clients video length.
How can I fix this. Can I somehow reset the servers base time on EOS? And if so how?
-28351953 0 Deploy Laravel on 1&1 ServersI have recently completed my first laravel site, but now I am stuck with deployment. This is an entirely new concept for me. My webspace is supplied by 1&1.
I have attempted several tutorials, but none seem to work. Based on the tutorial here at: Uploading Laravel Project onto Web Server
I structured my server folders like so:
(note when first FTPing my server, there was no www or html_docs, only a logs folder).
In the www, my index.php was altered to:
require __DIR__.'/../laravel/bootstrap/autoload.php'; $app = require_once __DIR__.'/../laravel/bootstrap/start.php';
In the laravel/bootstrap/paths.php file I altered:
'public' => __DIR__.'/../../www',
When visiting my domain in a browser, for example: myDomain.co.uk - the site is redirected to a "placeholder" (named /defaultsite) page for 1&1 domains and states "This domain name has just been registered."
If I append /www/index.php for example, I get file does not exist, even though the file is residing in my structure above.
As you probably noticed I am very new to server side aspects such as FTPing ect. I have read a few tuts, and all seem to take a different approach, leaving me confused to the best method. I am not sure where to go from here, so any advice is appreciated. Thank you.
Edit: I think I actually got it working, but now when I go to domain.com/public I get what I think is a DB error:
SQLSTATE[HY000] [2002] No such file or directory.
Any Advice please?
-24547164 0Assuming that the menu screen has sky and ground (i.e. that stuff isn't part of the game), then so far so good. Looks like you have the actors in separate classes, which is good. "MenuScreen" is the sort of thing that would make sense as a single responsibility.
-26057790 0 Redis key not removed even after Resque job completes successfullyHere is my scenario, i'm using resque to queue a job in redis, the usual way its done in ROR. The format of my key looks something like this (as per my namespace convention)
"resque:lock:Jobs::XYZ::SomeCreator-{:my_ids=>[101]}"
The job runs successfully to completition. But the key still exists in redis. For a certain flow, i need to queue and execute the job again for the same parameters (the key will essentially be same). But seems like the job does not get queued.
My guess is that since the key already exists in Redis, it does not queue the job again.
Questions:
Is this behavior of resque normal (not removing the key after successful completition)?
If Yes, how should i tackle this scenario (as per best practices)?
If No, can you help me understand what is going wrong?
-18424249 0Assuming you have some unique index on the table, this works great:
book = Book.first Book.delete_all(book.attributes)
If you don't have a unique index on the table, the above is dangerous - you could nuke more rows than anticipated. If that is the case, either add a unique index on an existing column (or columns) or else add a PK to the table.
-21031885 0 Require Client Certificate in IIS 7.5 IssueI have Windows Server 2008 r2 and IIS 7.5. I generated self signed server certificate and bind it to my "test" website. also, i have checked for the Required Client Certificate.
When i run the application on the same server it is prompting to select the client cert.
When i run it from other machine in the network it is not prompting to select it. i am using IE 10.
I gone through the different post but not able to resolve it.
Please help me.
-33389805 0 How to avoid lots of if-else in javascript (nodejs)Based on a parameter, function should select a json file out of more 100 json and fire a query to other system.
There will lots of query around in hundreds.
Obviously if else and switch won't be manageable. I took a look for strategy patten in the javascript.
var queryCode = req.param('queryCode'); if(queryCode == 'x'){ //do something } else if( queryCode == 'y'){ //do something } else if( queryCode == 'z') { //do something }
// do something
might become large sometimes...
so I want to replace it something like strategy pattern. Which will be the best design. Thanks in advance for any suggestion for this problem.
I've just run into a tricky issue. The following code is supposed to split words into chunks of length numOfChar
. The function calls itself, which makes it impossible to have the resulting list (res
) inside the function. But if I keep it outside as a global variable, then every subsequent call of the function with different input values leads to a wrong result because res
doesn't get cleared.
Can anyone help me out?
Here's the code (in case you are interested, this is problem 7-23 from PySchools.com):
res = [] def splitWord(word, numOfChar): if len(word) > 0: res.append(word[:numOfChar]) splitWord(word[numOfChar:], numOfChar) return res print splitWord('google', 2) print splitWord('google', 3) print splitWord('apple', 1) print splitWord('apple', 4)
-17801689 0 I believe there are three different concepts: initializing the variable, the location of the variable in memory, the time the variable is initialized.
When a variable is allocated in memory, typical processors leave the memory untouched, so the variable will have the same value that somebody else stored earlier. For security, some compilers add the extra code to initialize all variables they allocate to zero. I think this is what you mean by "Zero Initialization". It happens when you say:
int i; // not all compilers set this to zero
However if you say to the compiler:
int i = 10;
then the compiler instructs the processor to put 10 in the memory rather than leaving it with old values or setting it to zero. I think this is what you mean by "Static Initialization".
Finally, you could say this:
int i; ... ... i = 11;
then the processor "zero initializes" (or leaves the old value) when executing int i;
then when it reaches the line i = 11
it "dynamically initializes" the variable to 11 (which can happen very long after the first initialization.
There are: stack-based variables (sometimes called static variables), and memory-heap variables (sometimes called dynamic variables).
Variables can be created in the stack segment using this:
int i;
or the memory heap like this:
int *i = new int;
The difference is that the stack segment variable is lost after exiting the function call, while memory-heap variables are left until you say delete i;
. You can read an Assembly-language book to understand the difference better.
A stack-segment variable is "zero-initialized" or statically-initialized" when you enter the function call they are defined within.
A memory-heap variable is "zero-initialized" or statically-initialized" when it is first created by the new
operator.
You can think about static int i;
as a global variable with a scope limited to the function it is defined in. I think the confusion about static int i;
comes because static hear mean another thing (it is not destroyed when you exit the routine, so it retains its value). I am not sure, but I think the trick used for static int i;
is to put it in the stack of main()
which means it is not destroyed until you exit the whole program (so it retains the first initialization), or it could be that it is stored in the data segment of the application.
I have this code in client side:
fileUpload: function monkey(){ var file = t.gI("photoFile"); //get element by photoFile var formData = new FormData(); console.log(file.files.length); formData.append("upload", file.files[0]); var req = t.gR(); //XMLHTTPRequest req.open('POST', 'php/fileupload.php', true); req.setRequestHeader("Content-Type", "multipart/form-data", true); req.send(formData); req.onreadystatechange = function () { if (req.readyState === 4) { if (req.status == 200 && req.status < 300) { t.gI("eventBox").innerHTML = req.responseText; //eventbox error handler adminHandler.eventBox(); } } } },
And this in server side:
<?php header('Content-Type:multipart/form-data'); echo $_FILES['upload']['tmp_name']; ?>
And I got this error msg:
[15-Jun-2015 12:03:21 UTC] PHP Warning: Missing boundary in multipart/form-data POST data in Unknown on line 0 [15-Jun-2015 12:03:21 UTC] PHP Notice: Undefined index: upload in /home/webprogb/public_html/php/fileupload.php on line 4
What can I do to fix it?
-4663649 0if it's only calculating pairs of 2 (and no higher), you can simply count the other two arrays.
for anyone in array1, simply count(array2) + count(array3) = number of pairs
Maybe a possibility for you is to cache your data as real PHP. The function var_export
provides you with the PHP representation of data. It has some limitation, which serialize
does not have when it comes to circular references, but on the other hand it is way easier to understand, because you already know the syntax.
The code you gave was almost there. I needed the same thing for my code. I added information to the cookie (last time modified) and compare that to the current time. If there is enough space in between (in this case 1 second) then modify the cookie info. This works even if you have 15 tabs open.
I took out the check for whether they have cookies turned on.
$(function(){ resetCookies(); setTimeout(checkTime, 1000); }); function resetCookies(){ setCookie("loginTime",'10',1); } function checkTime() { var arrloginTime=getCookie("loginTime").split("--"); var loginTime=arrloginTime[0]; var dtmLastMod=new Date(arrloginTime[1]); console.log(loginTime); if (loginTime!=null && loginTime!=""){ var dtmNow = new Date(); if ((dtmNow.getTime() - dtmLastMod.getTime()) >= 1000){ var newTime=loginTime-1; if(newTime==0){ autoLogout(); return false;} setCookie("loginTime",newTime,1); } }else{ autoLogout(); return false;} setTimeout(checkTime, 1000); } function setCookie(c_name,value,exdays){ var exdate=new Date(); var dtmLastMod = new Date(); exdate.setDate(exdate.getDate() + exdays); var c_value=escape(value) + "--" + dtmLastMod + ((exdays==null) ? "" : "; expires="+exdate.toUTCString()); document.cookie=c_name + "=" + c_value; } function getCookie(c_name){ var i,x,y,ARRcookies=document.cookie.split(";"); for (i=0;i<ARRcookies.length;i++){ x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("=")); y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1); x=x.replace(/^\s+|\s+$/g,""); if (x==c_name){ return unescape(y); } } } function autoLogout(){ console.log('You have been logged out of this document due to inactivity.'); }
-33177719 0 What happens with replace method of a String? We know that the String object is immutable. But replace method is actually changing its state.
So what is happening in this case?
-33730402 0Optimized
if ($buyoption != 'With Validation' && $buyoption != "No Validation") { $buyoptionError = "Please select a buy option"; echo "$buyoptionError <br>"; $YesorNo = 0; }
-20850730 0 The input parameter is a string array which was stored in char*, when you get arg[1], it just return the string array (char*), if you ouput it, the whole string will be ouput. But if you convert it ot string, it just convert the memory address of the paramter to int, so you will just see the address result.
-37281898 0 Why does phpmyadmin act different in uppercase query?When using phpMyAdmin Ver. 4.0.10deb1, there is a table with a column named 'ID', which is a primary key. When I run the query "SELECT id FROM table
" I get the error;
This table does not contain a unique column. Grid edit, checkbox, Edit, Copy and Delete features are not available.
But if I run "SELECT ID FROM table
" it works fine. I don't understand.
I need some tip on tuning some TSQL to execute faster, it's taking way too long although it works. This may be because I'm fetching a key from another table before I can do the insert, any ideas anyone?
DECLARE db_cursorReads CURSOR FOR SELECT [MeterId] ,[MeterRead] FROM MdsReadsImports; declare @PremiseMeterId int; declare @MeterId nvarchar(24); declare @MeterRead int; OPEN db_cursorReads; FETCH NEXT FROM db_cursorReads INTO @MeterId ,@MeterRead; WHILE @@FETCH_STATUS = 0 BEGIN set @PremiseMeterId = (select top 1 PremiseMeterId from PremiseMeters where MeterId = @MeterId) insert into PremiseMeterReads (MeterRead,PremiseMeterId) values (@MeterRead, @MPremiseMeterId) FETCH NEXT FROM db_cursorReads INTO @MeterId ,@MeterRead; END; CLOSE db_cursorReads; DEALLOCATE db_cursorReads;
-25296714 0 the Constractor must get Context
try using getApplicationContext()
or pass Context
to this Class
You are hiding your adMobBannerView
in your displayiAdsOrNot
function. This function is called every time the viewWillAppear
. Remove this and you should get the results you desire.
As for the rest of your code, you have a lot going on here. First, to simplify things you should move all of your code that is creating and laying out your adBanner
and adMobBannerView
under viewWillAppear
when [[NSUserDefaults standardUserDefaults] boolForKey:@"IAPSuccessful"]
is false, and set both banners .hidden = YES
automatically. This will eliminate the need for your displayiAdsOrNot
and displayAdMobBannerOrNot
where you are repeating a lot of the same if
statements checking for IAP and which device the user is using. After doing this, in your delegate methods you can simply hide or show the correct banner depending on if iAd fails or not now. For example, iAd loads so set its hidden value to NO
and AdMob’s to YES
, and vice versa if iAd fails to load an ad. I’m sure you were checking the IAP every time in case the user purchased it while in the current session so you could remove the ads. An easier solution would be to move the ads outside of the screen bounds on completion of the IAP and then on the next launch of your application simply do not create either banner at all if [[NSUserDefaults standardUserDefaults] boolForKey:@"IAPSuccessful"]
is true. A few other things to point out are, you should remove your request.testDevices
AdMob request before submitting your application, and it seems you are defining your NSLayoutConstraint *myConstraint
multiple times. I’m not exactly sure what you’re trying to do here. Also, in didFailToReceiveAdWithError
you have self.adBanner.hidden = true
, it should be self.adBanner.hidden = YES
.
Are you using models? Code igniter doesn't enforce this, but using models in addition to controllers and views is a good way to have a shorter controller function. Alternatively, you could place some of the functions in your own helper, then import it.
And if you want to set some default values for the entire constructor, you can use the class constructor. This is outlined here:
http://codeigniter.com/user_guide/general/controllers.html#constructors
-202460 0Full text search in SQL Server is really easy, a bit of configuration and a slight tweak on the queryside and you are good to go! I have done it for clients in under 20 minutes before, being familiar with the process
Here is the 2008 MSDN article, links go out to the 2005 versions from there
-24586080 0You could implement an API
http://railscasts.com/episodes/348-the-rails-api-gem
the idea to send data RESTfully as JSON or XML then parse that the using javascript (jquery,angular,etc..) to display it as HTML
This main challenge in creating an API is authentication. You take a look at Oauth and Doorkeeper gem for rails
-34742550 0You can now do this with JSONModel
.
Assume we have the following model:
@class MyModel @property (strong, nonatomic) NSString *name; @property (strong, nonatomic) NSArray *products; @end
If the complete JSON doc looks like this:
{ "productType1": { "name": "foo", "products": [] }, "productType2": { "name": "foo", "products": [] }, "productType3": { "name": "foo", "products": [] } }
then you should use one of the [MyModel dictionaryOfModelsFrom...];
methods.
If it looks like this:
{ "productTypes": { "productType1": { "name": "foo", "products": [] }, "productType2": { "name": "foo", "products": [] }, "productType3": { "name": "foo", "products": [] } } }
Then you should use another model like this:
@class MyModelContainer @property (strong, nonatomic) NSDictionary <MyModel> *productTypes; @end
-31453817 0 Getting first image from content in silverstripe I have the following method where it is suppose to get the first image that is displayed from the content.
public function FirstImage($content) { $dom = new DOMDocument(); $dom->loadHTML($content); Debug::dump($content); }
The wierd thing is when i do $dom->loadHTML I get the following error Empty string supplied as input
, but as soon as I dump it I do get the correct data. How can I fix this problem ?
I also done $this->owner->Content which has the same thing.
-27622207 0Use agrep
function.
Initial data:
x <- c("Company A Pty.","BigData GMBH","Company A Pty. Ltd.","Red Pants Warsaw", "Company A Georgia", "Red Pants Ltd", "BlueSocks House")
first argument is pattern that you want to look in data (eg x[1]), second is where you want to look, max
is the max distance two strings can differ. value
means that we want to obtain strings instead of indexes of vector.
If there is no match, you can change max
, but be careful! More is not always better.
agrep(x[1],x, max=0.1, value=TRUE) ## [1] "Company A Pty." "Company A Pty. Ltd." agrep(x[1],x, max=0.3, value=TRUE) ## [1] "Company A Pty." "Company A Pty. Ltd." "Company A Georgia" agrep(x[1],x, max=0.7, value=TRUE) ## [1] "Company A Pty." "Company A Pty. Ltd." "Company A Georgia" "Red Pants Ltd"
What's more, this is not symetrical. "Red Pants Warsaw" (x[4]) was not matched to "Red Pants Ltd" (x[6]) but it worked other way - x[6] was matched to x[4]. Be aware of this.
agrep(x[4],x, max=0.2, value=TRUE) ## [1] "Red Pants Warsaw" agrep(x[6],x, max=0.2, value=TRUE) ## [1] "Red Pants Warsaw" "Red Pants Ltd"
-3575665 0 $('.class:nth-child(odd)')...;
http://api.jquery.com/nth-child-selector/
-39054313 0You have this:
"click": "function(){console.log(1); }"
Should be like this
"click": function() { console.log(1); }
-36391917 0 Try this:
In survey flow:
human = 0
Question html:
<a href="http://vpf2.cise.ufl.edu/Classic/Interaction/Prototype/22318?username=" id="human" target="_blank">Click here</a>
JavaScript:
Qualtrics.SurveyEngine.addOnload(function() { $('human').observe('click',function(event) { Qualtrics.SurveyEngine.setEmbeddedData("human", "1"); }); });
Note: In Qualtrics $ refers to prototypejs, not jquery.
-40577676 0That’s how I usually annotate my test classes:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { JPAUnitTestConfiguration.class }) @Transactional //rollback if exception occurs during test method @TransactionConfiguration(defaultRollback = true) //rollback at end of method @DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD) public class FooBarTest { }
Add @TransactionConfiguration(defaultRollback = true) to your test class.
My transaction configuration:
import java.sql.SQLException; import javax.sql.DataSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.FilterType; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; import org.springframework.transaction.annotation.EnableTransactionManagement; import ch.ams.pois.repository.AuthTokenRepository; import ch.ams.pois.repository.GroupRepository; import ch.ams.pois.repository.InvitationRepository; import ch.ams.pois.repository.LocationRepository; import ch.ams.pois.repository.UserRepository; @Configuration @EnableTransactionManagement @EnableJpaRepositories(basePackages = JPAConfiguration.JPA_REPOSITORIES_BASE_PACKAGES, includeFilters = @ComponentScan.Filter(value = { UserRepository.class, LocationRepository.class, GroupRepository.class, AuthTokenRepository.class, InvitationRepository.class }, type = FilterType.ASSIGNABLE_TYPE)) public class JPAUnitTestConfiguration extends JPAConfiguration { @Bean public DataSource dataSource() throws SQLException { EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); return builder.setType(EmbeddedDatabaseType.H2).build(); } }
The dependencies for the persistence layer:
<dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-jpa</artifactId> <version>1.3.4.RELEASE</version> </dependency> <dependency> <groupId>org.hibernate.javax.persistence</groupId> <artifactId>hibernate-jpa-2.0-api</artifactId> <version>1.0.1.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>4.0.1.Final</version> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <version>1.3.173</version> </dependency> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <version>9.2-1003-jdbc4</version> </dependency>
-5579426 0 Mandatory and Non mandatory in non identifying relationships With reference to the last part of answer given here: What's the difference between identifying and non-identifying relationships?
A non-identifying relationship can be optional or mandatory, which means the foreign key column allows NULL or disallows NULL, respectively.
I am creating a non-identifying relationship in MySQL Workbench and whether I keep foreign key column MANDATORY or NON-MANDATORY, has no effect. Even if it is NON-MANDATORY I can't enter NULL values in it. I have to explicitly choose that particular foreign key as allowing NULL and only then I am able to store NULL values.
So I want to ask if this is the correct behaviour or this is a problem with MySQL Workbench or MySQL?
Thanks
-10893435 0import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; public class MainActivity extends Activity { /** Called when the activity is first created. */ Button btnTakePhoto; ImageView imgTakenPhoto; private static final int CAM_REQUREST = 0; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); btnTakePhoto = (Button) findViewById(R.id.button1); imgTakenPhoto = (ImageView) findViewById(R.id.imageView1); btnTakePhoto.setOnClickListener(new btnTakePhotoClicker()); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub super.onActivityResult(requestCode, resultCode, data); if (requestCode == CAMERA_PIC_REQUEST) { Bitmap thumbnail = (Bitmap) data.getExtras().get("data"); imgTakenPhoto.setImageBitmap(thumbnail); } } class btnTakePhotoClicker implements Button.OnClickListener { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST); } } }
-18328360 0 Random numbers have certain special properties. Computer memory in general doesn't satisfy those properties.
If I sampled computer memory, tons of it would be quite similar, and certain numbers would have such a low probability of existing, that they might not even be found within the entire memory of a computer.
That's not to mention that if I read a bit of memory that's outside of the memory allocated to a program, the OS will kill me dead with a SEGFAULT.
It's a bad idea, on many levels. Use a proper random number generator.
-34938709 0 Outlook 2010 HTML Display: Newsletter displays fine on one's computer, but not anotherMost of us in our office environment uses Outlook 2010 for our email needs. We'll eventually upgrade to higher versions of Office, but that may be sometime later.
I have worked with a vendor to create an internal email template, to be used by a colleague who is meant to just input text within the template and send it out. The odd part is the template works well on my computer, but not on the colleague's. The vendor has already optimized the template to be good for Outlook 2010.
On my colleague's computer, it seems like the template has added additional padding between the images or table cells. The email she'll eventually send out will have this additional padding as well.
Is there any settings I need to do on her Outlook 2010 settings?
NOTE: It's in HTML, and not saved as an Outlook Template yet.
-20395141 0Set e.Handled to true and then shutdown the application.
private void Application_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) { var exception = e.Exception; ShowErrorMessage(exception); if (string.CompareOrdinal(exception.Message, FP.Properties.Resources.GAConnectionErrorText) == 0 || ( !ReferenceEquals(exception.InnerException, null) && string.CompareOrdinal(exception.InnerException.Message, FP.Properties.Resources.GAConnectionErrorText) == 0)) { e.Handled = true; Application.Current.Shutdown(); } }
-32515075 0 Example 1:
loop { var x = anyobject do something with x }
create x and then release x each loop
Example 2:
var x = anyobject loop { do something with x }
x inside the loop has the same memory with x outside the loop. Doesn't create/release each loop or end of the loop
-34099585 0 Strange issues with Android AVD for API level 21 and upI recently updated Android Studio to version 1.5 from 1.02. I had been running mainly API level 19 emulators and everything was fine. Now I am trying to run emulators for Lollipop and Marshmallow. I spent over an hour trying various API levels, and here is what I am seeing.
These were all run on an AMD Phenom II processor running Ubuntu 14.04 (with KVM enabled):
however
Can anyone shed any light on what is going on here?
-22281179 0You got the entire logic correct, except one minor flaw. You have idxR
as a logical matrix. Hence colonies
is a logical matrix too. Therefore, you get the expected output till the second-last line. Problem occurs on the last line, when you try to assign an array of numbers in which each number is greater than 1 (colonies(colonies==1).*ret;
) to a logical matrix.
Elements greater than 1 are clipped to one and thus you see only zeros and ones. There is a simple workaround. Change the first line to
colonies = double(idxR);
P.S. The answer was right in front of you, you just didn't spot it. You had written:
I tried this code in a new file and assigned a matrix with random ones and zeros to idxR and then it seems to work.
The idxR
matrix must have been of double datatype, if you used randi
.
I need to get the profile picture of a channel in Telegram. According to this doc: https://core.telegram.org/bots/api
I first try to use getChat to get the basic information about a channel . Which I get successfully. It gives me a json like this:
{"ok":true,"result":{"id":-1001003587533,"title":"\u06a9\u0627\u0641","username":"kafiha","type":"channel"}}
After this I try to use 'getUserProfilePhotos' to get the profile photo. But I can't get it to work because it responds with error when I either pass the id I got from the last request or the channeld username (@channelName).
Do you know how can I accomplish this using Bot API for Telegram?
-7101741 0 C# .NET StreamWriter: How to skip lines when writing file using StreamWriter?I read in a text file using StreamReader. I want to write out this same text file EXCEPT its first 4 lines and its last 6 lines.
How do I do this? Thanks.
-15402703 0There are a couple of known fixes that have managed to sort this similar problem out.
The AVD does not have enough RAM. Try increasing the RAM of the AVD by editing it from the AVD Manager. Source: http://stackoverflow.com/a/9384040/450534
The AVD you are using may have been corrupted. The solution is to delete the current AVD and create new one with the same settings (if that is important to your apps functioning). Source: http://stackoverflow.com/a/2199621/450534
Had the same issue when attempting to use $watch for data binding.
At this time of writing, the current version of Angular New Router (v0.5.3) could not instantiate controller with $scope injected. The issue was logged on github.
According to a separate thread, there is an interim package on npm with the fix of this issue. Check out zVictor's post for instructions.
-31815894 0 I need a Hexadecimal Number ListI need a script that generates all 65536 Hexadecimal numbers from 0000 to FFFF and puts them in a text file like this:
0000 0001 0002 0003 ... FFFF
I don`t care what programming language it is written in, but please not one that I have to run a web server (PHP) or that is Windows only.
-7729259 0 Android: How to download file and show notification with progressbar?I have an activity that downloads a file from the web when a button is clicked. The downloading of the file is done via an inner AsyncTask. The download works, I can even show, update, and hide a progressbar widget in the the Activitys layout.xml using the AsyncTask. I can also, show a notification from this AsyncTask. I Cannot however, update the progressbar inside the notification from the AsyncTask. I get a Force Close as soon as the first update is processed. Will supply my code if needed!
Thanks for your time
InvocationTargetException.<init>(Throwable) line: 50 Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method] Method.invoke(Object, Object...) line: 507 ZygoteInit$MethodAndArgsCaller.run() line: 845 ZygoteInit.main(String[]) line: 603 NativeStart.main(String[]) line: not available [native method]
This is thrown to this line
myContentView.setProgressBar(R.id.status_progress, 100, Integer.parseInt(progress[0]), false);
Here is my code
protected String doInBackground(String... aurl) { int count; try { URL url = new URL(aurl[0]); String path = url.getPath(); String filename = new File(path).getName(); Environment.getExternalStorageDirectory(); File tm = new File("/sdcard/Transform Mii/"); tm.mkdirs(); File out = new File(tm, filename); URLConnection conexion = url.openConnection(); conexion.connect(); int lenghtOfFile = conexion.getContentLength(); Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile); InputStream input = new BufferedInputStream(url.openStream()); OutputStream output = new FileOutputStream(out); byte data[] = new byte[1024]; long total = 0; while ((count = input.read(data)) != -1) { total += count; publishProgress(""+(int)((total*100)/lenghtOfFile)); output.write(data, 0, count); } output.flush(); output.close(); input.close(); } catch (Exception e) {} return null; } protected void onProgressUpdate(String... progress) { progressbar.setProgress(Integer.parseInt(progress[0])); myContentView.setProgressBar(R.id.status_progress, 100, Integer.parseInt(progress[0]), false); notificationManager.notify(NOTIF_ID, notification); }
progressbar is the bar that is in the activity's layout.xml, this updates normally
myContentView progressbar is the bar that is inside the notification
-22213313 0 Perl - is "uc" enable to use when return to a variable?Just a simple question I want to ask. I am beginner for Perl script, sorry if you feel this question is stupid.
The question is can I return a variable and apply "uc" when return.
Here is the code:
my $desc = ""; @names = ("thor-12345-4567"); $size = @names; Thor(); print $desc; sub Thor() { if ($size ne "0") { return uc ($desc=$names[0]); } $desc = "NA"; return $desc; }
I just want to know that is "uc" can be use when we return to a variable?
When I try to print $desc, it did not return to uppercase.
Thank you very much!
-8389545 0Your problem is not occuring at the GROUP BY level, but rather in the JOIN. The rows with a NULL qualifier cannot be JOINed and, because you're using INNER JOIN, they fall out of the result set.
Use LEFT OUTER JOIN to see all the rows.
-33449354 0 eclipse gets stuck while running xdebugI'm having a problem making breakpoints with eclipse and xdebug in centos. I mark a breakpoint, and it is simply ignored. The script runs without stopping.
it seems that eclipse gets stuck on 78% mark on the progress bar. waiting to have a response from xdebug.
here are the xdebug settings:
xdebug xdebug support enabled Version 2.2.7 IDE Key ECLIPSE_DBGP Supported protocols Revision DBGp - Common DeBuGger Protocol $Revision: 1.145 $ Directive Local Value Master Value xdebug.auto_trace Off Off xdebug.cli_color 0 0 xdebug.collect_assignments Off Off xdebug.collect_includes On On xdebug.collect_params 0 0 xdebug.collect_return Off Off xdebug.collect_vars Off Off xdebug.coverage_enable On On xdebug.default_enable On On xdebug.dump.COOKIE no value no value xdebug.dump.ENV no value no value xdebug.dump.FILES no value no value xdebug.dump.GET no value no value xdebug.dump.POST no value no value xdebug.dump.REQUEST no value no value xdebug.dump.SERVER no value no value xdebug.dump.SESSION no value no value xdebug.dump_globals On On xdebug.dump_once On On xdebug.dump_undefined Off Off xdebug.extended_info On On xdebug.file_link_format no value no value xdebug.idekey ECLIPSE_DBGP ECLIPSE_DBGP xdebug.max_nesting_level 100 100 xdebug.overload_var_dump On On xdebug.profiler_aggregate Off Off xdebug.profiler_append Off Off xdebug.profiler_enable Off Off xdebug.profiler_enable_trigger Off Off xdebug.profiler_output_dir /tmp /tmp xdebug.profiler_output_name cachegrind.out.%p cachegrind.out.%p xdebug.remote_autostart On On xdebug.remote_connect_back On On xdebug.remote_cookie_expire_time 3600 3600 xdebug.remote_enable On On xdebug.remote_handler dbgp dbgp xdebug.remote_host 77.127.241.252 77.127.241.252 xdebug.remote_log /log.txt /log.txt xdebug.remote_mode req req xdebug.remote_port 1002 1002 xdebug.scream Off Off xdebug.show_exception_trace Off Off xdebug.show_local_vars Off Off xdebug.show_mem_delta Off Off xdebug.trace_enable_trigger Off Off xdebug.trace_format 0 0 xdebug.trace_options 0 0 xdebug.trace_output_dir /tmp /tmp xdebug.trace_output_name trace.%c trace.%c xdebug.var_display_max_children 128 128 xdebug.var_display_max_data 512 512 xdebug.var_display_max_depth 3 3
can anyone help?
-9323906 0 how to substitute underscore of a string in hamlI use rails_admin
One of my partial is like this :
%b= questionnaire.title - CSV.parse(questionnaire.content, :headers => true, :col_sep => ",") do |row| - row.to_hash.each do |key, value| = succeed value do %b= key + " : "
but key is sometimes like this "I_dont_want_underscore"
I tried this :
%b= questionnaire.title - CSV.parse(questionnaire.content, :headers => true, :col_sep => ",") do |row| - row.to_hash.each do |key, value| = succeed value do %b= key.gsub!-'_',' ') + " : "
but then I've got this error showing : Can't convert frozen string (or something like this) Then I tried to duplicate
%b= questionnaire.title - CSV.parse(questionnaire.content, :headers => true, :col_sep => ",") do |row| - row.to_hash.each do |key, value| = succeed value do %b= key.dup.gsub!-'_',' ') + " : "
But then server does not respond anymore...how come ? finally I tried to put a def in my application_helper.rb
def sub_underscore self.dup.gsub!-'_',' ') end
and
%b= questionnaire.title - CSV.parse(questionnaire.content, :headers => true, :col_sep => ",") do |row| - row.to_hash.each do |key, value| = succeed value do %b= key.sub_underscore + " : "
But I get this error : "no method sub_underscore for this string"
Any ideas ?
-6873677 0 how to avoid refreshing a div. if the div has been used?i have a div inside a iframe. It will be refreshing very 10 seconds. the div place holder has 4 text boxes controls. if any of the textbox is used then i want to not to refresh the div.
-39853751 0 RegExp method "test" return wrong resultAcoording to https://regex101.com/ regexp '^[-+]?[0-9]*\.?[0-9]$'
for strings like "g2", "a8" etc. (one digit preceded by one letter) should return "false" (no match), but if I use it in JavaScript using RegExp
test
method "true" is returned. What is the reason of that behaviour?
<!DOCTYPE html> <html> <body> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> function myFunction() { var str = "g2"; var patt = new RegExp('^[-+]?[0-9]*\.?[0-9]$'); var res = patt.test(str); document.getElementById("demo").innerHTML = res; } </script> </body> </html>
I have a huge problem. I have 2 Flyway's services, each service connects to different schema, and a mysql Service. The .yml file looks like:
version: '2' services: mysqldb: image: mysql:5.6.26 environment: MYSQL_USER: mialquileruser MYSQL_PASSWORD: password MYSQL_ROOT_PASSWORD: password MYSQL_DATABASE: mialquiler ports: - "3306:3306" flyway-service-i: image: mialk/flyway-service volumes: - "../resources/db/migration:/migrations/ro" depends_on: - mysqldb links: - mysqldb command: migrate -url=jdbc:mysql://mysqldb:3306/mialquiler -user=mialquileruser -password=password -schemas=mialquiler -baselineOnMigrate=true -locations='filesystem:/migrations' flyway-post-i: image: mialk/flyway-post-service volumes: - "../../../../postService/src/main/resources/db/migration:/migrations/ro" depends_on: - mysqldb links: - mysqldb command: migrate -url=jdbc:mysql://mysqldb:3306/mialquiler -user=mialquileruser -password=password -schemas=mialquiler_post -baselineOnMigrate=true -locations='filesystem:/migrations'
flyway-service-i connects to mialquiler schema and flyway-post-i connects to mialquiler_post schema.
When I run the command sudo docker-compose up, the flyway-service-i is okey, but with flyway-post-i I get an error message of Unable to create schema mialquiler_post:
I don't understand why, because I've given grants to that schema to all the hosts:
But when I execute a SELECT of the grants of the user of the container, it only shows me one schema, mialquiler schema:
Why can't it create the mialquiler_post schema? What can I do?
This is not duplicate, this is a specific problem.
-11283037 0 apache poi evaluateall() unavailablei create a workbook and want to evaluate all formulas:
Workbook wbTemp = new HSSFWorkbook(inp); //do workbook stuff here wbTemp.getCreationHelper().createFormulaEvaluator().evaluateAll();
i get this error:
The method evaluateAll() is undefined for the type FormulaEvaluator
when it clearly says here that evaluateAll is an existing method. what might be causing this?
-19443541 0 javascript function with in function in variableI have a doubt
My Code :-
function f() { var g = function() { return 1; } return g; };
How do I can call g? I want to return 1 once and again I want to return g.
I did a Research I found a solution
How we can call g is:-
f()();
Why this is ?? What is f()();
in JavaScript. why not we can achieve this using f.g
or something.
How can I return g from the function f ??
Please clarify my doubts ?
-13357311 0Try
Object result = expr.evaluate(doc, XPathConstants.NODESET); // Cast the result to a DOM NodeList NodeList nodes = (NodeList) result; for (int i=0; i<nodes.getLength();i++){ System.out.println(nodes.item(i).getNodeValue()); }
-34436108 0 What's wrong with my solution of SearchInsert? puzzle:
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
And my code here:
public class Solution { public static int searchInsert(int[] nums, int target) { return searchInsert(nums, target, 0, nums.length-1); } private static int searchInsert(int[] nums, int target, int start, int end) { if(start <= end) { return target <= nums[start] ? start : (start+1); } int m = (start + end) / 2; if(nums[m] == target) { return m; } else if(nums[m] < target) { return searchInsert(nums, target, m+1, end); } else { return searchInsert(nums, target, start, m-1); } } public static void main(String[] args) { int[] nums = {1, 3}; System.out.print(searchInsert(nums, 4); } }
The result turns out like this:
Input:
[1,3]
4
Output:
1
Expected:
2
I've simulate the process of this input over and over again on paper, but just cannot figure out how my code could output 2
.
Please help me with this, thx in advance.
-15873610 0Use CSS media queries as follows. In your handlebars template:
<div class="show-ipad"> {{outlet "ipad-outlet1"}} {{outlet "ipad-outlet2"}} </div> <div class="show-iphone"> {{outlet "iphone-outlet1"}} {{outlet "iphone-outlet2"}} </div>
In your stylesheet (media-queries taken from this article):
/* iPads (portrait and landscape) ----------- */ @media only screen and (min-device-width : 768px) and (max-device-width : 1024px) { .show-iphone { display: none; } } /* Smartphones (portrait and landscape) ----------- */ @media only screen and (min-device-width : 320px) and (max-device-width : 480px) { .show-ipad { display: none; } }
Adapt the media-queries to your needs (targeting iPads in landscape, in portrait, etc.).
In Javascript don't assume anything about the client device. Just render all outlets for all devices, and let the CSS media-query handle what is shown and what is hidden.
-31273046 0 When modifying a theme in wordpress, when i want to remove theme content is it better to remove CSS or PHP or BOTHI am doing my website, with studiopress genesis framework and their theme child, now i want to remove some unneccesary header content. So I know which code to remove from CSS and which from PHP, is it enought if I only remove CSS and leave PHP, and vice versa, or do I need to remove them both?
Thank you on help!
-31575692 0You are going to want to change the settings in your plist for the app transport security. Do this in watch extension plist if you are doing the network call on the watch. Here is a helpful link
Also for your url you are going to need to use either http:// or https:// in order for this to work.
-19365733 0 X86 encode near call relative offsetLet's say I've the following set of instructions:
00E79E00 | E8 AE580000 CALL someprocess.00E7F6B3 00E79E05 | 85C0 TEST EAX, EAX (output taken from OllyDbg)
How do I encode the rel32 offset from the near call(0xE8) so I can get the absolute position I can jump to?
I know that the offset is relative to the next instruction and is calculated by subtracting the target with it. My question is: how do I 'reverse' this so I get the function addres 00E7F6B3
from the relative offset AE580000
I've been searching for this for many hours but didn't find a way to make it.
I have a UITableView
whose UITableViewCells
use AutomaticDimension
for Height:
tableView.RowHeight = UITableView.AutomaticDimension; tableView.EstimatedRowHeight = 160f;
The problem is when I try to get tableView's ContentSize
. It seems to be calculated based on EstimatedRowHeight
instead of the current height of its rows. Suppose, if there are 10 Cells then ContentSize's returned value is 160x10.
Then my question is if there is a way to do this.
Any help will be really appreciated... I use Xamarin.iOS but Obj-C and Swift answers are obviously welcome :)
-24678934 0 Audio Playing Badly when OnlineI've created this game using Javascript, and I play all sounds (including effects and background music) using the Audio type. It works perfectly when I run the page from my computer, but after I uploaded on my host and tried to run from the web, it started to sounds really terrible: sometimes it is delayed, sometimes it does not play at all.
I've noticed that the main problem is related to playing the same audio more than once in a short amount of time: it plays a shooting sound whenever the user clicks on the page, so usually it isn't that bad when they're not spamming their mouse, but once you start clicking many times the sounds turns out terrible.
The audio file for that particular sound is very short, and when running from my computer is has no problem even when the user is clicking very fast. Here is what the function does:
function play(aux,volume){ if(volume == undefined) volume = 1; if(!sound){return;} aux.volume = globalVolume * aux.customVolume * volume; aux.load(); aux.play(); }
So, pretty much, what it does is loading and playing the sound again whenever that function is called. That was made so it would start again even if the the function is called while the sound was still going on.
Again, this whole things works smoothly when running from my computer, but from the web it just sucks.
Q: Does anyone knows how to fix this? Or does anyone know an alternative I could use to make it work?
Suggestions are welcome as well.
-19904512 0LESS might be a perfect solution. Convert the CSS to LESS by add a scope like this
#myId{ .ui-datepicker { ... /* width:auto; (in example) */ } }
Now convert it back via LESS2CSS to
#myId .ui-datepicker{ ... }
Regards.
-27861459 0Yes you need image responsive. I think instead of featured-work should be container instead
<div class="container"> <div class="row row-work"> <div class="col-md-6"> <img class="img-responsive" src="http://lorempixel.com/600/400/"> </div> <div class="col-md-6"> <img class="img-responsive" src="http://lorempixel.com/600/400/"> </div> </div> <div class="row row-work"> <div class="col-md-6"> <img class="img-responsive" src="http://lorempixel.com/600/400/"> </div> <div class="col-md-6"> <img class="img-responsive" src="http://lorempixel.com/600/400/"> </div> </div> </div> </div>
-9043390 0 Here is another question that is pretty similar to what you are asking: how to change color of facebook like button
And here is a reference guide for the Facebook Like button: https://developers.facebook.com/docs/reference/plugins/like/
Sounds like it's probably not possible to change the color of the Like button text, at present. But, you can change the color scheme between "light" or "dark" themes, according to the links above.
Search is your friend. :)
-21316140 0I think Stack might be not the best place for this, but custom data is available only on Premium accounts.
-851314 0 Selecting an entity doesn't subselect associated entitiesI'm learning ASP.NET MVC (and MVC in general) and all the help online I find only demonstrates using a single table, not relations between multiple tables. I'm running a query that I expect should also return associated entities, but it's not and can't figure out what I'm missing. I appreciate your help!
I have the following data:
Ticket TicketID CompanyID Subject ... -------- --------- ------- 1 1 "stuff" 2 1 "things" Company CompanyID Name ... --------- -------- 1 "FredCo"
So every ticket is linked to a specific company. I am trying to create a Details view for Tickets, and I want to display the company name. Here is what I have set up at the moment.
Model
A Ticket
entity and a Company
entity, and there is an association called CompanyTicket
between them. The navigational properties are Ticket.Company and Company.Tickets.
In the mapping details for the association, I have:
Maps to Ticket Company.CompanyID <-> CompanyID Ticket.TicketID <-> TicketID
Controller
My TicketController.Details method looks like this:
public ActionResult Details( int id ) { var tickettoview = ( from m in _db.Ticket where m.TicketID == id select m ).First(); return View( tickettoview ); }
Edit: After going through Mark Hamilton's suggestion, I realize the problem is my query. Putting a breakpoint on the return shows that tickettoview
never has Customer populated. So this narrows it down, but I'm still not sure how to populate the Company attribute.
Again, thank you!
-6303813 0I've got two approaches for you:
Firstly using Activator.CreateInstance
public static IEnumerable<TV> To<TU, TV>(this IEnumerable<TU> source) { return source.Select(m => (TV) Activator.CreateInstance(typeof(TV), m)); }
Secondly, you could use interfaces to define properties rather than use parameterized constructors:
public interface IRequiredMember {} public interface IHasNeccesaryMember { IRequiredMember Member { get; set; } } public static IEnumerable<TV> To<TU, TV>(this IEnumerable<TU> source) where TV : IHasNeccesaryMember, new() where TU : IRequiredMember { return source.Select(m => new TV{ Member = m }); }
The first method works but feels dirty and there is the risk of getting the constructor call wrong, particularly as the method is not constrained.
Therefore, I think the second method is a better solution.
-4035830 0The problem is that you are using a normal pointer to store your EqVector. When you map a shared memory segment, it maybe mapped into any location in the process's address space. This means that where eqVector is stored in memory is different in the first process' memory space than in the second process'. You need to use a boost::offset_ptr, which stores addresses as offsets from the beginning of shared memory segments, see here: http://www.boost.org/doc/libs/1_35_0/doc/html/interprocess/offset_ptr.html
-33523070 0Which CodeIgniter version are you running?
If CodeIgniter 2.*. Try looking at this page: CodeIgniter Guides - Views
Under Loading a View it shows you the code of how to load your ViewMessages.php inside your controller
-2352887 0You need -source 1.5 or -source 1.6 I think. Or better yet use an IDE. Eclipse, NetBeans, and IntelliJ are all free.
-26343690 0I just used a simple regex. Of course, my answer is in python 2.7 so this may not work for you, depending on the version of python you are using.
input = '' with open('input.xml', 'r') as input_file: input_file = open('input.xml', 'r') input = input_file.read() import re output = re.sub('\n\s*([^<> ]+)\s*\n\s*', '\\1', input, flags=re.MULTILINE) with open('output.xml', 'w') as output_file: output_file.write(output)
Here's a working repl: http://repl.it/1SG/3
EDIT
This will not work if your values contain greater than or less than signs. I'm not sure how XML works entirely but it may not even allow those characters as values anyway.
-30251563 0In UrlManager, It will search from Top to Down.
So upto my knowledge, you can not define two CONTROLLER/ACTION for same Url alias.
But you can use controller forward in siteController. If your condition not satisfy then forward to mediaController.
$this->forward('media/index');
Hope helps !!
-37619201 0You can add 1 (= one day) to the time difference, then calculate it directly using TimeValue to remove the date part:
ShiftDuration = TimeValue(CDate(#06:00:00 am# - #10:00:00 pm# + 1)) ShiftDuration = TimeValue(CDate(#10:00:00 pm# - #02:00:00 pm# + 1)) ShiftDuration = TimeValue(CDate(#02:00:00 pm# - #06:00:00 am# + 1))
All of these will return a date/time value (a timespan) of 08:00:00
which can format for display using Format as you like or convert to hours and/or minutes.
If you need to display durations of more than 24 hours, use a function like this:
Public Function FormatHourMinute( _ ByVal datTime As Date, _ Optional ByVal strSeparator As String = ":") _ As String ' Returns count of days, hours and minutes of datTime ' converted to hours and minutes as a formatted string ' with an optional choice of time separator. ' ' Example: ' datTime: #10:03# + #20:01# ' returns: 30:04 ' ' 2005-02-05. Cactus Data ApS, CPH. Dim strHour As String Dim strMinute As String Dim strHourMinute As String strHour = CStr(Fix(datTime) * 24 + Hour(datTime)) ' Add leading zero to minute count when needed. strMinute = Right("0" & CStr(Minute(datTime)), 2) strHourMinute = strHour & strSeparator & strMinute FormatHourMinute = strHourMinute End Function
-30056571 0 Why is Android Studio taking it's time to launch an app on the device When I was using Eclipse with the ADT plugin and I clicked on launch, it almost instantly launched the app on my device.
I've switched to Android Studio because I wanted the gradle build system (I know that is available in Eclipse, but Android Studio itself is easier)
But when I click launch in Android Studio, it takes about 2 to 4 times longer than using Eclipse. I'm not working at a company so nobody is bothering, but my work is definitely slowed down by this.
Why is Android Studio slower than Eclipse? Because of the Gradle building system?
-38534312 0 In Firebase 3.0 together with Angularjs, it seems onAuthStateChanged fires on every route change. Is that expected?I have an app using Firebase and Angularjs. If I put a listener on onAuthStateChanged, it seems to fire every time I navigate to a new url in my site, and the Angularjs Route changes. This seems undesirable/incorrect? Anyone else experience this? E.g. if I do this in a controller:
firebase.auth().onAuthStateChanged(function(user) { if (user) { alert("changed"); } });
every time the route changes the alert pops up.
Since the logged in state of the user doesn't seem to be changing, why would this listener fire? I think I am missing something. Anyone understand what's going on?
-19833598 0as per discussion on IRC with op, could be
qs = qs.exclude( Q ( shared = True ) && ~ Q ( number__in=[1,6,7] ) )
-16132794 0 Show a colour X Window Pixmap in the root window's background I have a got a colour X PixMap file, GCC compiler, a working X server on a display and a very simple task: show an XPM file in colour by a C/C++ program via the X Server running on a display.
I have googled a lot and my brain is completely broken. No information about XCreatePixmapFromData. I can't get in the xloadimage sources. But putting a 1-bit depth bitmat is successfull and I want such an easy solution for a colour pixmap.
Teh pixmap is ordinary and here it is, for example, I just wanna show that it has almost the same structure as an X BitMap file (an array of constant chars) and can be included in the C/C++ program... http://pastebin.com/b5QTrDTH
A simple code example drawing a colour pixmap would be great.
That should be easy, please help! P. S. sorry, that's my first stackoverflow question.
-34907469 0There are two ways. The quick way to is to change the __unicode__
return for your TestTable
to return the field you like. However you might only want to show that field in current form but not other places, so it's not ideal.
Second option, you could define you own form field. It inherits ModelChoiceField
, but override label_from_instance
method:
class TestTableModelChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): # return the field you want to display return obj.display_field class TestForm(forms.ModelForm): type = TestTableModelChoiceField(queryset=Property.objects.all().order_by('desc1'))
-35171488 0 php missing argument error for a function hi guys i am Currently Confused why do i get this error about missing argument when i compile the code it gives me this error Warning: Missing argument 5 for print_LCS(), here is my code:
this is the function
function print_LCS($b,$x,$i,$j,$k){ $fLCS=array(); if ($i==0||$j==0) { return 0; } if ($b[$i][$j]=='c') { print_LCS($b,$x,$i-1,$j-1); $fLCS[$k] = $x[$i-1]." "; $k++; } elseif ($b[$i][$j]=='u') { print_LCS($b,$x,$i-1,$j); } else { print_LCS($b,$x,$i,$j-1); } return array($fLCS); }
and this is the function call:
list($final)=print_LCS($var2,$first,$var3,$var4,$var5);
hoping for your quick response guys. thank you So much.
-20981637 0 Reflective capabilities of R7RS SchemeThe R7RS report on the programming language Scheme describes two ways of running Scheme code in a Scheme system:
1) A scheme system can run a program as described in section 5.1 in the report.
2) A scheme system can offer a read-eval-print-loop, in which Scheme code is interpreted interactively.
My question is on how these two ways of running Scheme code can be reflected inside a Scheme system with what's included in the R7RS report.
There is the eval library procedure eval
, which executes Scheme code inside a running Scheme system so eval
looks like what I am searching for.
However, the only guaranteed mutable environment I can plug in eval
is the environment returned by the interaction-environment
repl library procedure. With this, however, I cannot reliably simulate a REPL (point 2) from above) because a REPL allows the import form, which the eval
procedure does not have to.
Also, I cannot use the interaction environment for eval
ing a full Scheme program by other reasons: It is generally not empty, in particular it contains all bindings of (scheme base)
.
For realising 1) inside a running Scheme system, the eval library procedure environment
looks promising as it allows to import libraries beforehand (which is part of running programs). However, the environment is immutable, so I cannot evaluate define
s inside the environment. A way out would be to wrap the body of the program to be run in a lambda
form so that define
would define local variables. However, this also doesn't work: Inside a lambda
form all defines have to come at the beginning of the body (which is not true for the top-level of a Scheme program) and inside a lambda
form library bindings can be lexically overwritten, which is not possible by top-level bindings.
As Scheme is Turing-complete, I can, of course, simulate a Scheme system inside a running Scheme system but I am wondering whether it is possible just by using the eval
procedure. One reason for my interest is that eval
might be optimized (e.g. by a JIT compiler backend), so using this procedure might give near native speed (compared to writing a simple interpreter by hand).
I've tried looking up how I might go about this for a while now, and maybe I am using the wrong terminology in my searches or it's way too advanced for me. I basically want to be able to analyze audio files in real-time. I know hardly anything about audio processing so I should probably start small and work my way up. Eventually I'd like to be able to display a power (or frequency?) spectrum correlating to audio playing in real time. Basically like the WinAmp spectogram (terminology?)
Any online tutorials with perhaps an API suggestion or two would be greatly appreciated. I've found some vague explanations (mostly dealing with calculating FFT's then converting them to something...) Like I said, I know little of audio processing, so knowing where to start would be great.
Language of choice: C++
-2157452 0netstat information can be retrieved by calling the GetTcpTable and GetUdpTable functions in the IP Helper API, or IPHLPAPI.DLL. For more information on calling the IPHLPAPI.DLL from Delphi, check out this Network traffic monitor. There are some wrappers for it too, and it is part of JEDI API Library.
I wrote a Delphi version of NetStat long ago, but have since lost the source code. Those resources should get you started though.
-951425 0I think this is an implementation detail of the Linux file system. While on Windows .h and .H files are effectively the same, on Linux you can have a traditional.h and a traditional.H in the same directory.
If I am understanding you correctly, you just need to specify the capital H in the files that include your headers.
-35944923 0Disclaimer: Do not down vote without explaining why, because OP didn't include his entire code base or hardware/infrastructure design. But if i've made critical errors in my code or logic, explain them and down vote accordingly.
Lets start off with defining the bottle-necks you'll encounter (some obvious, some not).
In regards to a CSV reader, they're fine but maybe not so efficient.
Since you're going to read through both files anyway I would consider the following:
Read the 13GB file line by line and save the ID
in a dictionary without checking if the key/value exists. (why? Because checking if the value exists is slower than just overwriting it and dictionaries also has a added bonus that keys are unique so duplicates will be weeded out) or add it to a set()
as described by many others.
followed by reading the smaller file line by line and checking your dict
or set
if it contains the ID
.
dict()
vs set()
vs list()
Here's a comparison between the three data types set()
, list()
and dict()
:
code used: test.py
(11.719028949737549, 999950, 'Using dict() for inserts') (1.8462610244750977, 'dict() time spent looking through the data') (11.793760061264038, 999961, 'Using set() for inserts') (7.019757986068726, 'set() time spent looking through the data') (15min+, 'Using list()') # Honestly, I never let it run to it's finish.. It's to slow.
As you can see dict
is marginally quicker than set
, while list()
just falls behind completely (see description of why by Antti). I should point out my data is a bit skewed since it's a quick and dirty demo of the speed difference, but the general idea should still come across.
So if you do not have access to a database version of the source-data, and you need to use Python, id go with something along the lines of:
delimiter = b'\x01' big_source = {} with open('13_gig_source.log', 'rb') as fh: for line in fh: csv = line.split(delimiter) big_source[csv[4]] = None # 5:th column, change to match CUSTOMER_ID output = open('result.log', 'wb') with open('smaller_file.log', 'rb') as fh: for line in fh: csv = line.split(delimiter) if csv[4] in big_source: output.write(csv[4] + b'\n') output.close()
Since I didn't know which column the data exists on i didn't optimize the split()
.
For instance, if it's the last column you're trying to fetch, do line.rsplit(delimiter, 1)[-1]
instead. Or if it's the 3:d column do line.split(delimiter, 3)[2]
because it will abort the process of looking for the next position of the delimiter
in the split()
functions.
Yes, some tools might be better off suited for this such as awk
because of the fact that it's a specific tool written in C to perform a very specific task. Even tho Python is based on C it still has a lot of abstraction layers on-top of that C code and will for the most part be slower than the counterpart C tools written for specific tasks.
Now I have no data to test this with, nor am i a PRO With Nix-Commands or PWN-C for short. So I'll leave someone else to give you examples of this, but i found this:
And it might be helpful.
-6338456 0 sequentially including various View classes in a parent layoutI have a main layout in which I'd like to sequentially display / hide various custom layouts according to timers and user input.
In my example, I'd like the following timeline:
show an initial layout, created by the class MainStart. The user will click on the button when they're ready to start.
after the user clicks, we'll run a countdown timer, displaying the countdown to the screen. This is done by MainCountdown.
once the countdown is complete, MainLast is displayed. It has a button allowing the user to click "Again?" when they want to start over.
if the user clicks "Again?" then go to step 1.
According to this question, I may have to use removeView() and addView() to achieve what I want.
I pushed to GitHub a trimmed down version of what I want to do: Hide and Show Layouts so you can see everything, but the problem seems to boil down to myView
still being visible after this:
myView = inflate(mContext, R.layout.main_start, _view_group); myView.setVisibility(View.GONE);
Can I make a small change to my code/layouts to make the views hide/appear the way I want?
Am I completely Doing It Wrong?
-18321293 0No you can't see the parents local variables. You inherit the parents prototype chain, not their local state. In your case you're applying the parent function onto the child object which does not hold the state.
apply(this,...)
means that you're binding the function to the current value of this. when you call method b from the child object, its then bound to the child, and therefore is not operating within the closure that contains the parents value.
-28994003 0For admob I use this plugin https://github.com/floatinghotpot/cordova-plugin-admob
It works perfectly and very easy to use
-22802839 0 What type of relationship these two tables will have in laravel?i have four tables in database:
A user will have many conversations and each conversation will have its members and replies.
here are the details:
Users migration:
$table->increments('id'); $table->string('name', 32); $table->string('username', 32); $table->string('email', 320); $table->string('password', 64); $table->timestamps();
Conversations migration:
$table->increments('id'); $table->timestamps();
conversationsmembers migration:
$table->increments('id'); $table->integer('conversation_id'); $table->integer('user_id'); $table->timestamps();
conversationsreply migrations
$table->increments('id'); $table->integer('conversation_id'); $table->integer('user_id'); $table->timestamps();
Now in User model, i need to define relationship between users table and conversations table. As they are not directly connected, i used hasManyThrough relation.
..app/models/User.php
... public function conversations() { return $this->hasManyThrough('Conversation', 'ConversationsMember', 'conversation_id', 'id'); } ...
When i 'm trying to use it, it's showing a blank array.
-11665717 0If you are using c#, you can simplify your life and use two separate regex:
bool res = false; string str = // your string if (str < 8) { res = Regex.IsMatch(str, @"^[0-9]+$"); } else { res = Regex.IsMatch(str, @"^(?=[a-zA-Z0-9]*[a-zA-Z])[a-zA-Z0-9]*$"); }
-27179117 0 char string[128];
defines a statically sized array of char
s. There is no need to allocate memory for it, but, on the other hand, there is no way to resize the memory portion.
To use a dynamically sized array use char *string;
with string = malloc(128)
, string = realloc(string, newsize)
and free(string)
when you are done.
Open a new Fragment when a gridView is clicked and then pass the position from the bundle parameters. Then in NewFragment show the listview and the data from database.
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { NextFragment nextFrag= new NextFragment(); Bundle bundle = new Bundle(); bundle.putInt("POSITION",position); this.getFragmentManager().beginTransaction() .replace(R.id.Layout_container, nextFrag,TAG_FRAGMENT) .addToBackStack(null) .commit(); } });
In the NextFragment get the reference of listView and then update the data from database using proper adapter.
-24518256 0Unexpectedly, but I've found an answer.
The only reason was in source-map package, which is in brunch
dependencies.
I've tried only two last versions of brunch: 1.7.13 and 1.7.14. Both of them requires source-map
version ~0.1.26
. Which is for now resolved to 0.1.34
wherever you install brunch.
And this is a root of evil.
What I've actually did is manual replace 0.1.34 with 0.1.33, directly in global brunch/node_modules
folder.
And that's it. After this everything magically fixed, and my sourcemaps point to right lines again.
Don't know WHY it is so - maybe, source-map@0.1.34
is broken. But this really works.
I want to have to shapes, that intersect each other. The intersection should be empty then. Somewhere I read that this is achieved by clockwise and anticlockwise drawing direction. But i cant figure it out...
this is my code:
<html> <head> <script> with( document.getElementById( 'myCanvas' ).getContext( '2d' ) ){ shadowOffsetX = 10; shadowOffsetY = 10; shadowBlur = 20; shadowColor = "rgba(0, 0, 0, .75)"; translate( 50, 70 ); scale( 2, 2 ); beginPath(); fillStyle = 'red'; strokeStyle = "white"; fillStyle = "#FFFF00"; beginPath(); arc(100,100,50,Math.PI*2,0,true); closePath(); stroke(); fill(); strokeStyle = "white"; fillStyle = "#FFFF00"; beginPath(); arc(50,50,50,-Math.PI*2,0,true); closePath(); stroke(); fill(); closePath(); fill(); } </script> </head> <body> <canvas id = myCanvas width = 400 height = 400 style = "border:1px solid #000" > </canvas> </body>
What i get is this: http://dl.dropbox.com/u/1144075/Bild%207.png
-30832253 0There are consistency problems:
static pid_t P1, P2, P3; // PIDs for each process int P; // parent PID
Why is P
and int
instead of a pid_t
? Why is it global instead of static
? Why is it P
instead of P0
? Should the whole lot be an array?
static pid_t P[4];
(There would be benefits to using an array!)
There is repetition that should be in a function invoked multiple times:
// Sending PIDs to process 1 close(providePIDY1[0]); write(providePIDY1[1], &P, sizeof(int)); write(providePIDY1[1], &P1, sizeof(int)); write(providePIDY1[1], &P2, sizeof(int)); write(providePIDY1[1], &P3, sizeof(int)); close(providePIDY1[1]); // Sending PIDs to process 2 close(providePIDY2[0]); write(providePIDY2[1], &P, sizeof(int)); write(providePIDY2[1], &P1, sizeof(int)); write(providePIDY2[1], &P2, sizeof(int)); write(providePIDY2[1], &P3, sizeof(int)); close(providePIDY2[1]);
Note that there's also repetition because the P
values aren't an array. There's also a possible portability liability; pid_t
does not have to be the same size as int
.
There are problems with checking inputs:
choice = getchar(); if(choice == 's')
Since choice
is a char
, you can get erroneous handling of EOF — if you bothered to test for it. You also leave a newline (at least) in the input, and don't skip leading spaces in the input. You'd likely do better with reading a line of data (fgets()
or POSIX readline()
) and then using if (sscanf(buffer, " %c", &choice) != 1) { …handle error… }
to get the character.
Your next input block is curious:
printf("Which process is receiving the signal - 1, 2, or 3?: "); choice2 = getchar(); choice2 = getchar(); printf("\n"); if((choice2 < 1) && (choice2 > 3))
The first input reads the newline (assuming there were no trailing spaces, etc), and the second gets a '1'
, '2'
, or '3'
. However, you test whether the input value is both less than 1 and greater than 3, and there's no known value in the universe for which both conditions are true (NaN
values are unknown values). You really wanted something like:
if (choice2 < '1' || choice2 > '3')
After you've determined which signal to send (more or less), you have another block of repeated code because you used P1
etc instead of an array P
.
There are chunks of repeated code in your child processes, such as the code that reads the process numbers. These should be in a function, too. The signal handling setup should probably be in a function too, though I've not spent a lot of time checking for the differences and similarities between the different process functions.
You say the code is supposed to be processing arithmetic expressions. You have the main program loop reading choices about signal handling, but you seem to have process1()
also trying to read expressions. This is bad news; it is indeterminate which of the processes will get to read any given input.
You have:
dataSize = strlen(buff) + 1; // plus NULL if(dataSize > 0) write(pfd12[1], &dataSize, sizeof(int)); write(pfd12[1], &buff, sizeof(char)*dataSize);
The test is a little pointless; the minimum value that strlen()
can return is 0
, so the minimum value in dataSize
is 1
, so the condition will always be true. (Theoretically, I suppose, you could enter so much data that the size_t
returned by strlen()
overflows the int dataSize
, but you've not allocated enough space for that to be an actual problem — your code will have had other problems before that.)
In process2()
, this code is curious:
token = strtok(buff, delim); while( token != NULL ) { number = strtol(token, &end, 0); if(!isInteger(number)) break; }
There are no circumstances under which the int number;
is going to be a non-integer when you scan the string with strtol()
. You have a risk of overflow (sizeof(int) != sizeof(long)
on 64-bit Unix systems, for example). You have a risk of not being able to interpret the remnants of floating point value (because the .
is not a valid part of an integer). You'll need to rework that code.
There's a lot of repetition in the signal handling code; it should be refactored so that you need fewer functions. It'll be easier to understand in the long run. Copy'n'paste'n'edit is a very bad way of programming when the result is near clones of the code in a single program.
I'm not clear what the differences are between the two versions you show; I've not scrutinized them. You should look at how to create an MCVE (How to create a Minimal, Complete, and Verifiable Example?) or SSCCE (Short, Self-Contained, Correct Example) — two names and links for the same basic idea. I'm not sure that either lot of code qualifies as an MCVE; both versions is overkill. Just supply the compilable code.
I've compiled the second chunk of code (saved in a file called procsync.c
) on my Mac running Mac OS X 10.10.3 with GCC 5.1.0, and using the command line:
$ gcc -O3 -g -std=c11 -Wall -Wextra -Wmissing-prototypes -Wstrict-prototypes \ > -Wold-style-definition -Werror procsync.c -o procsync $
To my considerable surprise, the code compiled under those very stringent options with no complaints — that is something I very seldom see in code on SO.
Congratulations!
(But there are still the other issues to worry about.)
-40320142 0 Excel Enter Value only IF Row contains specific textI have this formula that I use to calculate lead-time for jobs which works great for what I have needed. Now my job data is going to change in each row and the data I need will not always be in the same column as it once was. What I need to do is add to my existing formula to only fill in the leadtime IF any cells in the row contain the text "COMPLETED", otherwise leave the cell blank. Can anyone help with this?
=(IF(ISBLANK(P1),"",(IF(P1-G1<7,IF(WEEKDAY(P1)>WEEKDAY(P1),P1-G1-2,P1-G1),(P1-G1-(ROUNDDOWN((P1-G1)/7,0)*2))))))
-27872542 0 Paypal Rollback / Refund IPN if database update fails? I am wondering how I should handle a situation where a customer was billed for digital goods, so then the IPN is called and I deliver the digital good. What happens if something goes wrong in the delivery process? How should this case be handled? Is there something I can do to cancel / refund in this case?
I'm basing my ipn code off of a sample I found
protected void Page_Load(object sender, EventArgs e) { //Post back to either sandbox or live string strSandbox = "https://www.sandbox.paypal.com/cgi-bin/webscr"; // string strLive = "https://www.paypal.com/cgi-bin/webscr"; HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strSandbox); //Set values for the request back req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; byte[] param = Request.BinaryRead(HttpContext.Current.Request.ContentLength); string strRequest = Encoding.ASCII.GetString(param); strRequest += "&cmd=_notify-validate"; req.ContentLength = strRequest.Length; //for proxy //WebProxy proxy = new WebProxy(new Uri("http://url:port#")); //req.Proxy = proxy; //Send the request to PayPal and get the response StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII); streamOut.Write(strRequest); streamOut.Close(); StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream()); string strResponse = streamIn.ReadToEnd(); streamIn.Close(); if (strResponse == "VERIFIED") { //UPDATE YOUR DATABASE //check the payment_status is Completed //check that txn_id has not been previously processed //check that receiver_email is your Primary PayPal email //check that payment_amount/payment_currency are correct //process payment } else if (strResponse == "INVALID") { //UPDATE YOUR DATABASE } else { //UPDATE YOUR DATABASE } }
What if my updating of the database fails?
-2940823 0 generateUrl problemI am trying to generate a url but I keep getting a strange warning even though it works. I am making an api xml page and I use the following call in the controller:
public function executeList(sfWebRequest $request) { $this->users = array(); foreach($this->getRoute()->getObjects() as $user) { $this->users[$this->generateUrl('user_show', $user, true)] = $user->asArray($request->getHost()); } }
The user_show route is as follows:
# api urls user_show: url: /user/:nickname param: { module: user, action: show }
And the xml outputs as follows:
<br /> <b>Warning</b>: array_diff_key() [<a href='function.array-diff-key'>function.array-diff-key</a>]: Argument #1 is not an array in <b>/opt/local/lib/php/symfony/routing/sfRoute.class.php</b> on line <b>253</b><br /> <br /> <b>Warning</b>: array_diff_key() [<a href='function.array-diff-key'>function.array-diff-key</a>]: Argument #1 is not an array in <b>/opt/local/lib/php/symfony/routing/sfRoute.class.php</b> on line <b>253</b><br /> <br /> <b>Warning</b>: array_diff_key() [<a href='function.array-diff-key'>function.array-diff-key</a>]: Argument #1 is not an array in <b>/opt/local/lib/php/symfony/routing/sfRoute.class.php</b> on line <b>253</b><br /> <?xml version="1.0" encoding="utf-8"?> <users> <user url="http://krowdd.dev/frontend_dev.php/user/danny"> <name>Danny tz</name> <nickname>danny</nickname> <email>comedy9@gmail.com</email> <image></image> </user> <user url="http://krowdd.dev/frontend_dev.php/user/adrian"> <name>Adrian Sooian</name> <nickname>adrian</nickname> </user> </users>
So it outputs the correct xml but I do not know why it throws thows warning when calling the generateurl method.
Thanks!
-20927866 0With mapsforge you cannot do this. You have to use a routing library like graphhopper is one. See here how to use it: http://graphhopper.com/#developers.
But there are other offline and online routers as well. Have a look here: http://wiki.openstreetmap.org/wiki/Routing/offline_routers and here http://wiki.openstreetmap.org/wiki/Routing
-38976434 0 Can't show value with json format on apache tomcat serverI've been trying to make a certain API and I need it to show result of a method on server in JSON format. If I try simple
import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; @Path("/messages") public class MessageResource { @GET @Produces(MediaType.TEXT_PLAIN) public String getMessages() { return "Hello World!"; } }
it works but when I try to use my class where I return values in JSON format it shows some errors on the server (it works in ordinary console).
I'm new to this, hope I explained it well enough.
type Exception report message org.glassfish.jersey.server.ContainerException: java.lang.NoClassDefFoundError: org/codehaus/jackson/map/ObjectMapper description The server encountered an internal error that prevented it from fulfilling this request. exception javax.servlet.ServletException: org.glassfish.jersey.server.ContainerException: java.lang.NoClassDefFoundError: org/codehaus/jackson/map/ObjectMapper org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:489) org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427) org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388) org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341) org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) root cause org.glassfish.jersey.server.ContainerException: java.lang.NoClassDefFoundError: org/codehaus/jackson/map/ObjectMapper org.glassfish.jersey.servlet.internal.ResponseWriter.rethrow(ResponseWriter.java:278) org.glassfish.jersey.servlet.internal.ResponseWriter.failure(ResponseWriter.java:260) org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:509) org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:334) org.glassfish.jersey.internal.Errors$1.call(Errors.java:271) org.glassfish.jersey.internal.Errors$1.call(Errors.java:267) org.glassfish.jersey.internal.Errors.process(Errors.java:315) org.glassfish.jersey.internal.Errors.process(Errors.java:297) org.glassfish.jersey.internal.Errors.process(Errors.java:267) org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317) org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305) org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154) org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:473) org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427) org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388) org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341) org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) root cause java.lang.NoClassDefFoundError: org/codehaus/jackson/map/ObjectMapper valendor.messenger.ReturnJson.main(ReturnJson.java:27) sun.reflect.GeneratedMethodAccessor19.invoke(Unknown Source) sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) java.lang.reflect.Method.invoke(Unknown Source) org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81) org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:144) org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:161) org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$VoidOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:143) org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:99) org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389) org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347) org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102) org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:326) org.glassfish.jersey.internal.Errors$1.call(Errors.java:271) org.glassfish.jersey.internal.Errors$1.call(Errors.java:267) org.glassfish.jersey.internal.Errors.process(Errors.java:315) org.glassfish.jersey.internal.Errors.process(Errors.java:297) org.glassfish.jersey.internal.Errors.process(Errors.java:267) org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317) org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305) org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154) org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:473) org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427) org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388) org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341) org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) note The full stack trace of the root cause is available in the Apache Tomcat/8.0.36 logs.
thats the error
-2268143 0for visual studio: add in the Linker settings->command line "gdiplus.lib" to the 'Additional Options'
-7760883 0 Nginx: Setting a default file extensionWhat rule would I use for nginx so my default file extension is .php?
I currently access a pages using www.mywebsite.com/home.php but I want to just use www.mywebsite.com/home
Thanks
-40629380 0For basic types like int
, NoneType
, dict
and other simple cases there's a natural "factory" in Python - it is ast.literal_eval
.
>>> import ast >>> ast.literal_eval('None') is None True >>> ast.literal_eval('{1: 2}') {1: 2} >>> ast.literal_eval('1e6') 1000000.0
So if your data is a superposition of basic types (something json-like for instance), then you can parse it with single ast.literal_eval
call. Unlike exec
and eval
, ast.literal_eval
is much safer as you can't run any code with it.
When start the development server, Java will crash What is the cause?
(OS)
Mac OS X 10.6.6
(Java)
Java(TM) SE Runtime Environment (build 1.6.0_24-b07-334-10M3326) Java HotSpot(TM) 64-Bit Server VM (build 19.1-b02-334, mixed mode)
(GAE) Version 1.4.2
(console)
admin$ ./dev_appserver.sh --port=8080 /Users/admin/projects/sample1/war/ 2011-03-10 12:51:02.582 java[2542:903] [Java CocoaComponent compatibility mode]: Enabled 2011-03-10 12:51:02.583 java[2542:903] [Java CocoaComponent compatibility mode]: Setting timeout for SWT to 0.100000 2011/03/10 3:51:03 com.google.apphosting.utils.jetty.JettyLogger info ####: Logging to JettyLogger(null) via com.google.apphosting.utils.jetty.JettyLogger 2011/03/10 3:51:04 com.google.apphosting.utils.config.AppEngineWebXmlReader readAppEngineWebXml ####: Successfully processed /Users/admin/projects/sample1/war/WEB-INF/appengine-web.xml 2011/03/10 3:51:04 com.google.apphosting.utils.config.AbstractConfigXmlReader readConfigXml ####: Successfully processed /Users/admin/projects/sample1/war/WEB-INF/web.xml 2011/03/10 3:51:04 com.google.apphosting.utils.jetty.JettyLogger info ####: jetty-6.1.x 2011/03/10 3:51:04 com.sun.jersey.api.core.PackagesResourceConfig init ####: Scanning for root resource and provider classes in the packages: sample1.resources jp.tryden.resources.test 2011/03/10 3:51:04 com.sun.jersey.api.core.ScanningResourceConfig logClasses ####: Root resource classes found: class sample1.resources.CheckinsResource class sample1.resources.UsersResource class sample1.resources.ItemsResource 2011/03/10 3:51:04 com.sun.jersey.api.core.ScanningResourceConfig init ####: No provider classes found. 2011/03/10 3:51:05 com.sun.jersey.server.impl.application.WebApplicationImpl initiate ####: Initiating Jersey application, version 'Jersey: 1.1.5.1 03/10/2010 02:33 PM' 2011/03/10 3:51:06 com.google.apphosting.utils.jetty.JettyLogger info ####: Started SelectChannelConnector@127.0.0.1:8080 2011/03/10 3:51:06 com.google.appengine.tools.development.DevAppServerImpl start ####: The server is running at http://localhost:8080/ admin$ ( <- Stopped!! )
(crash log)
Process: java [3466] Path: /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/bin/java Identifier: java Version: 1.0 (1.0) Code Type: X86-64 (Native) Parent Process: java [3465] Date/Time: 2011-03-10 14:22:12.206 +0900 OS Version: Mac OS X 10.6.6 (10J567) Report Version: 6 Exception Type: EXC_BAD_ACCESS (SIGSEGV) Exception Codes: KERN_INVALID_ADDRESS at 0x0000000000000000 Crashed Thread: 10 Dispatch queue: com.apple.root.low-priority Thread 0: Dispatch queue: com.apple.main-thread 0 ??? 0x000000010301f383 0 + 4345426819 1 ??? 0x000000010300685a 0 + 4345325658 2 ??? 0x0000000103006e8d 0 + 4345327245 3 ??? 0x00000001030069b3 0 + 4345326003 4 ??? 0x00000001030069b3 0 + 4345326003 5 ??? 0x0000000103006e8d 0 + 4345327245 6 ??? 0x000000010300685a 0 + 4345325658 7 ??? 0x000000010300685a 0 + 4345325658 8 ??? 0x000000010300685a 0 + 4345325658 ...
-17758697 0 Try setting the setOnPreferenceChangeListener for your editPreference in onCreate(), put your validation code inside this callback.
Reading the docs, they say OnSharedPreferenceChangeListener is called when the shared preference is changed(is already changed). In the other hand the setOnPreferenceChangeListener is triggered "when this Preference is changed by the user (but before the internal state has been updated)"
-4032071 0 Dealing with implementation concerns in TDDI've just got started on TDD and very quickly ran into a brick wall. Here's my scenario... I'm trying to model an Image object, and going through the TDD steps I've started with a simple object which eventual grew into...
public class ImageObject { public string Name {get; set;} public int Width {get; set;} public int Height {get; set;} public bool IsValid() { //Some rules } }
Of course the obligatory tests...
[Test] public void ImageWidthCannotBeLessThanZero {...} [Test] public void ImageHeightCannotBeLessThanZero {...} and so forth...
So far so good. Next, I want to represent the physical file in the class somehow. It could be with a file path
public class ImageObject { public string Path {get; set;} }
or a series of bytes
public class ImageObject { public byte[] Bytes {get; set;} }
(Please this is not an argument about DB vs File system for storage.)
At this point I'm not feeling comfortable because my mind is drifting and starting thinking about the infrastructure/implementation details. Where is my flaw?? Should i make the decision upfront on the implementation detail? Do i need a clever design pattern to deal with this? Would a mocking framework help? This is an Object Analysis/Design problem and I should use UML tools? (Wait a minute i thought TDD was about design?)
Anyway how do i overcome this of problem? I want to remain focused on designing my objects and not think about infrastructure concerns at this time?
-22404540 0Your call to setAttribute
uses the key "userbean"
, then your call to getAttribute
uses urbean.getUser_mobile()
.
Unless urbean.getUser_mobile()
returns "userbean"
then getAttribute
will return null
.
Given the code setting the attribute is:
session.setAttribute("userbean", urbean);
The code to get the attribute should be:
User_Registration urbean = (User_Registration)session.getAttribute("userbean")
You have to use the same key to get that you used to set...
-15563518 0You must assign $connection
to a
mysql_connect()
function
Anyway you should not use mysql functions anymore because they are deprecated. You can use PDO instead.
-37391413 0Could do with seeing a bit more context, but the following should do what I think you want:
Private Sub btnIgnorar_Click(sender As Object, e As EventArgs) Handles btnIgnorar.Click DialogResult = DialogResult.Ignore Close End Sub
This will close the dialog and return the associated result code to the caller. As to the original code, it seems a bit strange setting the values in the buttons click handlers?
-36375412 0You can replace the old object with the cloned-updated one.
doEdit: function (record) { var index = _.indexOf(this.list, this.cache); this.list.splice(index, 1, record); }
https://jsbin.com/ruroqu/3/edit?html,js,output
-19021699 0Integrating OpenCms with Liferay Portal Server there are many options, some
OC & LR integrated in the same container pro: cost (if tou pay per container) cons: maintenance, high impact on installation
OC/LR on different containers comunicating via http pro: easier then 1 cons: low level comunication capabilities
OC/LR on different containers, OC expose WebServices called by LR pro: loose coupling, poor installaction impacts cons: bit of it skills
This is a big problem, you cannot do it all by your self. There should by a community to support 3rd solution
-7797841 0There's nothing wrong with adding script elements mixed in the middle of the body
, however if you want to improve loading times, you might want to append the script
elements to footer.php
. Having scripts called after the rest of the dom has loaded will prevent the loading of the scripts from blocking the rest of the page from rendering.
If it's a very small script, I see no reason not to just add them inline where it'll be easy to see what elements they affect.
-2165923 0It is useful to mark "unknown" or missing values.
For instance, if you're storing people, and one of the fields is their birthday, you could allow it to be NULL
to signify "We don't know when he was born".
This is in contrast to having non-nullable fields where, for the same type of meaning, you would need to designate a "magic value" which has the same meaning.
For instance, what date should you store in that birthday field to mean "we don't know when he was born"? Should 1970-01-01 be that magic value? What if we suddenly need to store a person that was born on that day?
Now, having said that, NULL
is one of the harder issues to handle in database design and engines, since it is a propagating property of a value.
For instance, what is the result of the following:
SELECT * FROM people WHERE birthday > #2000-01-01# SELECT * FROM people WHERE NOT (birthday > #2000-01-01#)
(note, the above date syntax might not be legal in any database engine, don't get hung up on it)
If you have lots of people with an "unknown" birthday, ie. NULL
, they won't appear in either of the results.
Since in the above two queries, the first one says "all people with criteria X", and the second is "all people without criteria X", you would think that together, the results of those two queries would produce all the people in the database.
However, the queries actually say "all people with a known and definite criteria X."
This is similar to asking someone "am I older than 40?" upon which the other person says "I don't know". If you then proceed to ask "am I younger than 41?", the answer will be the same, he still doesn't know.
Also, any mathematics or comparisons will produce NULL
as well.
For instance, what is:
SELECT 10 + NULL AS X
the result is NULL
because "10 + unknown" is still unknown.
Need to install the actual APK to be able to debug the application
https://blog.nraboy.com/2015/02/properly-testing-ionic-framework-mobile-application/
-9627687 0Use index() method to get position. Can show you how to get it, however there is nothing in question to define "List" http://api.jquery.com/index/
Your input html is invalid
<input type="text" value="b" /> $('span input:text').live('blur', function(){ var position=$(this).index()+1;/* index is zero based*/ var value = $(this).val(); })
-12826718 0 Why don't you use ruby's coverage capability or a code coverage tool like SimpleCov?
-18482734 0This library will probably make things a lot easier for you: https://code.google.com/p/php-csv-parser/. I have used it in a recent project where I need to parse CSVs and insert into a MySQL database.
You can choose which table to insert into by using $csv->getCell($x, $y)
where $x
and $y
point the cell with "Table1"
or "Table2"
inside.
So you could do:
$table_name = $csv->getCell($x, $y); if( $table_name === "Table1" ) { // code to insert into table 1 } else if( $table_name === "Table2" ) { // code to insert into table 2 }
-12036376 0 Please use theDate.ToString({format as you need})
. May be format of date in your locale contains "bad" symbols(slashes).
Formats can be found at http://msdn.microsoft.com/en-us/library/az4se3k1.aspx
-10961643 0 Can i create non-rectangle window without compositing manager?I want to create custom shaped window. I only need to specify which pixels have to be drawn.
When compositing manager is used i can use alpha channel, but without it i don't know how can i do it.
-13731744 0 cannot debug into my DbContext derived class code using Entity Framework (ver 4.3.1) code-firstHere is my solution setup using VS 2012 Ultimate:
I have a project (e.g. MyDomainModel) containing all the business domain types using POCO classes. I have another project (e.g. MyEntity) referring to the MyDomainModel project and has the derived DbContext class (e.g. MyDbContext) implementing custom business logic (e.g. for automatic time-stamping when inserting and modifying data) in the SaveChanges method.
I have another mstest based project (e.g. MyEntity_Tests) which will test the derived DbContext (e.g. MyDbContext) with known seeded data as part of the database initialization.
My problem is that when debugging the test, the breakpoint set on the MyDbContext's c# code is not hit. However if I put lines such as Debug.Print("xxx") in the file and debugging the same test, the test output will contain those expected output "xxx".
I know that Entity Framework runtime will generate proxy dll behind scene to wrap those dlls (e.g. MyDomainModel.dll). However not being able to debug my own code as in MyDbContext is really a big problem to me. Do other people have the similar problem when using EF code-first and how to solve this problem?
-29730457 0upgrade gulp-useref:
npm remove gulp-useref && npm i gulp-useref --save-dev
-34959739 0 So this problem arose because of inexperience with the express module.
I thought bodyParsed would hold a value returned from: app.use(bodyParser.json());
when you use app.use(bodyParser.json()); It actually stores it in the body property of the Request.
So:
app.use(bodyParser.json(joptions));//causes request.body to populate with the JSON data app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded requires multer app.all('/*', function(request, response){ //Handle request var bucket = request; console.log('\n \n \n &&&&&& \n \n \n'); var joptions = { type: 'application/json' } console.log(request.body)); var headParsed = parseHttpHeader(bucket.headers['content-type'])[0]; console.log(headParsed); });
Not sure if this forces all requests to be parsed as application/json. Maybe moving the bodyparser inside the app.all() will cause it to only parse when using that route?
-39078600 0The image
on a UIImageView
is an UIImage
optional, meaning that it can have a value (contain an image) or it can be nil
.
So, when you're saying:
let ocrSample = myImageView.image
your ocrSample
is now an UIImage
optional, which you then have to unwrap before you use it.
When you then say:
tesseract.image = ocrSample!.fixOrientation().g8_blackAndWhite()
you are force unwrapping your ocrSample
by using !
, meaning that you are telling the compiler to just unwrap and use the optional, regardless of it being nil
or not. This causes a crash when you then try to use that unwrapped optional if it contains nil
.
What you can do is unwrap ocrSample
using an if let
like so:
func checkWithOCR() throws{ if let ocrSample = myImageView.image { tesseract.image = ocrSample.fixOrientation().g8_blackAndWhite() if(tesseract.recognize()){ let recognizedText = tesseract.recognizedText if recognizedText != nil{ print("recognizedText: \(recognizedText)") let trimmedText = String(recognizedText.characters.filter { !" \n\t\r,".characters.contains($0) }) myImageView.image = tesseract.image convertCurrency(Float(trimmedText)!) //convert the tesseract text } } SwiftSpinner.hide() } else { //No value could be found, do your error handling here } }
Here:
if let ocrSample = myImageView.image
you are trying to unwrap the value of myImageView.image
into ocrSample
, if that succeeds, then you know for sure that ocrSample
is not nil
and can use it onwards. If it fails, then you can do your error handling, show an alert view and whatever else you need to do.
Hope that helps you.
-12091730 0You need to call rect
for each colour that you want to draw, and have those colours in a categorical column in your data frame so that you can filter the data per category for each call to rect
.
I don't know what your original data is like, so here's something similar:
# set up simple plotting window plot.new() plot.window(xlim=c(0,6),ylim=c(0,8)) # example data. Using colour as the categorical value we will filter on sample.d <- data.frame(x=c(3,4,5,6), yb=c(1,3,5,7), yt=c(0,2,4,6), colour=c("black","black","red","red")) # draw black rectangles black.d <- sample.d[sample.d$colour == "black",] rect(0, black.d$yb, black.d$x, black.d$yt, col="black") # draw red rectangles red.d <- sample.d[sample.d$colour == "red",] rect(0, red.d$yb, red.d$x, red.d$yt, col="red")
-40535976 0 And the reason it is not changing because LayoutSubviews is called all the time and overrides your SetItems. Use constructor to populate toolbar first time
public partial class CustomUiToolbar : UIToolbar { public CustomUiToolbar (IntPtr handle) : base (handle) { var _UIBarButtonItemArrayOne = new UIBarButtonItem[3]; for (int i = 0; i < 3; i++) { var _item = new UIBarButtonItem(i.ToString(), UIBarButtonItemStyle.Done, null); _item.TintColor = UIColor.Red; _UIBarButtonItemArrayOne[i] = _item; } //var __UIBarButtonItemArrayTwo = new UIBarButtonItem[2]; //for (int i = 0; i < 2; i++) //{ // var _item = new UIBarButtonItem(i.ToString(), UIBarButtonItemStyle.Done, null); // _item.TintColor = UIColor.Blue; // __UIBarButtonItemArrayTwo[i] = _item; //} SetItems(_UIBarButtonItemArrayOne, true); } public override void LayoutSubviews() { base.LayoutSubviews(); } }
-18899613 0 You need to set an expectation on the UsarioService to say what will be returned when usarioService.save(...) is called.
Before getting to that point, you need to say in the test mockUsarioService.createMock() which will create the actual instance of the mock object, that's what you will pass to the controller usarioService attribute. Copied the code below from the Grails documenation. http://grails.org/doc/1.1/guide/9.%20Testing.html
String testId = "NH-12347686" def otherControl = mockFor(OtherService) otherControl.demand.newIdentifier(1..1) {-> return testId } // Initialise the service and test the target method. def testService = new MyService() testService.otherService = otherControl.createMock()
-17645190 0 I'm one of the AeroGear JS devs. The JS OTP lib is just getting started, but we have both Android and iOS libs that are more mature and since you are using cordova/phonegap it's possible to create a plugin to access the native libs until the JS version is a bit more solid.
-Luke
-39504019 0It is not possible, to return a vector c(4, 'not possible', 3, 'not possible')
as such a vector does not exist. All elements in a vector must be of the same type. Off course you can output numbers an texts together. This is a simple exercise that can be solved in a number of ways. For teaching purposes, I propose the following, where the two problems are divided into two functions in a very functional manner:
getSingleRoot <- function(x){ if(x<0){ cat("not possible ") return(NaN) } else{ cat(sqrt(x)) cat(" ") return(sqrt(x)) } } getRoot <- Vectorize(getSingleRoot) a <- getRoot(c(4, -4, 9, -16))
Other good solutions could make use of a for
Loop, of Map
, of ifelse
or sapply
, on sqrt
already being a vectorized function and so on. Ìf this is homework, it depends on what you have already learned.
According to the docs (http://emberjs.com/api/classes/Ember.Handlebars.html#method_registerBoundHelper) you should be using Ember.Handlebars.registerBoundHelper
to get this data binding. registerHelper
by default is unbound.
Visual Studio 2008 Express, (or Visual C# 2008 Express, if you don't want to use other languages) is a good choice. It's free.
Non-Microsoft, try SharpDevelop
Edit: if you are a student, and your university is MSDN AA certificated, you can get Visual Studio 2008 Professional for free. Yes, free.
-4699117 0I was just pointed to this solution:
import java.lang.reflect.ParameterizedType; public abstract class A<B> { public Class<B> g() throws Exception { ParameterizedType superclass = (ParameterizedType) getClass().getGenericSuperclass(); return (Class<B>) superclass.getActualTypeArguments()[0]; } }
This works if A
is given a concrete type by a subclass:
new A<String>() {}.g() // this will work class B extends A<String> {} new B().g() // this will work class C<T> extends A<T> {} new C<String>().g() // this will NOT work
-17095602 0 Raghav, at present card.io is not able to detect the cardholder name. We do hope to add that feature sometime in the future, though.
-2468288 0this should fix it
.a, .b, .c { float: left; } .b { clear: both; }
-7930019 0 As you're using GroupBy extension method you're getting list of grouped items where each group is enumerable of elements with same OfferId.That's why you have 'System.Collections.Generic.List<System.Linq.IGrouping<long,myDAL.viewOffers>>'
as a result of your operation. Look into IGouping documentation.
Turning comment into answer since it turned out to be the solution:
In your shader code you have a varying variable called LightDirection_cameraspace
, which you use in your fragment shader computations. But you never assign a value to it in the vertex shader (instead you compute a local variable LightPosition_cameraspace
which isn't used further, though). So it probably has some undefined value inside the fragment shader, causing your lighting issues.
How about invalidate the current session? Something like this:
public String logout(HttpSession session) { session.invalidate(); .... }
-22343518 0 At present this functionality is not available for android in API V2. You can do this in website for browser using API V3. In Android when you try to get route between two Lat Long, you will need to call web service. Likewise you will need to call web service for each such route, which is not an efficient way. This will reduce performance of your application.
Hope this will help you.
-17582473 0try {{item.link['xx-test'].href}}
For further reading on bracket notation:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
-1239219 0Normally you would just use a each statement like below:
jQuery.each(json.answers, function(i, val) { $("#" + i).val() = val; });
-33553915 0 aria-describedby text not announced on I have an HTML form with mainly 2 types of fields - text and checkboxes groups. Each form field has a hidden that includes error message and connected to formfield with "aria-describedby". When form with errors is hit submit button, common error message shows up on top and culprit fields gets error styling at field level. As user tabs to errornous form to edit, to each field, field level error message is also displayed via CSS changes. If JAWS is running, it is read out as user tabs into field.
But this is not happening for checkboxes group. I have checkboxes wrapper - tabbable, user can Kb focus to it and error div is displayed but not announced.
We do not have aria-live and alert on each form field but on common error message div on top. This is on purpose as we want those errors to be announced first by JAWS as user hits save.
Any suggestions to this problem? I tried to have tabindex and aria-describedby /aria-invalid on outer div or on another wrapper div but failed to fix jaws issue.
<div style="display: none; left: -9999px; z-index: 1000; top: 335.717px;" class="errorClass" id="showerror">Error: Please select a checkbox </div <div> <fieldset aria-describedby="showError" aria-invalid="true" id="myFieldSet" tabindex="0" > <legend>some legend text</legend> <div class="checkboxClass"> <input type="checkbox" id="1" value="1" name="chkgp"> <input type="checkbox" id="2" value="2" name="chkgp"> </div> </fieldset> </div></div>
-25600734 0 To maintain state across activities you have to use SharedPreferences, or database. In your case SharedPreferences is the best option
You have used OnSavedInstance it will only save the instance until the activity is not destroyed i.e it stays on the stack.
Check activity lifecycle to understand more about when an activity is destroyed.
For each checkbox you can store its value in sharedPreference and on onCreate() of you activity you should check the checkboxes according to the sharedPreference values
Here is how you use shared prefs
SharedPreferences prefs= context.getSharedPreferences("myPrefs", 0); SharedPreferences.Editor editor = prefs.edit(); editor.putBoolean("checkbox1", true);//true if checked editor.commit(); // get stored value , if no value is stored then assume its false prefs.getBoolean("checkbox1", false);
-19338908 0 Linear Diophantine equations take the form ax + by = c
. If c
is the greatest common divisor of a
and b
this means a=z'c
and b=z''c
then this is Bézout's identity of the form
with a=z'
and b=z''
and the equation has an infinite number of solutions. So instead of trial searching method you can check if c
is the greatest common divisor (GCD) of a
and b
(in your case this translates into bx - dy = c - a
)
If indeed a
and b
are multiples of c
then x
and y
can be computed using extended Euclidean algorithm which finds integers x
and y
(one of which is typically negative) that satisfy Bézout's identity
and your answer is:
a = k*x
, b = k*y
, c - a = k * gcd(a,b)
for any integer k.
(as a side note: this holds also for any other Euclidean domain, i.e. polynomial ring & every Euclidean domain is unique factorization domain). You can use Iterative Method to find these solutions:
By routine algebra of expanding and grouping like terms (refer to last section of wikipedia article mentioned before), the following algorithm for iterative method is obtained:
pseudocode:
function extended_gcd(a, b) x := 0 lastx := 1 y := 1 lasty := 0 while b ≠ 0 quotient := a div b (a, b) := (b, a mod b) (x, lastx) := (lastx - quotient*x, x) (y, lasty) := (lasty - quotient*y, y) return (lastx, lasty)
So I have written example algorithm which calculates greatest common divisor using Euclidean Algorithm iterative method for non-negative a
and b
(for negative - these extra steps are needed), it returns GCD and stores solutions for x
and y
in variables passed to it by reference:
int gcd_iterative(int a, int b, int& x, int& y) { int c; std::vector<int> r, q, x_coeff, y_coeff; x_coeff.push_back(1); y_coeff.push_back(0); x_coeff.push_back(0); y_coeff.push_back(1); if ( b == 0 ) return a; while ( b != 0 ) { c = b; q.push_back(a/b); r.push_back(b = a % b); a = c; x_coeff.push_back( *(x_coeff.end()-2) -(q.back())*x_coeff.back()); y_coeff.push_back( *(y_coeff.end()-2) -(q.back())*y_coeff.back()); } if(r.size()==1) { x = x_coeff.back(); y = y_coeff.back(); } else { x = *(x_coeff.end()-2); y = *(y_coeff.end()-2); } std::vector<int>::iterator it; std::cout << "r: "; for(it = r.begin(); it != r.end(); it++) { std::cout << *it << "," ; } std::cout << "\nq: "; for(it = q.begin(); it != q.end(); it++) { std::cout << *it << "," ; } std::cout << "\nx: "; for(it = x_coeff.begin(); it != x_coeff.end(); it++){ std::cout << *it<<",";} std::cout << "\ny: "; for(it = y_coeff.begin(); it != y_coeff.end(); it++){ std::cout << *it<<",";} return a; }
by passing to it an example from wikipedia for a = 120
and b = 23
we obtain:
int main(int argc, char** argv) { // 120x + 23y = gcd(120,23) int x_solution, y_solution; int greatestCommonDivisor = gcd_iterative(120, 23, x_solution, y_solution); return 0; }
r: 5,3,2,1,0,
q: 5,4,1,1,2,
x: 1,0,1,-4,5,-9,23,
y: 0,1,-5,21,-26,47,-120,
what is in accordance with the given table for this example:
You could send HTTP Link
headers instead:
Link: <http://www.example.com/favorite-books/everything-on-one-page>; rel="canonical" Link: <http://www.example.com/favorite-books/page-1>; rel="prev" Link: <http://www.example.com/favorite-books/page-3>; rel="next"
According to Google’s documentation about their usage of canonical
, it’s supported.
While support isn’t mentioned on Google’s documentation about their usage of prev
/next
, support was confirmed in a thread on their product forums.
Option 1:
I think that from the select efficiency point of view, option 1 might give you the best result, using a filtered index on the userId
column in the UserScan
table.
Option 2:
Your second option is probably the worst option since it means you will have two almost identical table structures in your database, and that's a bad design.
Option 3:
On the academic level, option 3 is the way to go. Nullable columns are frowned upon in the relational model. To prevent the UserScanEvent
table from creating a many to many relationship between scans and persons, add a unique constraint on the scanId
column. this way, each scan in this table can only be associated with a single person.
To sum up:
Having said all that, Select efficiency is a tricky thing to predict. My hunch tells me that option 1, while might not be the best fit to the relational model, will enable faster select executes then option 3, but as Jorge Campos wrote in his comment, it is merely my opinion, it's not something I can say for sure.
How can I arrange where tool options are placed, like I illustrate in the screenshot:
I don't have any idea how I located this panel on the top but it's annoying. The default view:
Or maybe just reset view settings..
-10684657 0 DataGrid not displaying dataI am trying to display a DataGrid
on my mobile application after reading a CSV file and processing it. Here is what I have so far:
private void btOpenFile_Click(object sender, EventArgs e) { try { // Process all data into an array of Object // this.records array contains objects of type MyRecord // Create datatable and define columns DataTable dt = new DataTable("myDt"); dt.Columns.Add( new DataColumn("String A",typeof(string))); dt.Columns.Add( new DataColumn("Int 1", typeof(int))); // Loop through and create rows foreach(MyRecord record in records) { DataRow row = dt.NewRow(); row[0] = record.stringA; row[1] = record.int1; dt.Rows.Add(row); } // Create dataset and assign it to the datasource.. DataSet ds = new DataSet("myDs"); ds.Tables.Add(dt); dataGrid.DataSource = ds; dataGrid.Refresh(); } catch (Exception ex) { MessageBox.Show("Error: " + ex.Message,"Error"); } }
All I get is a blank data grid component when running my application. Can somebody point out my mistake? or how to do this correctly?
-1851781 0 Transpose a row into columns with MySQL without using UNIONS?I have a table that is similar to the following below:
id | cat | one_above | top_level | 0 'printers' 'hardware' 'computers'
I want to be able to write a query, without using unions, that will return me a result set that transposes this table's columns into rows. What this means, is that I want the result to be:
id | cat | 0 'printers' 0 'hardware' 0 'computers'
Is this possible in MySQL? I can not drop down to the application layer and perform this because I'm feeding these into a search engine that will index based on the id. Various other DBMS have something like PIVOT and UNPIVOT. I would appreciate any insight to something that I'm missing.
Mahmoud
P.S.
I'm considering re-normalization of the database as a last option, since this won't be a trivial task.
Thanks!
-21691360 0 Camel and MQTT RouteI am working on a project and have decided to use Camel and ActiveMQ. I am attempting to create a route using Java and MQTT endpoints. Within this route I have also incorporated a Processor. This is what my route looks like:
from("mqtt:test?subscribeTopicName=zaq.avila.send") //.process(new RestProcessor()) .to("mqtt:test?publishTopicName=zaq.avila.receive");
From my understanding, the route is consuming from zaq/avila/send, a processor is applied and then the message is published to zaq/avila/receive. The to() part does not appear to be happening, when I check the console, I see that the processor executes though no message is published to zaq/avila/receive. Also, within the web console I see that the messages in zaq/avila/send for enqueued and dequeued increment even when I only pusblished one message. In addition, if I shutdown ActiveMQ I get the following:
INFO | Waiting as there are still 1 inflight and pending exchanges to complete, timeout in 7 seconds.
Also:
WARN | Error occurred while shutting down service: Endpoint[mqtt://test?publish TopicName=zaq.avila.receive]. This exception will be ignored. java.lang.NullPointerException
These exception make me wonder that the exchange is not completing and something is missing. I need help!
-39051546 0 How to use regex to exclude a url path?I'm working on a process where I have to exclude a specific url path.
--exclude "/faq"
The above will exclude example.com/faq but not the other paths such as example.com/questions, example.com/needed, example.com/answers ....
What I want is:-
example.com/cricket-or-football/question-3695225 --> only this (instead of) example.com/cricket-or-football/question-3695225/3699293/3463987 -----> has to be excluded.
How can I do this in regular expression?
I tried:-
--exclude "/.+/question-[0-9]/.+"
But its not working!
-16033943 0It sounds like there's a network issue preventing you from connecting to your Worklight server.
This can be due to many different reasons, to list some:
To ensure that you are indeed reaching the server I would suggest using a network sniffer. One tool that runs on Windows is Fiddler.
Fiddler can be set up as a reverse proxy where your device will be making calls to the proxy. The proxy will then route your request to the web server but it will also log the information so you can view it.
If you are on Windows, I would suggest installing Fiddler and following Option #2 of this answer.
You should then be able to see if your requests are reaching the server and continue investigation from there.
-19163076 0 JavaFX: Latest version of javafx-runtimeWhat is the latest version of javafx runtime?
I tried to add the following dependency:
<dependency> <groupId>com.oracle</groupId> <artifactId>javafx-runtime</artifactId> <version>2.2.25</version> </dependency>
I get the following error while saving my pom.xml.
Missing artifact com.oracle:javafx-runtime:jar:2.2.25
I tried updating the project dependencies but that did not help. Any pointers will be helpful.
-33342151 0 Laravel 5 - Auth Middleware dont protect route but throw error messageI have some problems with my auth middleware. I want to protect my routes with it, but in some controllers it dosent work really. If I check the routes as logout user, I got different error messasges instead of blocking the access and redirect to the login page. I use the middleware always over the __construct() in the controllers.
An example.
Controller
public function show(Dialog $dialog) { return $this->template($dialog, self::DISPLAY_MODE_DIALOG); } protected function template(Dialog $dialog, $displayMode, $messageLimit = 10) { $user = Auth::user(); // Check if the profile is currently controlled by the current user $isControlled = $dialog->moderator()->appProfile()->isControlledBy($user->id); $messageList = $dialog->latestMessages($messageLimit); return view('dialog.chat.template') ->with(compact('dialog', 'messageList', 'isControlled', 'displayMode')); }
Model
public function isAccessibleBy(User $user) { $profile = $this->moderator()->appProfile(); return $profile->isOwner($user->id) || $profile->isControlledBy($user->id); }
Error
Argument 1 passed to App\Model\Dialog\Dialog::isAccessibleBy() must be an instance of App\Model\Account\User, null given, called in C:\projekte\php\newchat\app\Model\Dialog\Dialog.php on line 332 and defined
Now I realize why this happens, but i think the middleware should dont show this messages an protecte the route.
http://laravel.com/docs/5.0/middleware
-25249886 0"However, if the user is authenticated, the middleware will allow the request to proceed further into the application."
The batch script below will print out the existing default JRE. It can be easily modified to find the JDK version installed by replacing the Java Runtime Environment with Java Development Kit.
@echo off setlocal ::- Get the Java Version set KEY="HKLM\SOFTWARE\JavaSoft\Java Runtime Environment" set VALUE=CurrentVersion reg query %KEY% /v %VALUE% 2>nul || ( echo JRE not installed exit /b 1 ) set JRE_VERSION= for /f "tokens=2,*" %%a in ('reg query %KEY% /v %VALUE% ^| findstr %VALUE%') do ( set JRE_VERSION=%%b ) echo JRE VERSION: %JRE_VERSION% ::- Get the JavaHome set KEY="HKLM\SOFTWARE\JavaSoft\Java Runtime Environment\%JRE_VERSION%" set VALUE=JavaHome reg query %KEY% /v %VALUE% 2>nul || ( echo JavaHome not installed exit /b 1 ) set JAVAHOME= for /f "tokens=2,*" %%a in ('reg query %KEY% /v %VALUE% ^| findstr %VALUE%') do ( set JAVAHOME=%%b ) echo JavaHome: %JAVAHOME% endlocal
-14697454 0 Where can I get debug symbols (PDB) for Windows.Live.dll? I am using the Microsoft Live SDK for Windows Phone to access SkyDrive and get an exception in Microsoft.Live.dll. I'd like to step through the source to debug the issue, but fetching symbols from symbol server http://msdl.microsoft.com/download/symbols fails.
I followed these instructions on how to set up the symbol server in my dev environment. The environment variable _NT_SYMBOL_PATH
is set to srv*c:\symbols*http://msdl.microsoft.com/download/symbols. This seems to work for other assemblies. While debugging I see the symbol cache at c:\symbols grow with entries, but Microsoft.Live is missing.
Where can I get debug symbols for Microsoft.Live.dll?
-3038834 0 Android - Persist file when app closesI am creating a file in my Android application as follows:
HEADINGSTRING = new String("Android Debugging " + "\n" "XML test Debugging"); } public void setUpLogging(Context context){ Log.d("LOGGING", "Setting up logging....."); try { // catches IOException below FileOutputStream fOut = context.openFileOutput(FILE_NAME,Context.MODE_APPEND); OutputStreamWriter osw = new OutputStreamWriter(fOut); // Write the string to the file osw.write(HEADINGSTRING); /* ensure that everything is * really written out and close */ osw.flush(); osw.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally{ Log.d("LOGGING", "Finished logging setup....."); } }
And I write to the file during the running of the app as follows:
public void addToLog(File file, String text) throws IOException { BufferedWriter bw = new BufferedWriter (new FileWriter(file, true)); bw.write ("\n" + text); bw.newLine(); bw.flush(); bw.close(); }
This works fine but when my app closes the file gets deleted and when the app is run again all the information I wrote to it is gone.
How can I make sure the file persists even after closure of the app?
Update:
I have changed MODE_PRIVATE to MODE_APPEND and the problem is fixed, thanks Skirmish.
-8275469 0Take a look at revalidator. It is described as "A cross-browser / node.js validator used by resourceful and flatiron."
-3345183 0Both versions of your TransferText operation are using a SpecificationName named tblEmployees. What Code Page is specified in that Specification?
Try importing the text file manually. Choose "Advanced" from the Import Text Wizard. Then select Unicode in the Code Page list box. You may need to test with different Code Page selections until you find which one imports your text correctly.
Which ever Code Page selection works, save your choices as a specification and use it in your TransferText command, without supplying a separate CodePage parameter.
-28342258 0 Bootstrap works on one server but not another in IE8I am using http://www.keenthemes.com/preview/metronic/theme/templates/admin3/ui_colors.html as a theme/template.
Here's my code
<!DOCTYPE html> <!--[if IE 8]> <html lang="en" class="ie8 no-js"> <![endif]--> <!--[if IE 9]> <html lang="en" class="ie9 no-js"> <![endif]--> <!--[if !IE]><!--> <html lang="en"> <!--<![endif]--> <!-- BEGIN HEAD --> <head> <meta charset="utf-8" /> <title>Home</title> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta content="width=device-width, initial-scale=1.0" name="viewport" /> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <meta content="" name="description" /> <meta content="" name="author" /> <!-- BEGIN GLOBAL MANDATORY STYLES --> <link href="https://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700&subset=all" rel="stylesheet" type="text/css"> <link href="/assets/global/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link href="/assets/global/plugins/simple-line-icons/simple-line-icons.min.css" rel="stylesheet" type="text/css"> <link href="/assets/global/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css"> <link href="/assets/global/plugins/uniform/css/uniform.default.css" rel="stylesheet" type="text/css"> <!-- END GLOBAL MANDATORY STYLES --> <!-- BEGIN THEME STYLES --> <link href="/assets/global/css/components.css" rel="stylesheet" type="text/css"> <link href="/assets/global/css/plugins.css" rel="stylesheet" type="text/css"> <link href="/assets/admin/layout3/css/layout.css" rel="stylesheet" type="text/css"> <link href="/assets/admin/layout3/css/themes/default.css" rel="stylesheet" type="text/css" id="style_color"> <link href="/assets/admin/layout3/css/custom.css" rel="stylesheet" type="text/css"> <!-- END THEME STYLES --> <link rel="shortcut icon" href="favicon.ico" /> </head> <!-- END HEAD --> <!-- BEGIN BODY --> <!-- DOC: Apply "page-header-menu-fixed" class to set the mega menu fixed --> <!-- DOC: Apply "page-header-top-fixed" class to set the top menu fixed --> <body class="page-header-menu-fixed"> <!-- BEGIN HEADER --> <div class="page-header"> <!-- BEGIN HEADER TOP --> <div class="page-header-top" style="height:150px !important;"> <div class="container"> <!-- BEGIN TOP NAVIGATION MENU --> <div class="top-menu"> <h1>Health Intelligence Portal</h1> <h4>Central Southern Commissioning Support Unit</h4> <!--#include virtual="/inc/top-menu-live.inc"--> </div> <!-- END TOP NAVIGATION MENU --> <!-- BEGIN RESPONSIVE MENU TOGGLER --> <a href="javascript:;" class="menu-toggler"></a> <!-- END RESPONSIVE MENU TOGGLER --> <!-- BEGIN LOGO --> <div class="page-logo"> <a href="index.html"><img src="assets/global/img/central-southern-logo.png" alt="logo" class="logo-default"> </a> </div> <!-- END LOGO --> </div> </div> <!-- END HEADER TOP --> <!-- BEGIN HEADER MENU --> <div class="page-header-menu"> <div class="container"> <!-- BEGIN HEADER SEARCH BOX --> <form class="search-form" action="extra_search.html" method="GET"> <div class="input-group"> <input type="text" class="form-control" placeholder="Search" name="query"> <span class="input-group-btn"> <a href="javascript:;" class="btn submit"><i class="icon-magnifier"></i></a> </span> </div> </form> <!-- END HEADER SEARCH BOX --> <!-- BEGIN MEGA MENU --> <!--#include virtual="/inc/mega-menu-live.inc"--> <!-- END MEGA MENU --> </div> </div> <!-- END HEADER MENU --> </div> <!-- END HEADER --> <!-- BEGIN PAGE CONTAINER --> <div class="page-container"> <!-- BEGIN PAGE HEAD --> <div class="page-head"> <div class="container"> <!-- BEGIN PAGE TITLE --> <div class="page-title"> <h1>Welcome to the CSCSU Health Intelligence Portal</h1> </div> <!-- END PAGE TITLE --> </div> </div> <!-- END PAGE HEAD --> <!-- BEGIN PAGE CONTENT --> <div class="page-content"> <div class="container"> <!-- BEGIN PAGE CONTENT INNER --> <div class="row"> <div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"> <a href="javascript:;"> </p> <div class="dashboard-stat blue-madison"> <div class="visual"> <i class="fa fa-check"></i> </div> <div class="details"> <div class="number"> Self Service Portal </div> <div class="desc"> Log Calls </div> </p> </div> </p> </div> <p> </a> </div> <div class="col-lg-4 col-md-4 col-sm-6 col-xs-12" style="z-index:1 !important;"> <a href="javascript:;"> </p> <div class="dashboard-stat blue-madison" style="z-index:0"> <div class="visual"> <i class="fa fa-file-pdf-o"></i> </div> <div class="details"> <div class="number"> I.T. Forms </div> </p> </div> </p> </div> <p> </a> </div> <div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"> <a href="javascript:;"> </p> <div class="dashboard-stat blue-madison"> <div class="visual"> <i class="fa fa-video-camera"></i> </div> <div class="details"> <div class="number"> User Guides & Videos </div> </p> </div> </p> </div> <p> </a> </div> </div> <div class="row"> <div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"> <a href="javascript:;"> </p> <div class="dashboard-stat blue-madison"> <div class="visual"> <i class="fa fa-file-pdf-o"></i> </div> <div class="details"> <div class="number"> I.T Policies </div> </p> </div> </p> </div> <p> </a> </div> <div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"> <a href="javascript:;"> </p> <div class="dashboard-stat blue-madison"> <div class="visual"> <i class="fa fa-signal"></i> </div> <div class="details"> <div class="number"> Guest Wifi Details </div> </p> </div> </p> </div> <p> </a> </div> <div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"> <a href="javascript:;"> </p> <div class="dashboard-stat blue-madison"> <div class="visual"> <i class="fa fa-clock-o"></i> </div> <div class="details"> <div class="number"> Opening Hours </div> </p> </div> </p> </div> <p> </a> </div> </div> <div class="row"> <div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"> <a href="javascript:;"> </p> <div class="dashboard-stat blue-madison"> <div class="visual"> <i class="fa fa-phone"></i> </div> <div class="details"> <div class="number"> Contact Us </div> </p> </div> </p> </div> <p> </a> </div> <div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"> <a href="javascript:;"> </p> <div class="dashboard-stat blue-madison"> <div class="visual"> <i class="fa fa-support"></i> </div> <div class="details"> <div class="number"> Remote Support </div> </p> </div> </p> </div> <p> </a> </div> <div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"> <a href="javascript:;"> </p> <div class="dashboard-stat blue-madison"> <div class="visual"> <i class="fa fa-users"></i> </div> <div class="details"> <div class="number"> About Us </div> </p> </div> </p> </div> <p> </a> </div> </div> <!-- END PAGE CONTENT INNER --> </div> </div> <!-- END PAGE CONTENT --> </div> <!-- END PAGE CONTAINER --> <!-- BEGIN PRE-FOOTER --> <!--#include virtual="/inc/footer-live.inc"--> <!-- END PRE-FOOTER --> <!-- BEGIN FOOTER --> <div class="page-footer"> <div class="container"> 2014 © CSCSU. All Rights Reserved. </div> </div> <div class="scroll-to-top"> <i class="icon-arrow-up"></i> </div> <!-- END FOOTER --> <!-- BEGIN JAVASCRIPTS(Load javascripts at bottom, this will reduce page load time) --> <!-- BEGIN CORE PLUGINS --> <!--[if lt IE 9]> <script src="/assets/global/plugins/respond.min.js"></script> <script src="/assets/global/plugins/excanvas.min.js"></script> <![endif]--> <script src="/assets/global/plugins/jquery-1.11.0.min.js" type="text/javascript"></script> <script src="/assets/global/plugins/jquery-migrate-1.2.1.min.js" type="text/javascript"></script> <!-- IMPORTANT! Load jquery-ui-1.10.3.custom.min.js before bootstrap.min.js to fix bootstrap tooltip conflict with jquery ui tooltip --> <script src="/assets/global/plugins/jquery-ui/jquery-ui-1.10.3.custom.min.js" type="text/javascript"></script> <script src="/assets/global/plugins/bootstrap/js/bootstrap.min.js" type="text/javascript"></script> <script src="/assets/global/plugins/bootstrap-hover-dropdown/bootstrap-hover-dropdown.min.js" type="text/javascript"></script> <script src="/assets/global/plugins/jquery-slimscroll/jquery.slimscroll.min.js" type="text/javascript"></script> <script src="/assets/global/plugins/jquery.blockui.min.js" type="text/javascript"></script> <script src="/assets/global/plugins/jquery.cokie.min.js" type="text/javascript"></script> <script src="/assets/global/plugins/uniform/jquery.uniform.min.js" type="text/javascript"></script> <!-- END CORE PLUGINS --> <script src="/assets/global/scripts/metronic.js" type="text/javascript"></script> <script src="/assets/admin/layout3/scripts/layout.js" type="text/javascript"></script> <script src="/assets/admin/layout3/scripts/demo.js" type="text/javascript"></script> <script> jQuery(document).ready(function() { Metronic.init(); // init metronic core components Layout.init(); // init current layout }); </script> <!-- END JAVASCRIPTS --> </body> <!-- END BODY --> </html>
When saved on Server 1, it works fine as shown below in all browsers, and specifically IE8
Now, the exact same code on Server 2 shows the following for IE8 only. Please not just two columns and the search box acting up.
Developer tools in Chrome and Firefox show no errors. No missing files. No nothing. I got the assets on Server 1 to point to Server 2. Still worked. I got the assets on Server 2 to point to the assets on Server 1, still broken.
Any ideas? Exact same code, on the exact same server setup (Windows 2008 R2). With that said, could IIS be doing something?
-41051628 0I'm pretty sure you could just go over it to find out why this is happening. You could simply try to debug it, go through everything carefully and make sure everything works. With problems I encounter like that, I like to add excessive things to it, and then slowly whittle it down to where it works.
So, to sum it up, in your case, just to make sure, simply try str()
to start with, and continue debugging from there.
MySQL is awfully lax when it comes to the GROUP BY
-clause. In MySQL, you can add columns to your select clause that are not in the GROUP BY
or an aggregate functions. Other RDBMS do not allow this, as it makes no sense semantically. MySQL just returns more or less random row values that fit the given query.
From the MySQL Doc
In standard SQL, a query that includes a GROUP BY clause cannot refer to nonaggregated columns in the select list that are not named in the GROUP BY clause. [...] MySQL extends the use of GROUP BY so that the select list can refer to nonaggregated columns not named in the GROUP BY clause.
What you have to do is, find out what the query is supposed to do and rewrite it.
-7663818 0 How to reference JSF managed beans which are provided in a JAR file?I have a WAR file with the following structure:
The JSF managed bean BusinessObjectTypeListController
is located in commons-web-1.0.jar
in /WEB-INF/lib
and referenced in BusinessObjectTypeListView.xhtml
. When I run my web application and I call that view, I get the following error:
javax.servlet.ServletException: /view/common/businessObjectTypeListView.xhtml @34,94 listener="#{businessObjectTypeListController.selectData}": Target Unreachable, identifier 'businessObjectTypeListController' resolved to null
Why isn't the controller class found? It should be in the classpath, is it?
-32368788 0 Filter NSDictionary from NSArrayI have One NSArray That contains NSDictionary Object with keys{"name","age","weight"} where the key name is NSString ,age is NSInteger ,weight is float Value
I need to filter the NSArray with the following conditions 1.name contains 'abc' 2.age below 18 3.weight less than 50
Answer will be Appreciated
-37689599 0Is using proxies a hard requirement? I wouldn't recommend proxies for general programming tasks as you can end up with unpredictable and hard-to-spot side effects.
If you keep to data and functions to transform it, avoiding mutable state where possible, I think you'll end up with simpler code that's easier to maintain.
var activities = ['reading', 'swimming']; var sfilter = function(activities){ return activities.filter(function(v){ return v[0] === 's'; }); }; console.log(sfilter(activities)); var memap = function(activities){ return activities.map(function(v){ return 'I am ' + v; }); }; console.log(memap(activities)); activities.push('smiling'); console.log(sfilter(activities)); console.log(memap(activities)); // Yes, I know this doesn't work in quite the same way, // but you're asking for trouble here since in your // code you're appending to one list, but overwriting // an element in the other. activities[1] = 'snoopying'; console.log(sfilter(activities)); console.log(memap(activities));
Stick to a Single Source of Truth and observe that. With each copy you are multiplying state complexity. That will make debugging, testing, and extending the code difficult.
-37348669 0The IQueryable Where takes an Expression<Func<TSource, bool>>
, NOT a Func<TSource, bool>
, so a different overload of Where is being called, causing the query to execute and the result to be returned as an IEnumerable instead of an IQueryable.
public static IQueryable<TSource> Where<TSource>( this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate )
Pass your Func as an Expression and you should get the desired behavior.
-22555229 07d1bad12 is a Hex string and not your normal string. I assume you gave a delete request and shortly you logged into the system and saw your VPC still existing. VPC deletion is a time consuming process and it takes time before your VPC is deleted. When the API says it returned successfully it means that the SDK was able to send the delete request successfully and this delete request is asynchronous and therefore, it returns immediately. If your VPC was empty then after some time it should go away from the AWS console.
-22259286 0 C++: Using a Stack to Verify if Parentheses are Balanced (Logic error)I have a simple stack I created with basic initialize, show, push, pop, top, etc. functions. I need a function to verify whether or not a string has matching parentheses. I think I'm pretty close, but I have a problem with the following: if (s.size == 0 && c == ')') in the middle of my balanced function.
This condition should be met by string "s1" with the parenthesis just prior to the division sign, but it is not...It is still returning true.
Thanks for looking.
#include <iostream> #include <string> #include <stdlib.h> using namespace std; struct Stack{ static const unsigned MAX_SIZE = 5; char data[ MAX_SIZE ]; unsigned size; }; void initialize( Stack & stack ); void show( const Stack & stack ); unsigned getSize( const Stack & stack ); void push( Stack & stack, char c ); char pop( Stack & stack ); char top( const Stack & stack ); bool die( const string & msg ); bool balanced (const string & expr); int main(){ string s1 = "X*((4+(3-2)/(Y+X))+(Z-8))) / ((A+(B-2))"; string s2 = "())"; string s3 = "(()"; cout << balanced(s1) << endl; cout << balanced(s2) << endl; cout << balanced(s3) << endl; } void initialize( Stack & stack ){ stack.size = 0; } void show( const Stack & stack ){ cout <<"[" << stack.size <<"]:"; for( unsigned i = 0; i < stack.size; i++ ) cout <<stack.data[i]; cout <<endl; } // show unsigned getSize( const Stack & stack ) {return stack.size;} void push( Stack & stack, char c ){ if( stack.size == Stack::MAX_SIZE ) die( "push: overflow" ); stack.data[stack.size++] = c; } // push char pop( Stack & stack ){ if( stack.size == 0 ) die( "pop: underflow" ); return stack.data[--stack.size]; } // pop char top( const Stack & stack ){ if( stack.size == 0 ) die( "top: underflow" ); return stack.data[stack.size-1]; } // top bool die( const string & msg ){ cerr <<endl <<"Fatal error: " << msg <<endl; exit( EXIT_FAILURE ); } bool balanced (const string & expr){ Stack s; initialize(s); for (unsigned i = 0; i < expr.size(); i++){ char c = expr[i]; if (c == '(') { if( expr.size() == Stack::MAX_SIZE ) { die( "push: overflow" ); } push(s, c); } if (s.size == 0 && c == ')') { return false; } else if (c == ')'){ pop(s); } if (s.size == 0){ return true; } else return false; } }
-35703569 0 The image you've shown is probably a UISegmentedControl. That's how you tap something so that it stays selected (and other choices are deselected). It's easy to customize a segmented control so that the background image is different when a segment is selected vs. when it is not.
-14217416 0StackOverflowException
is usually caused by some method which invokes itself endlessly.
The fact that it occurs after some time makes me even more adamant about it: you're facing infinite recursion.
An extremely simple example of this behavior would be:
void SomeMethod() { SomeMethod(); // StackOverflowException }
-38023773 0 Assigning more than one video file to an id in rails Am working on a video application where the app in rails receive video files from different user. The videos are sent individually not multiple upload. Am trying to make a user to me able to store more than one video in the same row. for example. if a user has uploaded a video before( say video1), if the same user( with same id) upload another video, i want to update the existing video field( video1, video2 or something similar). I don't want to create another row for the same user. In summary i want to link a user to more than one video submission without adding a new row. Am currently using carrierwave gem
, how can i achieve this
class Submission < ActiveRecord::Base mount_uploader :videos, VideoUploader end
video field above
submit = Submission.find(8) #asumming 8 is the id of the same user submit.videos = params[:videos] #new parameter coming in
was also thinking of concantenating both the old valid and new valid seperated by a comma, but don't know how to handle that when calling the field.
-1705191 0You have several options, and it really depends on what you are trying to get the system to do.
Im trying to update a record with a HQL query but I am getting a CastException
. If anyone could help me out I would really appreciate it. I have checked the Internet for a while now but I cant find any information on this. Please let me know if you have more information on this exception.
The full error message its returning:
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: org.hibernate.hql.ast.tree.SqlNode cannot be cast to org.hibernate.hql.ast.tree.FromReferenceNode at org.hibernate.hql.ast.HqlSqlWalker.generateSyntheticDotNodeForNonQualifiedPropertyRef(HqlSqlWalker.java:495) at org.hibernate.hql.ast.HqlSqlWalker.lookupNonQualifiedProperty(HqlSqlWalker.java:488) at org.hibernate.hql.antlr.HqlSqlBaseWalker.propertyRef(HqlSqlBaseWalker.java:1102) at org.hibernate.hql.antlr.HqlSqlBaseWalker.assignment(HqlSqlBaseWalker.java:1008) at org.hibernate.hql.antlr.HqlSqlBaseWalker.setClause(HqlSqlBaseWalker.java:729) at org.hibernate.hql.antlr.HqlSqlBaseWalker.updateStatement(HqlSqlBaseWalker.java:349) at org.hibernate.hql.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:237) at org.hibernate.hql.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:228) at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:160) at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:111) at org.hibernate.engine.query.HQLQueryPlan.(HQLQueryPlan.java:77) at org.hibernate.engine.query.HQLQueryPlan.(HQLQueryPlan.java:56) at org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:72) at org.hibernate.impl.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:133) at org.hibernate.impl.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:112) at org.hibernate.impl.SessionImpl.createQuery(SessionImpl.java:1623) at Database.HibernateConnection.updateFlight(HibernateConnection.java:161) at Controller.Controller.ChangeFlight(Controller.java:527) at View.CreateChangeFlightView.btnSaveActionPerformed(CreateChangeFlightView.java:738) at View.CreateChangeFlightView.access$1000(CreateChangeFlightView.java:45) at View.CreateChangeFlightView$6.actionPerformed(CreateChangeFlightView.java:299) at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995) at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318) at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387) at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242) at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236) at java.awt.Component.processMouseEvent(Component.java:6263) at javax.swing.JComponent.processMouseEvent(JComponent.java:3267) at java.awt.Component.processEvent(Component.java:6028) at java.awt.Container.processEvent(Container.java:2041) at java.awt.Component.dispatchEventImpl(Component.java:4630) at java.awt.Container.dispatchEventImpl(Container.java:2099) at java.awt.Component.dispatchEvent(Component.java:4460) at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4574) at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238) at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168) at java.awt.Container.dispatchEventImpl(Container.java:2085) at java.awt.Window.dispatchEventImpl(Window.java:2478) at java.awt.Component.dispatchEvent(Component.java:4460) at java.awt.EventQueue.dispatchEvent(EventQueue.java:599) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161) at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
query: deleted
-24807189 0Well, looks like it just enough to move you Cache logic to the ChannelInterceptor
:
<int:channel id="tcpInbound"> <int:interceptors> <bean class="com.my.proj.si.CachePutChannelInterceptor" </int:interceptors> </int:channel>
And use this interceptor from any place when you need to use Cache.
-40314237 0 Progress Bar with Ajax JQuery and PHP for import a .csv file to MySQLI tried to write a code for a progress bar using PHP, JQuery and HTML. So, I made a Ajax Request for a PHP file and in the success
Ajax parameter I search a data
requested from PHP File like this..
success: function(data){ if(data == 'Error1'){ alert("The File is not a .csv"); }else if(data == "Error2"){ alert("Please select a file to import!"); }else{ $('#consumidor_table').html(data); alert("The importation has been made!"); } }
That else
does print a Table with MySql DB lines. The PHP file read a .csv from a HTML input and insert those lines in DB.
Actually, my code to do a progress bar is it: Before at success parameter
xhr: function(){ var xhr = new window.XMLHttpRequest(); xhr.upload.addEventListener("progress", function(evt){ if (evt.lengthComputable) { var percentComplete = evt.loaded / evt.total; console.log(evt.loaded); console.log(evt.total); console.log(percentComplete*100); addProgress(percentComplete*100); } }); return xhr; },
The entire codes: JQuery; PHP URL
The Error: When a upload a file and submit the form, the console.log(evt.total);
and console.log(evt.loaded);
print the same value, and them the progress bar is fully, but the Ajax continues requesting the PHP file and my table is empty yet.
So what I can do to my progress bar work with the response from PHP file?
-33532587 0Change
<div id="dateBox"> Today Beer Style is: <script> document.getElementById("dateBox").innerHTML=style[new Date().getUTCDate()]; </script> </div>
to:
<div id="dateBox"> Today Beer Style is: <span id="beerStyle"></span> <script> document.getElementById("beerStyle").innerHTML=style[new Date().getUTCDate()]; </script> </div>
-16270510 0 It sounds like you're not trying to do huffman coding yet, just turn "binary" String
s of 0
or 1
into Java integer types. Try this:
public static long decode(String textbytes) { long result=0; for(char ch : textbytes.toCharArray()) { result = result << 1; if(ch == '1') result = result + 1; } return result; }
This method decodes bit strings into Java long
s. There's no need to worry about breaking into chunks of 8 (unless this is homework, and that's part of the assignment). In particular, it handles the example you gave properly ("11010001" => 209).
The approach is pretty simple:
result = 0
result
1 bit to the left to "make room" for the bit represented by the current character. Afterwards, add 1
to result if the current character represents a 1
bit.Also, the code assumes you get no bit strings longer than 64 bits, which you may want to check for robustness.
-28075373 0Here's the corresponding docs for testing iphone/ipad: https://github.com/angular/protractor/blob/master/docs/mobile-setup.md#setting-up-protractor-with-appium---iossafari
I would suggest you test using a local device first if sauce doesn't work for you at first try, so you can narrow down the issue (unless you don't have a mac or physical ipad to test with that is).
-39769729 0Might try wrapping in Begin and End Latex's like this:
* This is a heading #+Begin_Latex \pagebreak #+End_Latex * Second heading
-7908699 0 The memory usage of a two dimensional array is slightly bigger, but this may result from bad code (?).
<!-- http://php.net/manual/en/function.memory-get-usage.php array1: 116408 (1D 1001 keys) (1x 100.000 keys: 11.724.512) array2: 116552 (2D, 1002 keys) (2x 50.000 keys: 11.724.768) total: +144 +256 --> <?php function genRandomString() { $length = 10; $characters = '0123456789abcdefghijklmnopqrstuvwxyz'; $string = ''; for ($p = 0; $p < $length; $p++) { $string .= $characters[mt_rand(0, strlen($characters))]; } return $string; } $i = 0; // ----- Larger 1D array ----- $mem_start = memory_get_usage(); echo "initial1: " . $mem_start . "<br />"; $arr = array(); for ($i = 1; $i <= 1000; $i++) { $arr[ genRandomString() ] = "Hello world!"; } echo "array1: " . (memory_get_usage() - $mem_start) . "<br />"; unset($arr); // ----- 2D array ----- $mem_start = memory_get_usage(); $arr2 = array(); echo "initial2: " . $mem_start . "<br />"; for ($i = 1; $i <= 500; $i++) { $arr2["key______1"][ genRandomString() ] = "Hello world!"; $arr2["key______2"][ genRandomString() ] = "Hello world!"; } echo "array2: " . (memory_get_usage() - $mem_start) . "<br />"; unset($arr2); unset($i); unset($mem_start) echo "final: " . memory_get_usage() . "<br />"; ?>
-2162851 0 bool hasDuplicates = myObjectList.Count > new HashSet<int>(myObjectList.Select(x => x.Order)).Count;
-40586241 0 This isn't an answer but it is too long for a comment: sorry.
There are three possibilities for creating variable bindings that seem to be common:
An example of (3) is Python. Languages which do this end up needing explicit scope-resolution operators (global
and now nonlocal
in Python) to deal with the stupid, lazy, pun they have done and are not worth discussing further: you need binding constructs which are distinct from assignment or you end up living in pain for ever.
Common Lisp is an example of (1), and C used to be: they are both (C was) examples of languages where all the bindings needed to be created at the start of a scope construct.
Within (1) there are languages which have some kind of block construct ({
... }
in C) which can be used for grouping and for scope, and ones which have a grouping construct and one or more separate scoping constructs: CL is in the latter family.
So in (old) C you would say
{ int i = 3; ... }
While in CL you say
(let ((i 3)) ...)
-- the scope construct here is let
(and there are others of course).
Of course, CL, being a Lisp, can perfectly happily invent a construct which looks like C's blocks:
(defmacro scope (&body vars/body) (loop for (var? . body?) on vars/body while (and (listp var?) (<= 2 (length var?) 3) (eql (first var?) 'var) (symbolp (second var?))) collect (case (length var?) (2 (second var?)) (3 (rest var?))) into bindings finally (return `(let* ,bindings ,var? ,@body?))))
And now
(scope (var a) (var b 2) ...)
is a construct in the language.
So really these two variants on (1) are more similar than they are different: it's just a matter of how you cut up the underlying constructs you want in the language: C conflated scope blocks and grouping, CL doesn't.
(2) is different however. Here you are allowed to intermingle binding constructs and other things within a scope construct. C is now like this, and so is JavaScript. CL is not like this natively (obviously, being a Lisp, it could become like this with some macrology, although that macrology would be a lot hairier than what I wrote above).
In such a language you really need a separate binding-creation construct, because it can't be part of the scoping construct. Languages like C already treat the binding-creation construct as separate, so for them it's just a matter of relaxing the rule which says bindings must all be created at the start of a scope construct.
Languages like this have a significant question to answer though: what is the scope of a binding? Does something like
{ ... int x = 3; ... }
Really mean
{ ... { int x = 3; ... } }
or does it mean
{ int x; ... x = 3; ... }
The latter case is easier, but means that there's an awkward region where references to x
are legal but its value may not be well-defined. C takes the former interpretation I think.
This is mostly fine for languages like C where the grouping construct is the same as the scoping construct. But it's not fine for languages like JavaScript where the grouping construct is not the scoping construct and, worse, where there is no scoping construct other than functions (or used not to be). And in fact languages like that can't really fix the problem, since there's no useful scoping construct. Well, of course, they fix it by growing a scoping construct.
Note that although CL is a (1) language there are Lisp-family languages which are (2) languages: in particular Racket is. In Racket (but not, I think, in Scheme) you can say
(define (foo) (define bar 1) ;; is baz bound here? (display bar) (define baz 3) (list bar baz))
And the answer is that yes, baz
is bound there, but it's bound to an undefined object and you'll get an error (at run time, not compile time) if you try to use it. So this is a run-time error:
(define (foo) (define bar 1) (display baz) (define baz 3) (list bar baz))
while this
(define (foo) (define bar 1) (display baz) (let () (define baz 3) (list bar baz)))
is a compile time error. (I am actually slightly confused about which constructs in Racket create scopes.)
-21792980 0Generally speaking, yes.
You can get type of class with typeof(YourClassHere)
or type of object with yourObject.GetType()
.
Then you can easily create object with an acitvator: Activator.CreateInstance(type, parameters for constructor)
EDIT AFTER QUESTION EDIT It's even easier when you have the generic.
public void DoWork<TClass>(int time) { IJobDetail job = (IJobDetail) Activator.CreateInstance(typeof(TClass), null /* no parameters */); job.WithIdentity("job1", "group1"); job.Build(); }
-39794903 0 The function that upcases the previous word is
(defun upcase-previous-word () (interactive) (upcase-word -1))
If you want more information on function upcase-word
, try M-x describe-function
then upcase-word
. This assigns M-u
to it
(global-set-key (kbd "M-u") 'upcase-previous-word)
-9892773 0 yeah why dont use filter_var,
filter_var ($isEmail, FILTER_VALIDATE_EMAIL);
And eregi (Posix Regex) has been deprecated as PHP 5.3.0. php-manual
-10404050 1 Scipy: Convert RGB TIFF to grayscale TIFF and output it on MatplotlibI want to manipulate RGB bands in a TIFF file and output the grayscale map on matplotlib. So far I have this code, but I couldn't get it on grayscale:
import scipy as N import gdal import sys import matplotlib.pyplot as pyplot tif = gdal.Open('filename.tif') band1 = tif.GetRasterBand(1) band2 = tif.GetRasterBand(2) band3 = tif.GetRasterBand(3) red = band1.ReadAsArray() green = band2.ReadAsArray() blue = band3.ReadAsArray() gray = (0.299*red + 0.587*green + 0.114*blue) pyplot.figure() pyplot.imshow(gray) pylab.show()
And these are the arrays:
[[255 255 255 ..., 237 237 251] [255 255 255 ..., 237 237 251] [255 255 255 ..., 237 237 251] ..., [237 237 237 ..., 237 237 251] [237 237 237 ..., 237 237 251] [242 242 242 ..., 242 242 252]] [[255 255 255 ..., 239 239 251] [255 255 255 ..., 239 239 251] [255 255 255 ..., 239 239 251] ..., [239 239 239 ..., 239 239 251] [239 239 239 ..., 239 239 251] [243 243 243 ..., 243 243 252]] [[255 255 255 ..., 234 234 250] [255 255 255 ..., 234 234 250] [255 255 255 ..., 234 234 250] ..., [234 234 234 ..., 234 234 250] [234 234 234 ..., 234 234 250] [239 239 239 ..., 239 239 251]]
Any idea how can I fix this?
-29692418 0Modulus is not using the 3
, it simply knows that:
20 / 6 = 3, with a remainder of 2 => 20 % 6 = 2
If you want the 3
, you just need the expression:
Math.floor(20 / 6)
(or possibly Math.trunc
depending on how you want negative numbers handled - floor
rounds towards negative infinity, trunc
rounds toward zero).
I believe this solves your problem.
DECLARE @command nvarchar(max) = 'SELECT CASE WHEN ( SELECT COUNT(*) FROM [table] WITH ( NOLOCK ) WHERE DATEDIFF(minute, systemupdatedtimestamp, GETDATE()) < 10 ) > 0 THEN 0 ELSE 1 END' exec sp_executesql @command
-1606141 0 It is actually possible to run multiple delayed_job workers.
From http://github.com/collectiveidea/delayed_job:
# Runs two workers in separate processes. $ RAILS_ENV=production script/delayed_job -n 2 start $ RAILS_ENV=production script/delayed_job stop
So, in theory, you could just execute:
$ RAILS_ENV=production script/delayed_job -n 50 start
This will spawn 50 processes, however I'm not sure whether that would be recommended depending on the resources of the system you're running this on.
An alternative option would be to use threads. Simply spawn a new thread for each of your jobs.
One thing to bear is mind with this method is that ActiveRecord
is not thread-safe. You can make it thread-safe using the following setting:
ActiveRecord::Base.allow_concurrency = true
-22440303 0 Webbrowser control in C# weird behavior I'm finishing (QA testing) a web parser built in C# that is parsing specific data from a web site that is being load to a webbrowser control in a WFA (Windows Form Application) program.
The weird behavior is when I'm killing the internet connection... Actually the program is designed to navigate recursively in the site and each step its waiting for a WebBrowserDocumentCompletedEventHandler
to be triggered. Beside that there is a Form timer set, and if the handler is not triggered in a specific interval then its reloading the entire procedure.
Everything is working good even if I manually avoid the handler from triggering - As I said the timer kicks in and restart the operation successfully and retrying another value successfully.
When shutting the internet connection manually while the procedure is running, I can see the page is getting the internet explorer message: "This page can't be displayed" (For some reason the DocumentComplete... is not triggered). Then immediately reconnecting the internet and waiting for the timer to kick in - As expected it fires the reload function but this time everything is going wild!! the functions are being fired not in the correct order and it seems like there is 100 threads that are running at the same time - a total chaos.
I know that its not easy to answer this question without experiencing that and seeing the code But if I copy the entire code it will be just too long using 5 different classes and I really can't see where is the problem... I'll try to simplify the question:
Thanks
-34647190 0 Cast a IQueryable type to interface in Linq to EntitiesI have the following method in my generic class:
// This is the class declaration public abstract class BaseService<TEntity, TKey> : IBaseService<TEntity, TKey> where TEntity : class, IEntity<TKey> // The Method public IQueryable<TEntity> GetActive() { if (typeof(IActivable).IsAssignableFrom(typeof(TEntity))) { return this.repository.Get().Cast<IActivable>() .Where(q => q.Active) .Cast<TEntity>(); } else { return this.Get(); } }
This is the interface:
public interface IActivable { bool Active { get; set; } }
Basically, TEntity
is an Entity (POCO) class, that can implement IActivable if they have Active
property. I want to the method to return all records that have Active
value true. However, I have this error:
Unable to cast the type 'WebTest.Models.Entities.Product' to type 'Data.IActivable'. LINQ to Entities only supports casting EDM primitive or enumeration types.
I understand why this error occurs. But the articles on SO does not have any valid solution for my case. Is it achievable with Cast
, or any other way? Note: I do not want to convert to IEnumerable
, I want to keep IQueryable
.
My main htaccess file does a bunch of things for my site to function correctly. I have added redirects for pages that have moved. I don't have root access to the server and using .htaccess is my only option.
Is it possible to include separate files for the redirects in the .htaccess file so I can keep them separate and write programatically to the additional files that hold my redirects?
Basically I want to reference separate files from my .htaccess to manage rules dynamically and also neaten up one long .htaccess file with a few smaller files.
I also want to add redirect rules on the fly as things change on the site within my application.
-22968014 0 Optimizing button.titleLabelI am optimizing my app on iPhone 4, it's really fast on iPhone 5 but lagging a little on iPhone 4. Using instrument Time Profiler, I found that 30% of the time is spent on [UIButton titleLabel], it seems huge for a UIKit simple task I am calling several times button.titleLabel.font and [button.titleLabel setFont:font]; but I don't see why using pointers would take so long. How would you optimise this? My app is using autolayout.
edit: it seems most of the performance goes into calling UIButton.titleLabel which triggers autolayout constraint calculation
-1989628 0 How can I find the index of a row for a value in excel Éis there a function in excel which can find the index of the row for a particular value É
ie if I write function(5.77) it will return 5 , because 5.77 appears in row 5 .
'1 Frequency '2 4.14 '3 4.19 '4 5.17 '5 5.77 '6 6.39
-35048791 0It is possible to inherit from stream.Stream
and make it work, however based on what's available in the documentation I would suggest inheriting from stream.Writable
. Piping into a stream.Writable
you'll need to have _write(chunk, encoding, done)
defined to handle the piping. Here is an example:
var asset = new ProjectAsset('myFile', __dirname + '/image.jpg') var stream = fs.createReadStream(__dirname + '/image.jpg', { encoding: 'base64' }).pipe(asset) stream.on('finish', function() { console.log(asset.binaryData); })
Project Asset
'use strict' var stream = require('stream'), util = require('util') var ProjectAsset = function() { var self = this self.data self.binaryData = []; stream.Writable.call(self) self._write = function(chunk, encoding, done) { // Can handle this data however you want self.binaryData.push(chunk.toString()) // Call after processing data done() } self.on('finish', function() { self.data = Buffer.concat(self.binaryData) }) return self } util.inherits(ProjectAsset, stream.Writable) module.exports = ProjectAsset module.exports.DEFAULT_FILE_NAME = 'file'
If you're looking to also read from the stream
, take a look at inheriting from stream.Duplex
and also including the _read(size)
method.
There's also the simplified constructors api if you're doing something simpler.
-39667826 0 Setting a cookie in Django Rest Framework APII am trying to set a cookie on my website when a GET request is made to an API end-point.
In my urls.py, I have this:
url(r'^api/cookies/$', views.cookies, name='cookies'),
which points to this view:
@api_view(['GET']) def cookies(request): if request.method == 'GET': response = HttpResponse('Setting a cookie') response.set_cookie('cookie', 'MY COOKIE VALUE') if 'cookie' in request.COOKIES: value = request.COOKIES['cookie'] return Response('WORKS') else: return Response('DOES NOT WORK')
In other words, when this view is loaded through a GET method, I am setting a cookie. If the cookie is set properly, I return 'WORKS', otherwise, I return 'DOES NOT WORK'.
Now, I am sending a GET request to this URL, and I get 'DOES NOT WORK', which means the cookie is not set properly. What am I doing wrong? How can I fix this? Note: I am using Django Rest Framework for my views.
-35952586 0 Sorting linked list by sorting the actual nodes and not just by swapping node valuesI want to sort my linked list so that the nodes are arranged in the sorted order. I have looked up several algorithms, but they all swap the data values and not the actual node itself. Does anyone know where I can find some code on how to swap the nodes themselves and not just the values?
-38448908 0 add another background image to change background during playing gamefunc createBackgrounds() { for i in 0...2 { let bg = SKSpriteNode(imageNamed: "BG Day") bg.name = "BG" bg.zPosition = 0; bg.anchorPoint = CGPoint(x: 0.5, y: 0.5) bg.position = CGPoint(x: CGFloat(i) * bg.size.width, y: 0) self.addChild(bg) } }
If I want to add another background image after 2 minutes to BG Night
, how can I write coding in swift 2?
I have this javascript code:
$(document).ready(function(){ $("#EstadoId").change(function(){ listaCidade($(this).val()); }); }); function listaCidade(uf) { $.getJSON("@Url.Action("ListaCidade")/" + uf, listaCidadeCallBack); } function listaCidadeCallBack() { alert('sucesso'); }
Everything is working...getJSON is calling my action "ListaCidade" but it isnt calling my "listaCidadeCallBack".
The result of the Action is
public ActionResult ListaCidade(int id) { var cidades = from c in ctx.Cidades where c.Estado.ID == id select c; return Json(cidades); }
-27360382 0 You can use so-called keyword-messages. You end a method with a colon and put the variable name after that (probably multiple times).
So if you have something like methodFoo(a, b, c)
in a curly-brace language, in Smalltalk you typically write
methodFoo: a withSomething: b containing: c
or likewise. This can make method names more readable, too!
Also, getters and setter in Smalltalk typically are named after the variable they are representing. (And classes are typically capitalized while variables are not)
So your example would turn into
Object subclass: Test [ | testvar | testvar: anObject [ testvar := anObject. ] testvar [ ^testvar ] ]. test := Test new. test testvar: 'my value'. test testvar print. " prints 'my value' "
-30860640 0 File deleted before downloaded in Ajax call in Asp.net MVC I am generating a excel file by using the Ajax call to my Action in my controller class in my ASP.net MVC application.Its working fine but the problem occures some time when my file is in downloading stage and the ajax call delete it.If there is any way without SetTimeout then please tell me.
Generate Excel File
$.ajax({ url: "@Url.Action("GenerateReport", "ClientAdmin")", type: "POST", data: { reportStart: reportStart, reportEnd: reportEnd}, dataType: "json", traditional: true, success: function (downloadUrl) { //Download excel file window.location = "/ClientAdmin/Download?file=" + downloadUrl; //Delete excel file $.ajax({ url: "@Url.Action("DeleteReportFile", "ClientAdmin")", type: "POST", data: { file: downloadUrl }, dataType: "json", success: function (downloadUrl) { }, error: function () { AlertShow("Error!", "Oops! An error occured"); } }) }, error: function () { AlertShow("Error!", "Oops! An error occured"); } })
-7495636 0 The logic of your recursive function is just wrong. You never actually read the contents of the array. I'm surprised you got any meaningful output out of that.
You need to rethink of the recursive definition to perform this addition.
Base case(s):
Sum of an empty array is 0.
.
i.e., sum_of_array(x, 0) == 0.
Sum of a 1-element array is the value of the element.
i.e., sum_of_array(x, 1) == x[0]
Recursive case:
Sum of an n-element array is the sum of the nth element and the sum of the first n-1
elements.
i.e., sum_of_array(x, n) == x[n-1] + sum_of_array(x, n-1)
Figure out how to encode this logic in your function.
-31866821 0Update part of your code like this:
public int Min(int[] numbers) { int m = numbers[0]; for (int i = 0; i < numbers.Length; i++) { if (m > numbers[i]) { m = numbers[i]; } } return m; } public int Max(int[] numbers) { int m = numbers[0]; for (int i = 0; i < numbers.Length; i++) { if (m < numbers[i]) { m = numbers[i]; } } return m; }
EDIT: This will help you get rid of the error you are getting. But you still need to figure out the logic on returning the correct value.
The reason you were getting this error is because, if in case none of the numbers in the array int[] numbers
that you are passing to the methods satisfy the if condition if (m > numbers[i])
, the code would never reach the return statement.
You can use DrawTextEx()
with the DT_CALCRECT
flag (thanks to Jonathan Potter for that addition). Then find the difference between top
and bottom
of the output RECT object.
Im facing an issue which I believe to be VAO-dependant, but Im not sure..
I am not sure about the correct usage of a VAO, what I used to do during GL initialization was a simple
glGenVertexArrays(1,&vao)
followed by a
glBindVertexArray(vao)
and later, in my drawing pipeline, I just called glBindBuffer(), glVertexAttribPointer(), glEnableVertexAttribArray() and so on.. without caring about the initally bound VAO
is this a correct practice?
-5572785 0 html5 search input eventsWhat event is triggered when a user clicks the X in a search input field (in webkit browsers) to cancel the search or clear the text?
Information is available about restyling the button and other custom events, but not on using this button.
-17212474 0 run an application on start screen in windows phoneI am stuck in a problem and need suggestions from you all.
My question is: Is it possible to run an app on start screen of a windows phone?
I have seen in android phone that there are apps like weather app in the phones start screen that opens there and there as a window on the same screen without navigation.
Can we make something like this in windows phone?
Thanks in advance.
-30359483 0I've never done this myself, so I kind of wanted to try it.
2 Forms, 1 query, and 1 (technically 3) line(s) of VBA.
The "search"/parent form. I created a blank form and called it Form4. I added 2 textboxes, 2 labels, and a button to it.
I then created a query that filters records by what's in these 2 textboxes. I don't have the same table/schema you did, so bare with me on the names/data types.
My setup:
SELECT tbl_Employee.ID, tbl_Employee.EmployeeNumber, tbl_Employee.FirstName, tbl_Employee.LastName FROM tbl_Employee WHERE (((tbl_Employee.ID) Like "*" & [Forms]![Form4]![txtSearch2] & "*") AND ((tbl_Employee.EmployeeNumber) Like "*" & [Forms]![Form4]![txtSearch1] & "*"));
The searches are flexible, as they use wildcards. You can remove these, but I figured the more information the better.
So, we now have a Form with 2 textboxes that we use to narrow down our query results.
Next step, create another form to be inserted into Form4 to view our search results.
Create a blank Form (I named mine Form5, hooray). Right click in the top left corner of the Form, and select "Properties".
On the Format tab: Default View: Datasheet
On the Data tab: Record Source: Query5 (or your query name) Recordset Type: Dynaset
Go back to the form. In design view, in the Access Tool bar at the top, and to the right "Add Existing fields". Add whichever fields you want from your query.
Close Form5.
Open Form4 in Design View. Drag Form5 onto Form4. Save it.
On Form4, right click on the Button we added, or add it if you have not. Go to Properties, Event -> OnClick -> (click the three little ...
). Double click on Code Builder. Type in Me.Form5.Requery
. (or Me.YourFormNameHere.Requery
).
Run Form4 and test your filtering capabilities.
-14366452 0First thing to remember is CI does not add $_FILES
to the input object. You will need to access those like $_FILES['img1']
etc. So these:
'img1'=>$this->input->post('img1'),//image path is not inserting But all other fields are inserting into db 'img2'=>$this->input->post('img2'),//image path is not inserting
should be something like:
'img1'=>$_FILES['img1']['name'],//image path is not inserting But all other fields are inserting into db 'img2'=>$_FILES['img2']['name'],//image path is not inserting
depending on what you expect to be storing in the database. You can rename files, etc through the upload class. I would suggest reading over those docs.
Secondly, you don't appear to be calling the actual upload method:
$this->upload->do_upload()
Not sure if you needed this but... If you want multiple configs, you have to redefine the config for multiple files if you want them to have different paths...
$config['upload_path'] = 'uploads/'; $config['allowed_types'] = 'gif|jpg|jpeg|png'; $config['max_size'] = '1000'; $config['max_width'] = '1920'; $config['max_height'] = '1280'; $this->load->library('upload', $config); $this->upload->do_upload("img1"); $config['upload_path'] = 'some_other_dir/'; $config['allowed_types'] = 'gif|jpg|jpeg|png'; $config['max_size'] = '1000'; $config['max_width'] = '1920'; $config['max_height'] = '1280'; $this->upload->initialize($config); $this->upload->do_upload("img2");
and if you don't want them to have different paths, you can just load in the library as you do in your example and call do_upload()
with no params passed.
If i missed the point or you need more info let me know and I may update.
-38646834 0The problem might be related to CORS (Cross Origin Resource Sharing)
Thy to enable in your application --> Enabling cors Rails5
Good luck
-10685700 0normally you would use a CMS-alike workflow, where you can set up a Master Layout and then make an Administrative way to add content to each part of the page you would want.
In a simple way, you can just easily create pages using 2 textboxes and a submit button:
<input type="text" id="txtFileName" /> <textarea id="txtContent" rows="80" cols="12"></textarea> <input type="submit" id="btnSave" value="Save File" />
and have your code to create a new text file with the passed contents like:
// create a writer and open the file using (TextWriter tw = new StreamWriter( txtFileName.Text, false, System.Text.Encoding.UTF8)) { // write the content tw.Write(txtContent.Text); // close the stream tw.Close(); }
You can show a list of all files and read them the same way, so you can edit them...
Now, in ASP.NET, this might not work properly as the server will need to compile again and for that you will need to also change the project file, but you can run a local script issuing the compile line and that will re-compile everything for you.
Give it a try, and when you come up with some stopper, let us know, we might give you a hand on that...
-9411544 0 parse date by prompting user for date format?My application reads a csv file provided by the user. This csv file contains a field for date and / or time, formatted in any way the user chose it. Like: 1999/10/28 or 2000-01-01,3PM-02-59
I want to offer the user the possibility to indicate the formatting of the date and time in this field. So, I'd have an input window saying: "Specify the formatting of your date/time field" "Example: for 1999/10/28 format, input yyyy/mm/dd" "Other example: for 2000-01-01,3PM-02-59,input yyyy-dd-mm,hh-mm-ss"
I would retrieve their input as a string, then do some complicated and annoying operation to derive a regular expression from this string, which I would then apply in the csv parser to identify years, months, days, hours, etc. in the "date and time" field.
My question before embarking in this: is there a library which already does this kind of thing? Am I reinventing the wheel? Is there a much more obvious approach I'm missing?
Thanks a lot!
PS: yes, it is all about users providing their own strange date and time formats. No need to suggest that it would be easier with a a uniform format! :-)
-6089797 0Ok, again I reply to my own question, but this time with a positive remark. I think what I was doing wrong had something to do with the hidden - for me - implications of the Document-based architecture of the default Document Application template.
I have tried with a different approach, creating an application from scratch NOT flagging "Document-based Application" and providing it with:
and I have forced instantiation of the NSWindowController subclasses in the MyDocument code.
I have also put the IBActions for the MenuItems in the MyDocument and I have bound the MyDocument Object to the MenuItems in the MainMenu.xib.
This time I was able to do whatever, hiding/showing windows starting with one hidden one not, enabling menu items automatically at will.
Here follows the code, for any newbie like me who might have to fight with this in the future.
// MyDocument.h #import <Cocoa/Cocoa.h> #import "testWindowController.h" #import "test2WindowController.h" @interface MyDocument : NSDocument { testWindowController *test; test2WindowController *test2; } - (IBAction)showWindow1:(id)pId; - (IBAction)showWindow2:(id)pId; - (IBAction)hideWindow1:(id)pId; - (IBAction)hideWindow2:(id)pId; @end // MyDocument.m #import "MyDocument.h" #import "testWindowController.h" #import "test2WindowController.h" @implementation MyDocument - (id)init { self = [super init]; if (self) { // Initialization code here. NSLog(@"MyDocument init..."); [self makeWindowControllers]; } return self; } - (void)dealloc { [super dealloc]; } - (void)makeWindowControllers { test = [[testWindowController alloc] init]; test2 = [[test2WindowController alloc] init]; [self addWindowController:test]; [self addWindowController:test2]; // start hiding the first window [[test window] orderOut:self]; } - (IBAction)hideWindow1:(id)pId { NSLog(@"hideWindow1"); [[test window] orderOut:self]; } - (IBAction)showWindow1:(id)pId { NSLog(@"showWindow1"); [test showWindow:self]; [[test window] makeKeyAndOrderFront:nil]; // to show it } - (IBAction)hideWindow2:(id)pId { NSLog(@"hideWindow2"); [[test2 window] orderOut:self]; } - (IBAction)showWindow2:(id)pId { NSLog(@"showWindow2"); [test2 showWindow:self]; [[test2 window] makeKeyAndOrderFront:nil]; // to show it } -(BOOL)validateMenuItem:(NSMenuItem *)menuItem { NSLog(@"in validateMenuItem for item: %@", [menuItem title]); if ([[menuItem title] isEqualToString:@"Show Window"] && [[test window] isVisible]){ return NO; } if ([[menuItem title] isEqualToString:@"Hide Window"] && ![[test window] isVisible]){ return NO; } if ([[menuItem title] isEqualToString:@"Show Window2"] && [[test2 window] isVisible]){ return NO; } if ([[menuItem title] isEqualToString:@"Hide Window2"] && ![[test2 window] isVisible]){ return NO; } return [super validateMenuItem:menuItem]; }
-7617586 0 git log @{u}..
This will list all the commits that are not yet pushed to the remote. If you want the diff of each commit then add a -p after log
git log -p @{u}..
Yes, the two dots at the end are necessary. :)
-34065784 0The most comfortable solution is
use Symfony\Component\HttpFoundation\BinaryFileResponse; use Symfony\Component\HttpFoundation\ResponseHeaderBag; $response = new BinaryFileResponse($file); $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT); return $response;
-13104157 0 How to display echo if user has not selected from a drop down menu In my code below I have 2 drop down menus. One is a "Course" drop down menu and the other is a "Modules" drop down menu:
Below is the code:
<?php // connect to the database include('connect.php'); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); die(); } $sql = "SELECT CourseId, CourseName FROM Course ORDER BY CourseId"; $sqlstmt=$mysqli->prepare($sql); $sqlstmt->execute(); $sqlstmt->bind_result($dbCourseId, $dbCourseName); $courses = array(); // easier if you don't use generic names for data $courseHTML = ""; $courseHTML .= '<select name="courses" id="coursesDrop" onchange="getModules();">'.PHP_EOL; $courseHTML .= '<option value="">Please Select</option>'.PHP_EOL; while($sqlstmt->fetch()) { $course = $dbCourseId; $coursename = $dbCourseName; $courseHTML .= "<option value='".$course."'>" . $course . " - " . $coursename . "</option>".PHP_EOL; } $courseHTML .= '</select>'; $moduleHTML = ""; $moduleHTML .= '<select name="modules" id="modulesDrop">'.PHP_EOL; $moduleHTML .= '<option value="">Please Select</option>'.PHP_EOL; $moduleHTML .= '</select>'; include('noscript.php'); ?> <script type="text/javascript"> function getModules() { var course = jQuery("#coursesDrop").val(); jQuery('#modulesDrop').empty(); jQuery('#modulesDrop').html('<option value="">Please Select</option>'); jQuery.ajax({ type: "post", url: "module.php", data: { course:course }, success: function(response){ jQuery('#modulesDrop').append(response); } }); } </script> <h1>EDIT AN ASSESSMENT'S DATE/START TIME</h1> <form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post"> <table> <tr> <th>Course: <?php echo $courseHTML; ?></th> <th>Module: <?php echo $moduleHTML; ?></th> </tr> </table> <p><input id="moduleSubmit" type="submit" value="Submit" name="moduleSubmit" /></p> </form> <?php if (isset($_POST['moduleSubmit'])) { $sessionquery = " SELECT SessionId, SessionDate, SessionTime, ModuleId, TeacherId FROM Session WHERE (ModuleId = ? AND TeacherId = ?) ORDER BY SessionDate, SessionTime "; $sessionqrystmt=$mysqli->prepare($sessionquery); // You only need to call bind_param once $sessionqrystmt->bind_param("si",$moduleId,$userid); // get result and assign variables (prefix with db) $sessionqrystmt->execute(); $sessionqrystmt->bind_result($dbSessionId,$dbSessionDate,$dbSessionTime, $dbModuleId, $dbTeacherId); $sessionqrystmt->store_result(); $sessionnum = $sessionqrystmt->num_rows(); if($sessionnum ==0){ echo "<p>Sorry, You have No Sessions under this Module</p>";
module.php where it displays "Module" drop down menu:
<?php // connect to the database include('connect.php'); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); die(); } $course = isset($_POST['course']) ? $_POST['course'] : ''; $sql = " SELECT cm.CourseId, cm.ModuleId, c.CourseName, m.ModuleName FROM Course c INNER JOIN Course_Module cm ON c.CourseId = cm.CourseId JOIN Module m ON cm.ModuleId = m.ModuleId WHERE (c.CourseId = ?) ORDER BY c.CourseId, m.ModuleId "; $sqlstmt=$mysqli->prepare($sql); $sqlstmt->bind_param("s",$course); $sqlstmt->execute(); $sqlstmt->bind_result($dbCourseId,$dbModuleId,$dbCourseName,$dbModuleName); $moduleHTML = ""; while($sqlstmt->fetch()) { $moduleHTML .= "<option value='$dbModuleId'>" . $dbModuleId . " - " . $dbModuleName . "</option>".PHP_EOL; } echo $moduleHTML; $sqlstmt->execute(); ?>
Now if you look at the bottom of the code, what happens is that it performs a query after the user has submitted the "Course" and "Module" drop down menus. if it doesn't find a session related with that module then it echos "Sorry, You have No Sessions under this Module"
.
But what my question is that I do not want this echo to be displayed if the user has not selected a "Course" and "Module" from their drop down menus or if the user has selected a course from the "Course" drop down menu but has not selected a module from the "Module" drop down menu.
Below is the echo's I wanted for each situation:
echo "Please Select a Course and Module";
echo "Please Select a Module";
echo "Sorry, You have No Sessions under this Module";
List 3 from above at the moment works but how can I get list 1 and 2 to work by only displaying their echo's and no other echo?
UPDATE:
Javascript code where it validates drop down menus:
function validation() { var isDataValid = true; var moduleTextO = document.getElementById("coursesDrop"); var courseTextO = document.getElementById("modulesDrop"); var errModuleMsgO = document.getElementById("moduleAlert"); if (courseTextO.value == "" && moduleTextO.value == ""){ errModuleMsgO.innerHTML = "Please Select a Course and Module"; isDataValid = false; } else if (courseTextO.value == ""){ errModuleMsgO.innerHTML = "Please Select a Course"; isDataValid = false; }else if (moduleTextO.value == ""){ errModuleMsgO.innerHTML = "Please Select a Module"; isDataValid = false; }else{ errModuleMsgO.innerHTML = ""; } return isDataValid; }
Below is HTML code:
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post"> <table> <tr> <th>Course: <?php echo $courseHTML; ?></th> <th>Module: <?php echo $moduleHTML; ?></th> </tr> </table> <p><input id="moduleSubmit" type="submit" value="Submit" name="moduleSubmit" /></p> <div id="moduleAlert"></div> </form>
-14433460 0 You can use Enumerable.Except to get distinct items from lines3 which is not in lines2:
lines2.AddRange(lines3.Except(lines2));
If lines2 contains all items from lines3 then nothing will be added. BTW internally Except uses Set<string>
to get distinct items from second sequence and to verify those items present in first sequence. So, it's pretty fast.
By using CAPI functions (in C# and Compact Framework 3.5), I try to sign a XML and create an CMS/PKCS envelop like the following OpenSSL command do:
openssl smime -sign -in file.xml -out file.b64 -passin pass:test -binary -nodetach -inkey cert.priv.pem -signer cert.pub.pem
By calling the functions "CryptMsgOpenToEncode" and "CryptMsgUpdate", I obtain a first signed file. Now I would add optional OID and others datas (more precisely the "SMIMECapabilities", and signing time).
How to do this?
-31352151 0First things first: Why are you trying to run a graphical application with superuser privileges? This is in general a a bad idea.
X11 implements various authentication mechanisms to prevent users which are not part of the login session to access the X server. This is implemented not though Unix file permissions, but through protocol authentication. So even if you're root, you can not talk to the X server, without jumping through a few hoops. In particular every client needs access to the Xauthority cookies. Those are stored by default in ${HOME}/.Xauthority
but can be defined to be fetched from a different location using the XAUTHORITY
environment variable.
So to pass that through sudo you'd set XAUTHORITY to point to your login session user's ~/.Xauthority
and then call sudo with environment preserving option.
export XAUTHORITY="${HOME}/.Xauthority" sudo -E ./idea.sh
Or you could set the XAUTHORITY environment after sudo. Another, much more blunt options is to simply punch a hole into authentication that allows all clients running locally to access the X server. However this is a bad idea, because then every user on your system could run a keylogger or otherwise mess with your session (for example preventing the screen locker to work). You can punch that hole with xhost +si:localuser
but you really should not do it.
In your code instead of using availability.getMode() use availabilty.getType() and check whether it is Presence.Type.available.
-37917506 0 using entityFrameWork in windows service application gives the underlying providor failed to open errorThis is my service start code and my class. it is long but problem is just with database and entityFrameWork section please omit other lines. consider I just want to read a data from database:
my service start code:
protected override void OnStart(string[] args) { System.Threading.Thread newThread = new System.Threading.Thread(new System.Threading.ThreadStart(ReadPolling.Read)); newThread.Start(); }
this is my ReadPolling.cs file:
public class ReadPolling { public static webtccUsersEntities db; public static void Read() { try { byte[] readBuffer = new byte[1024]; while (true) { writeToDb(readBuffer); System.IO.File.WriteAllText("D:\\1.txt", "read-write"); } } catch (Exception ex) { System.IO.File.WriteAllText("D:\\1.txt", ex.Message); } } public static void writeToDb(byte[] userId) { db = new webtccUsersEntities(); string _userId="";foreach(byte item in userId) { if(item!=0 || item!=40) _userId += (39 - item).ToString(); } _userId = "0009544023"; Time time; if(db.Times.Where(i=>i.userId==_userId).Count()>0)//User has at least one time { time = db.Times.Where(i => i.userId == _userId).OrderBy(i => i.dayDate).OrderBy(i=>i.inTime).Last();//last time if (time.dayDate == DateTime.Today)//today time { if(time.outTime==null)//wants an out for today { time.outTime = DateTime.Now.ToLocalTime();//an out for today db.SaveChanges(); } else//wants a new in/out for today { Time newTime = new Time();newTime = db.Times.Create(); newTime.userId = _userId; newTime.dayDate = DateTime.Now.Date; newTime.inTime = DateTime.Now.ToLocalTime(); db.Times.Add(newTime);db.SaveChanges(); } } else//not today time { //new in for today Time newTime = new Time();newTime = db.Times.Create();newTime.dayDate = DateTime.Today;newTime.inTime = DateTime.Now.ToLocalTime();newTime.userId = _userId; db.Times.Add(newTime);db.SaveChanges(); } } else//user first time { Time firstTime = new Time(); firstTime = db.Times.Create(); firstTime.userId = _userId;firstTime.dayDate = DateTime.Now.Date;firstTime.inTime = DateTime.Now.ToLocalTime(); db.Times.Add(firstTime);db.SaveChanges(); } } }
as you can see if an error occurs I write it to a file named "1.txt" in my drive "D:\". so when I start the service i open my text file and see the error "The underlying provider failed on Open.Login failed for user 'NT AUTHORITY\LOCAL SERVICE'.". what causes the problem?
-22280700 0If you use JSF 1.2 or higher you need change it like this:
<h:head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta http-equiv="cache-control" content="no-cache" /> <meta http-equiv="pragma" content="no-cache" /> <meta http-equiv="expires" content="0" /> </h:head>
it can be part of template.xhtml
-28628454 0 Overwrite proj property with msbuild switchGiven the following proj snippet:
<Project DefaultTargets="artifacts" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <msbuild40>"msbuild.exe"</msbuild40> </PropertyGroup> <Target Name="compile"> <Exec Command="$(msbuild40) src\ClientFrameworkLoader.sln /t:Build /p:Configuration=Debug;platform=win32" /> <Exec Command="$(msbuild40) src\ClientFrameworkLoader.sln /t:Build /p:Configuration=Release;platform=win32" /> </Target> </Project>
am I right in thinking I can overwrite the msbuild40
property using the following command?
MSBuild.exe snippet.proj /p:msbuild40="C:\Program Files (x86)\MSBuild\12.0\bin\MSBuild.exe"
I don't have a Windows machine to hand right now otherwise I'd just try this.
-12180268 0 How can I gently "bust" UIWebview?Recently, a few developers have started creating apps which do nothing more than point at state-owned content (free, public property) through UIWebViews. This wouldn't ordinarily be a problem, except the apps are all ad-supported and some are even paid. Essentially, they're making money on state-owned content.
My question is this: how can I force the site to open a new Safari window rather than display in the UIWebview (which is wrapped in their app's branding)? I am able to detect UIWebview using the following, but am unable to do anything besides simply hide the content. I'd prefer it to provide a link to our content which then opens in Safari.
This is how I'm detecting UIWebview:
var is_uiwebview = /(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/i.test(navigator.userAgent);
-27587721 0 Here's how I did it for your reference, but for apple, I haven't found a way to start the navigation through url scheme.
+ (void)navigateToLocation:(CLLocation*)_navLocation { if ([[UIApplication sharedApplication] canOpenURL: [NSURL URLWithString:@"comgooglemaps://"]]) { NSString *string = [NSString stringWithFormat:@"comgooglemaps://?daddr=%f,%f&directionsmode=driving",_navLocation.coordinate.latitude,_navLocation.coordinate.longitude]; [[UIApplication sharedApplication] openURL:[NSURL URLWithString:string]]; } else { NSString *string = [NSString stringWithFormat:@"http://maps.apple.com/?ll=%f,%f",_navLocation.coordinate.latitude,_navLocation.coordinate.longitude]; [[UIApplication sharedApplication] openURL:[NSURL URLWithString:string]]; } }
-5120851 0 I tend to put them in a client context static class. This way they are easily accessible from anywhere in your application and you can initialize them (where needed) on application startup or user login.
-24859883 0Basic implementation
public abstract class Field<T> { private T value; // + constructor(s) public T get() { return value; } public void set(T value) { this.value = value; } } public class StringField extends Field<String>{} public class IntField extends Field<Integer>{}
for more details Please visit this link link2
-12199151 0List.js is a lightweight JavaScript library for adding sorting, searching and paging functionality to plain html lists and tables.
One common solution is to create a pid file somewhere. If the pid file exists, exit the process early. Otherwise create the pid file (writing process.pid
to it) and delete it when the process exits.
I don't have a tcl with tclx to test with, but you probably need to pass the list variable name to the proc and then use upvar
inside. Try this:
keylset x ... keylset y ... proc_name x ;# just the varname proc_name y ;# just the varname proc proc_name {varname} { upvar 1 $varname keyedlist puts [keylkeys keyedlist] }
-33776140 0 how can we pass the Flv format files to rtmp using VideoCore Library in ios Hi i am making an app based on broadcast using RTMP, videocore lib and Wowza server my Wowza server play only FLV file But i don't know how to pass FLV videos to server and how to encode H.264 codec if it is H.264 for videos and AAC for Audio then only it will Start the Broadcasting but I am using below code
switch(_session.rtmpSessionState) { case VCSessionStateNone:[_session continuousAutofocus]; case VCSessionStatePreviewStarted: case VCSessionStateEnded: case VCSessionStateError: NSLog(@"///////////////////////////////////////////////vcsession error%ld",(long)VCSessionStateError); [_session startRtmpSessionWithURL:urlForStream andStreamKey:streamID]; break; default: [_session endRtmpSession]; break; }
and below log displaying in console
Hi,
I tried connecting the my app from iOS 8.3 to RTMP server(Wowza) using VCSimpleSession. But i am unable to connect. Always returning state -11 (ClientStateNotConnected)
Please find the log below:
[736:267980] Creating context
[736:267980] Context creation succeeded
ClientState: 1
ClientState: 2
ClientState: 3
ClientState: 4
ClientState: 5
ClientState: 6
received server window size: 10000000
received peer bandwidth limit: 10000000 type: 2
received ping, sending pong.
Received invoke
pktId: 1
received invoke _result
tracked command: connect
ClientState: 7
received unknown packet type: 0x18
Received invoke
pktId: 2
received invoke _result
tracked command: connect
ClientState: 11
-11398411 0There are several issues:
with
, you need to reference the object with .
Offset(x,y)
is a range, not a number - you are interested in the row, so you need to add .Row
End(xlUp)
thingy has to start from the last row to workThis is probably what you meant:
Sub ONJL() Dim lastrow As Long Dim wsRD As Worksheet 'Raw Data Set wsRD = Sheets("Raw Data") With wsRD Application.ScreenUpdating = False lastrow = .Range("J" & .Rows.Count).End(xlUp).Row .Range("J" & lastrow + 1).Formula = "=Today()" End With End Sub
And don't forget to turn the screenupdating on somewhere.
-17449086 0 Edit external CSS/SCSS with javascriptI need to 'edit' a file that's already saved on my server, example:
<link rel="stylesheet" href="css/plugin.scss">
But not only that, I want to edit a certain specific line, in SASS you can define variables in css, basically, I'd like to search inside this file with JAVASCRIPT for the string:
'$increment:
And if it's found, find out what line it is on and replace that whole line with:
'$increment:10;
Basically I want to generate a downloadable file for the user that's custom depending on what settings they choose via a html input field.
If there's a simpler/better explanation I'm all ears :)
-25182988 0 Check IExplorer CSS3 compatibility automaticallyI have a big css style sheet and I would like to know if these styles are compatible with Internet Explorer 9.
I can verify each property but would be more efficient to analyze the entire file.
For example: linear gradient was only introduced in IE10, if I check linear gradient for IE9 it must alert me.
-10636751 0Sometimes you need to modify some fields before returning from the clone() method.
Check this : http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Object.html#clone(). I pasted the relevant part here for convenience:
-5836357 0"By convention, the object returned by this method should be independent of this object (which is being cloned). To achieve this independence, it may be necessary to modify one or more fields of the object returned by super.clone before returning it. Typically, this means copying any mutable objects that comprise the internal "deep structure" of the object being cloned and replacing the references to these objects with references to the copies. If a class contains only primitive fields or references to immutable objects, then it is usually the case that no fields in the object returned by super.clone need to be modified."
You have to actually have a site set up in IIS with host name pointed to your site's url: mysite.com. Then go to project options, Web tab and select Use locakl IIS Web server, specifying Project URL as http://mysite.com
-20698403 0You don't need JQuery for this task. You can usee CSS3 transition.
Try this:
a { color: #fff; -webkit-transition: all 0.3s; -moz-transition: all 0.3s; -o-transition: all 0.3s; transition: all 0.3s; } a:hover { color: #ff000; -webkit-transition: all 0.3s; -moz-transition: all 0.3s; -o-transition: all 0.3s; transition: all 0.3s; } .dark a { color: #ff0000; -webkit-transition: all 0.3s; -moz-transition: all 0.3s; -o-transition: all 0.3s; transition: all 0.3s; } .dark a:hover { color: #000; -webkit-transition: all 0.3s; -moz-transition: all 0.3s; -o-transition: all 0.3s; transition: all 0.3s; }
-12306080 0 Microsoft Visual C 2010 Express: failure during conversion to COFF: file I get the following error, when I would like to make a Build solution.
-11422667 0LINK : fatal error LNK1123: failure during conversion to COFF: file invalid or corrupt
Also without the IF EXIST but using the /U option of XCOPY
xcopy source_file_name dest_folder /u /y
-30158874 0 You can instead use RcppRoll::roll_sum
which returns NA if the sample size(n
) is less than the window size(k
).
set.seed(1) dg$count = rpois(dim(dg)[1], 5) library(RcppRoll) library(dplyr) dg %>% arrange(site,year,animal) %>% group_by(site, animal) %>% mutate(roll_sum = roll_sum(count, 2, align = "right", fill = NA)) # site year animal count roll_sum #1 Boston 2000 dog 4 NA #2 Boston 2001 dog 5 9 #3 Boston 2002 dog 3 8 #4 Boston 2003 dog 9 12 #5 Boston 2004 dog 6 15 #6 New York 2000 dog 4 NA #7 New York 2001 dog 8 12 #8 New York 2002 dog 8 16 #9 New York 2003 dog 6 14 #10 New York 2004 cat 2 NA
-29290717 0 Datetimepicker returning a null value in mysql. [VB.NET] Here is my code:
'" & DateTimePicker1.Value & "')"
It keeps returning this in mysql, what am I doing wrong? "0000-00-00"
Also the type of the column in phpmyadmin is DATE
-10573833 0you need to declare inbuffer at least as many bytes as the size of MAX_PACKET char * inbuffer = new char[MAX_PACKET];
and place before each recv() memset(inbuffer,0,MAX_BUFFER); to zero out the buffer so you don't mistakenly see the tail end of a previous packet in the scenario you received two packets where the 2nd is shorter than the 1st.
if your incoming packet has no unique termination byte ie '\r' you need to add int recvbytes ; recvbytes =new recv(...) since recv returns the number of bytes received on the wire
-2947604 0 Naming Convention for Blackberry DevelopmentI have gone through with some of the sample examples of blackberry.
And in some classes I have found some variables are starting with _ like _address
and some of them are ALLCAPS.
It is a bit different than the basic Java naming conventions. Is there any difference between Java and BlackBerry naming convention?
-28520329 0 Disable all checkboxes when one activeMy problem is that i dont know which element i should target to check if the checkbox is checked and then to disable the other ones. Do i need put this code inside the form tag? In my code i have 2x2 checkboxes 2 for the yes answer and 2 for the no answer.
thas my HTML:
<div id="form"> <div class="anketa"> <h3>Pači sa Vám táto stránka?</h3> <div class="checkbox custom"> <input id="box" class="css-checkbox" type="checkbox" name="boxes" /> <label for="box" class="css-label" name="yes" onclick="" ></label> Áno </div> <div class="checkbox custom"> <input id="box1" class="css-checkbox" type="checkbox" name="boxes" /> <label for="box1" class="css-label" name="no" onclick="" ></label> Nie </div> </div> <div class="anketa"> <h3>Pomohla Vám táto stránka?</h3> <div class="checkbox custom"> <input id="box2" class="css-checkbox" type="checkbox" name="boxes" /> <label for="box2" class="css-label" name="yes" onclick=""></label>Áno </div> <div class="checkbox custom"> <input id="box3" class="css-checkbox" type="checkbox" name="boxes" /> <label for="box3" class="css-label" name="no" onclick=""></label> Nie </div> </div> </div>
And this is my script:
var checkbox = document.getElementByClassName("css-checkbox"); //? }
Thanks for every help.
-13838774 0Also you can not use getView() inside onCreateView because the view you are accessing has not been created yet. So you should do it like this:
View view = inflater.inflate(R.layout.dpsfrag, container, false);
TextView tv= (TextView) view.findViewById(R.id.textView1);
tv.setText("hello");
return view;
-3160946 0I highly recommend the Seam Framework from JBoss. It helps simplify JSF quite a bit, and also makes it very easy to integrate things like Hibernate or EJB3. Plus, it's quite pretty wide support across the major IDEs.
-21357659 0Currently, there's no triggers in mongo (but you can vote for the feature here -> https://jira.mongodb.org/browse/SERVER-124).
-37529085 0Pipes don't support inheritance. It's just a guess but I remember seeing that a pipe that extends another class causes this error. https://github.com/angular/angular/issues/8694
-15370535 0Both .each()
and .map()
are functions that are able to access the elements in your data.list
. Read more about .each() and .map()
You can use one or the other, you don't need both:
$.map(data.list, function(val, i) { $('#category').append(new Option(val,val)); console.log("val1 " + val); });
Or
$(data.list).each(function(i, val) { $('#category').append(new Option(val,val)); console.log("val1 " + val); });
Pay attention to the arguments order, .each()
is in different order from .map()
.
there is a good example in here to calculate distance with PHP http://www.geodatasource.com/developers/php :
function distance($lat1, $lon1, $lat2, $lon2, $unit) { $theta = $lon1 - $lon2; $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta)); $dist = acos($dist); $dist = rad2deg($dist); $miles = $dist * 60 * 1.1515; $unit = strtoupper($unit); if ($unit == "K") { return ($miles * 1.609344); } else if ($unit == "N") { return ($miles * 0.8684); } else { return $miles; } }
-7826776 0 i don't know how you would do it efficiently but if you need to get it done.
keywords = Keyword.objects.all() for keyword in keywords: print 'Total Articles: %d' % (Article.objects.filter(keywords=keyword).count())
-289703 0 You can do cross-class analysis in PMD (though I've never used it for this specific purpose). I think it's possible using this visitor pattern that they document, though I'll leave the specifics to you.
-1280436 0A likely reason is that each “copyData” is actually referencing the data in the original. As such, the new data objects will keep a reference to the original object. This is generally an efficiency advantage, since no copy of the actual data needs to be made. (The exception would be if you planned to keep a small subrange around.)
All of the data objects will be released properly when the active NSAutoreleasePool
is popped.
In general, you shouldn’t be looking at the retain count of objects anyway. Code that isn’t under your direct control can do just about whatever it wants with object references, as long as it balances its retains and releases properly. If you’re concerned about leaks, use appropriate tools such as Instruments’s Leaks instrument.
-23336183 0 How to read certain specified fields from text file in javascriptI am using text file data for my script. I am loading the text file and getting the data from it. The text file contains data as below.
'DoctorA': {name: "Pharmaceuticals", title: "Switzerland, 120000 employees"}, 'DoctorB': {name: "Consulting", title: "USA, 5500 employees"}, 'DoctorC': {name: "Diagnostics", title: "USA, 42000 employees"}, 'DoctorD': {name: "Fin Serv. & Wellness", title: "South Africa, employees"},
I load and use something like this to read the data from that text file.
data.speakers=names_val[0];
I have not fully specified my script. My problem is I am getting the entire text file when I load into data.speakers. Is there anyway to read only that title: fields or only that name: field
-35595911 0use the following:
glEnable(0x8642); glEnable(GL_POINT_SMOOTH);
and then increase the size of the vertex using either one of these:
glPointSize(10.0f); //in the application // OR gl_PointSize(10.0f); //in your vertex shader
-39713972 0 To have the image stick to both sides of screen and maintain the aspect ratio, set these 4 constraints:
Set an aspect ratio constraint: ImageView Width equal to ImageView Height with multiplier
480:640
. To set this, control-drag diagonally in the ImageView and select Aspect Ratio from the pop-up. Then change the multiplier to 480:640
.
Set the content mode for the image to Scale to fill
.
I have used the jQuery.click() function in the past with buttons and have had nothing but success, but I tried to use it to click on a <span>
and it doesn't work.
Also I noticed that it automatically executed my function without listening to the click.
Judging how I used it on buttons, this would be the syntax:
<p><span id="example">Click Here</span></p> $("#example").click(exampleFunction(p1, p2));
But it does not seem to work. Again it just executes it without the click even taking place. I even tried:
$(document).on("click", "#example", exampleFunction(p1, p2));
Still no luck, same results.
I am making a weather app and my goal with this is to toggle the temperature between Fahrenheit and Celsius by clicking on the unit. I made a copy of the code for the app on codepen.io here:
I appreciate the help!
-9653681 0Problem was the clientId. I used "javascript" because I saw it in an example. Turns out I needed to use "HTTP" instead.
-21427945 0 css overflow issue with two divisionFiddle
I have two Div
, one is in table and other , outside of table .
My problem is , as you can see , divOne
overflow outside of parent Div
.
I want to show like
--------------------- | ---- ---- | | | | | D2 | | | | D1 | | | | | | | ---- | | | | | | ---- | ---------------------
Here is my code ,
html
<div class="wrapper"> <textarea rows="12" cols="8" class="divOne"> Division One </textarea> <table> <tr> <td> <textarea rows="6" cols="8" class="divOne"> Division Two </textarea> </td> </tr> </table> </div>
Css
.wrapper { border: 1px solid #999999; position: relative; margin: 0px; padding: 10px; width: 600px; background-color: #FCFCFC; min-height: 50px; color: black; border-radius: 8px; -moz-border-radius: 8px; line-height:normal; } .divOne { float:left; }
-34274795 0 Dagger2: Is it possible to inject based on Android Version? Is it possible I can use Dagger2 to inject a concrete implementation based on SDK version?
For example
// MediaPlayerComponent.class @Component(modules = {MediaPlayerModule.class} public interface MediaPlayerComponent { void inject(MediaPlayerUI ui) } // MediaPlayerUI.java public class MediaPlayerUI { @Inject public MediaPlayer mPlayer; } // GingerbreadMediaPlayer.java public class GingerbreadMediaPlayer extends MediaPlayer {...} // IceCreamSandwichMediaPlayer.java public class IceCreamSandwichMediaPlayer extends MediaPlayer {...}
-21940061 0 The problem was that when the stream is read once the file offset position counter is moved to the end of file, using the same stream at others times you will get the error. I solved using docStyle.reset();
The old html presentational attributes are not a useful thing to use nowadays. I would discourage you from using any attributes on any elements in your body with the exceptions of class, id, data-* and things on input, audio, video or img.
To get the same effect, use
table { border-collapse: collapse; border-style:hidden; } table td { border-width: 1px; border-style: inset; border-color:black; }
As demoed here: http://jsfiddle.net/HknDE/35/
-24769231 0Your select
is not doing what you think it does.
The most compact version in PostgreSQL would be something like this:
with data(first_name, last_name, uid) as ( values ( 'John', 'Doe', '3sldkjfksjd'), ( 'Jane', 'Doe', 'adslkejkdsjfds') ) insert into users (first_name, last_name, uid) select d.first_name, d.last_name, d.uid from data d where not exists (select 1 from users u2 where u2.uid = d.uid;
Which is pretty much equivalent to:
insert into users (first_name, last_name, uid) select d.first_name, d.last_name, d.uid from ( select 'John' as first_name, 'Doe' as last_name, '3sldkjfksjd' as uid union all select 'Jane', 'Doe', 'adslkejkdsjfds' ) as d where not exists (select 1 from users u2 where u2.uid = d.uid;
-15495110 0 It looks as if you want to use Express and the express.compress
middleware. That will figure out if a browser supports gzip and/or deflate, so you don't have to.
A simple setup could look like this:
var express = require('express'); var app = express(); app.use(express.compress()); app.get('/', function(req, res) { res.send({ app_id: 'A3000990' }); }); app.listen(3000);
If your data is a JSON-string, you have to set the correct content-type header yourself:
res.setHeader('Content-Type', 'application/json'); res.send(data);
-13242395 0 Try to use regular expression, e.g.:
var count = Regex.Matches(input, @"\b\w+\b").Count();
-9563724 0 You don't need groups: you just have to make sure to disable the "self registration" option (from admin control panel: Global Configuration -> system -> Allow User Registration = No)
Also, you'll have to configure each article/menu to have Access Level "public"/"registered".
You can register new users from the admin control panel and only they will be able to view "registered" content.
I have created MKMapView, and instead of tagging "Google" it showing Legal. Please can anyone explain me why it showing Legal label.
In the simple case where the number of tasks is limited, I would do only a single query to retrieve them, and then separate them as follows:
tasks = Task.all @draft_tasks = tasks.select { |x| x.status == 'Draft' } @approved_tasks = tasks.select { |x| x.status == 'Approved' } @closed_tasks = tasks.select { |x| x.status == 'Closed' }
Furthermore, depending on the bendability of your requirements, I would even render them in a single table with a clear visual marker what the state is (e.g. background-colour or icons). Then there would not even be a reason to separate the tasks beforehand (but I can imagine this would break your UI completely).
None of the above is valid once the number of tasks becomes larger, and you will need to apply pagination, and you need to display three different tables (one for each state).
In that case you will need to use the three separate queries as answered by @Ben.
Now UI-wise, I am not sure how you can paginate over three different sets of data at once. So instead I would use a single table showing all the states, and offer the option to filter on the status. In that case at least it is clear for the user what pagination will mean.
Just my two cents, hope this helps.
-23746258 0Completely new answer as of given details. You are working with VBA
so you can call WorksheetFunctions like
Dim someVariable someVariable = WorksheetFunction.Quotient(Worksheets("Sheet1").Cells(1, "A").Value, Worksheets("Sheet1").Cells(1, "B").Value) Debug.Print someVariable
There is a quite good list of supported functions available on MSDN WorksheetFunction. Please choose your current Excel version on the linked page.
Furthermore I found another very important site concerning your problem that states that not all WorksheetFunctions are supported as Application. (see support.microsoft.com)
So I searched for workarounds and found a quite simple one on StackOverflow. But on the other hand - you really could make use of the VBA builtIn operator MOD
' created some variables, as I made some attempts on creating a good example Dim value1 value1 = Worksheets("Sheet1").Cells(1, "A").Value Dim value2 value2 = Worksheets("Sheet1").Cells(1, "B").Value someVariable = value1 Mod value2 Debug.Print someVariable ' of course you may use a single line statement too someVariable = Worksheets("Tabelle1").Cells(1, "A").Value Mod Worksheets("Tabelle1").Cells(1, "B").Value
I think there are some pretty good links to have a deeper look into.
-7809884 0You're mixing up Google Maps API 2 and API 3 code.
Remove the v=2 parameter or change it to v=3 (or v=3.5 for instance).
Change this: sensor=truese to either sensor=true or sensor=false
Remove the API key, that's only required for API 2.
Get rid of all the GMap2, GLatLng type of code that is for API 2 and change it all to be in API 3 syntax.
-9900892 0 Bouncing Ball program Would like ball to reappear at top and come down againRight now in my program the ball bounces up and down on the Y axis. What i want is for the ball to only move in the downward direction. when it gets to the bottom of the screen I want it to reappears at the top and starts down again. Continually moving from top to bottom.
@implementation BounceViewController @synthesize ball; -(void) bounce{ ball.center = CGPointMake(ball.center.x+position.x, ball.center.y+position.y); { if(ball.center.y>450 ||ball.center.y <0) position.y = -position.y; } } - (void)viewDidLoad { position = CGPointMake(0, 10); [NSTimer scheduledTimerWithTimeInterval:.05 target:self selector:@selector(bounce) userInfo:nil repeats:YES]; [super viewDidLoad]; } - (void)viewDidUnload { [self setBall:nil]; [super viewDidUnload]; } @end
-18162218 0 I have solved by my own with use of ParagraphProperties and TablecellProperties of openxml wordprocessing class. To align Vertically, I have used TablecellProperties to vertically align and ParagraphProperties to horizonal align and TextRotation.
-4690465 0There are no negative ASCII values. ASCII includes definitions for 128 characters. Their indexes are all positive (or zero!).
You're seeing this negative value because the character is from an Extended ASCII set and is too large to fit into the char literal. The value therefore overflows into the bit of your char
(signed on your system, apparently) that defines negativeness.
The workaround is to write the value directly:
unsigned char a = 0xAE; // «
I've written it in hexadecimal notation for convention and because I think it looks prettier than 174
. :)
I use UTF-8 everywhere on the site, the data come back in UTF-8 too, it works everywhere on the page, except one case: the (zend) form value.
I have checked everything, the string is utf-8, the page encoding is utf-8, the result from the Api is utf8.
(Margar\u00e9t\u00e1\u00f3\u0171\u00fa\u0151\u00fc\u00f6)
This is what I see in the divs, as well as in the header too :
Margarétáóűúőüö
This is what I got in the form:
Margarétáóűúőüö
I have tried many things, utf8_encode
, mb_convert_encoding
, but nothing was happened.
I used a helper, the $name contains the 'Margarétáóűúőüö' value:
$form = $this->_helper->form('user-settings'); $form->addElement('text', 'name', array( 'label' => 'Name', 'value' => $name, 'required' => true, 'autocapitalize' => 'off', 'autocorrect' => 'off', ));
-27441051 0 could not find method minifyEnabled() I'm working on an Android app using Android Studio. When trying to build the app, I get the following error. But I can't figure out how to fix that. All I did before was removing the /build directories from the SVN repository.
Error:(16) A problem occurred evaluating project ':app'.
Could not find method minifyEnabled() for arguments [false] on BuildTypeDsl_Decorated{name=release, debuggable=false, testCoverageEnabled=false, jniDebugBuild=false, renderscriptDebugBuild=false, renderscriptOptimLevel=3, applicationIdSuffix=null, versionNameSuffix=null, runProguard=false, zipAlign=true, signingConfig=null, embedMicroApp=true}.
Here's the part of the gradle file:
apply plugin: 'com.android.application' android { compileSdkVersion 18 buildToolsVersion "21.1.1" defaultConfig { applicationId "...xxx..." minSdkVersion 18 targetSdkVersion 18 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } }
-31060515 0 NO. Everywhere you see the *
operator with ptr
it will mean dereferencing EXCEPT that first time. When you do
int *ptr = 0;
the *
is making ptr
an integer pointer and pointing it the null address, the "zero-th" location in memory
What is the difference between the three, in terms of readability and performance?
There should be no difference in performance no matter which form you use.
As for readability, it's a matter of opinion. I would prefer to use
(*this)[i];
but I wouldn't complain if someone used one of the other forms.
Which is the "correct" way of invoking the operator?
All are correct - syntactically as well as semantically.
-25947074 0You can easily change particular ColumnDefinition
's Width
to 0
for hiding corresponding Grid
's column and getting the remaining columns equal width, for example :
//get column definition for the 1st column var col = myGrid.ColumnDefinitions[0]; //set it's width to 0 col.Width = new GridLength(0);
-40736223 0 You can reassign $this
value by variable variable
$name = 'this'; $$name = 'stack'; echo $this; // this will result stack
-13699874 0 Add vertical-align:top;
on your .item
class
.item{ vertical-align:top; }
-14645416 0 In Java all classes with scope public
must be save in file which name is exactly the same like name of this class. So if you have class named Sample
it has to be saved in file named Sample.java
. If class is named Student
then file should be named Student.java
One of reason for this is that packages
named and class
names can be easly mapped to real system paths.
In your controller declare :
$scope.selectedCity = 'cityName'; // any name you want to initialize with
-12580567 0 you can save access token on sharedReference when login as follow
public void onComplete(Bundle values) { SharedPreferences sp; Editor editor = sp.edit(); editor.putString("access_token",fb.getAccessToken()); editor.putLong("access_expires",fb.getAccessExpires()); editor.commit(); }
and Check this onCreate Method as follow
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_facebook_app); if(access_token != null){ fb.setAccessToken(access_token); } if(expires != 0){ fb.setAccessExpires(expires); } }
-11912381 0 ResourceEditor LWUIT NoClassDefFoundError: com/app/XMLMidlet: com/sun/lwuit/events/ActionListener I have developed Rss App LWUIT Project using ResourceEditor.
I opened the project in Netbeans IDE, I followed the link at developers Nokia site Generating the NetBeans project in the Resource Editor - Adding GUI resource file manually into your project.
While running my application, I am facing Uncaught exception
java/lang/NoClassDefFoundError: com/app/XMLMidlet: com/sun/lwuit/events/ActionListener
Could I do any extra thing?
-33045463 0 How can I quickly convert from hexadecimal to decimal in Scratch?In other languages you can use things like 0xFF
= 255
. I am working on a decoding project and I would like to be able to quickly convert from hexadecimal to decimal.
I was wondering if there was a very quick way to do this, besides writing a hexadecimal convertor?
-12612219 0This is a one-liner:
some_var.select{|v| v < compare_var}.max
-36022303 0 Error when publishing from VS 2015 - The components for communicating with FTP servers are not installed I'm using Visual Studio 2015 Enterprise with Update 1. I have a single solution, with a single ASP.NET web application project. I publish it by right-clicking on the project node, and clicking "Publish". I've setup a publish profile for FTP. Credentials work/tested/etc. Server connectivity is good.
However, when publish from Visual Studio 2015, it says "The components for communicating with FTP servers are not installed."
Things I've tried: - Validating FTP server name and credentials. - Clean/Rebuild - Restarting Visual Studio. - Kicking it (hard).
Things I did not try: - Restarting PC. - Repairing Visual Studio. - Sacrificing a goat.
I do NOT have Xamarin installed, but I do have Tools for Apache Cordova. I do NOT have VS 2013 (or any prior version) of VS installed.
-38223601 1 How to join three tables with Django ORM?My models are:
class Profiles(models.Model): first_name = models.CharField() last_name = models.CharField() email = models.CharField() class Meta: db_table = 'users' class Products(models.Model): title = models.CharField() content = models.CharField() price = models.BigIntegerField() user = models.ForeignKey(Profiles, related_name="product_owner") # user_id class Meta: db_table = 'products' class UserFollows(models.Model): profile = models.ForeignKey(Profiles, related_name='profile_following') # profile_id following = models.ForeignKey(Profiles, related_name='profile_is_following') # following_id class Meta: db_table = 'user_follows'
To get what I want, I would query it a raw sql query below:
SELECT * FROM products, users, user_follows WHERE products.user_id=users.id AND user_follows.following_id=products.user_id AND user_follows.profile_id=12345;
but I need to do it with Django ORM. I can join 'users' and 'products' tables with select_related but I have no idea how to join 'user_follows'. And I need to apply filter on a field of 'user_follows' table. Please help!
-30925381 0You need to bind to a ViewModel.Value somehow, and then use a (nested) binding to a format string.
When you have only one value:
<TextBlock Text="{Binding Path=DemoValue, StringFormat={StaticResource SomeKey}}" />
When you also have {1}
etc then you need MultiBinding.
When you really want to change languages in a live Form then the sensible way is probably to do all formatting in the ViewModel. I rarely use StringFormat or MultiBinding in MVVM anyway.
-19076687 0You can do this with the split command. For example making 1G slices from inputfile with names prefix-aa, prefix-bb,...
split -b1G inputfile prefix-
-16335944 0 How to export/import data from/to datagridview to a Excel file?I am using Microsoft Office 2007 and Visual studio 2010.
I want to save data of DataGridView into Excel file once I click the button on Windows form.
Also I want to load data from Excel file into DataGridView by clicking a button.
Pls help...I am very new to VB so unable to write code. Plsss help..
-32547430 0 Where can I get detailed understanding of mysql-server's codebase?Is there any resource of how mysql's source code (https://github.com/mysql/mysql-server) works? Any flow diagrams related to code's folders and files.
-24883358 0 How to Add custom markers to a google directions map at the start only of multiple journeysFirstly let me say I am not a Java or even web developer. I have pieced together this code via the web and am almost at the finish point - but cannot get over the line.
I am mapping journeys for a trucking firm, and want to use a custom marker at the start of each journey, with no marker at the end of the journey. The attached code does all I need for mapping the journey but I can't get the markers to render on the page. What am I missing?
var directionsService = new google.maps.DirectionsService(); var num, map, data; var requestArray = [], renderArray = []; // A JSON Array containing some people/routes and the destinations/stops var jsonArray = { "Journey1": ["-38.076600, 176.722100", "-38.279641, 175.897505"], "Journey2": ["-38.279641, 175.897505", "-38.058217, 175.783939"], "Journey3": ["-38.058217, 175.783939", "-37.964919, 175.478964"], "Journey4": ["-37.964919, 175.478964", "-38.323678, 175.152163"], "Journey5": ["-38.323678, 175.152163", "-38.274879, 175.894551"], "Journey6": ["-38.274879, 175.894551", "-38.095284, 176.076530"], "Journey7": ["-38.095284, 176.076530", "-38.075316, 176.716276"], "Journey8": ["-38.075316, 176.716276", "-38.076600, 176.722100"] } // 16 Standard Colours for navigation polylines var colourArray = ['Maroon', 'Green', 'Olive', 'DarkBlue', 'Violet', 'Teal', 'Gray', 'Silver']; var Labelarray = [ 'Kawerau Depot, Ex: CHH Kawerau - Cogen Plant Kinleith - Hogfuel - CHH KINLEITH', 'Cogen Plant Kinleith - TD Haulage Pinedale - Empty', 'TD Haulage Pinedale - Gascoigne Farms Cambridge - Post Peeling - Untreated - GASCOIGNE FARMS LTD', 'Gascoigne Farms Cambridge - Tregoweth Te Kuiti - Empty', 'Tregoweth Te Kuiti - CHH Kinleith - Chip - FLL NETLOGIX LTD', 'CHH Kinleith - Mamaku Sawmill Mamaku - Empty', 'Mamaku Sawmill Mamaku - CHH Kawerau - Chip - FLL NETLOGIX LTD', 'CHH Kawerau - Kawerau Depot - Empty']; // Let's make an array of requests which will become individual polylines on the map. function generateRequests() { requestArray = []; for (var route in jsonArray) { // This now deals with one of the people / routes // Somewhere to store the wayoints var waypts = []; // 'start' and 'finish' will be the routes origin and destination var start, finish // lastpoint is used to ensure that duplicate waypoints are stripped var lastpoint data = jsonArray[route] limit = data.length for (var waypoint = 0; waypoint < limit; waypoint++) { if (data[waypoint] === lastpoint) { // Duplicate of of the last waypoint - don't bother // continue; } // Prepare the lastpoint for the next loop lastpoint = data[waypoint] // Add this to waypoint to the array for making the request waypts.push({ location: data[waypoint], stopover: true }); } // Grab the first waypoint for the 'start' location start = (waypts.shift()).location; // Grab the last waypoint for use as a 'finish' location finish = waypts.pop(); if (finish === undefined) { // Unless there was no finish location for some reason? finish = start; } else { finish = finish.location; } // Let's create the Google Maps request object var request = { origin: start, destination: finish, waypoints: waypts, travelMode: google.maps.TravelMode.DRIVING }; // and save it in our requestArray requestArray.push({ "route": route, "request": request }); } processRequests(); } function processRequests() { // Counter to track request submission and process one at a time; var i = 0; // Determines if we will use an image for the icon 1 = true, 0 = false var UseImage = 1; var j = 0; var x = 0; // Used to submit the request 'i' function submitRequest() { directionsService.route(requestArray[i].request, directionResults); } // Used as callback for the above request for current 'i' function directionResults(result, status) { if (status == google.maps.DirectionsStatus.OK) { j++; //j = i + 1 // Create a unique DirectionsRenderer 'i' renderArray[i] = new google.maps.DirectionsRenderer({ suppressMarkers: true }); renderArray[i].setMap(map); renderArray[i].setOptions({ preserveViewport: true, suppressInfoWindows: true, polylineOptions: { strokeWeight: 3, strokeOpacity: 0.8, strokeColor: colourArray[i] } }); //************************************** // this is the code I am trying to add in so that I get a marker only at the start position of the line. // Shapes define the clickable region of the icon. var shape = { coords: [1, 1, 1, 20, 18, 20, 18, 1], type: 'poly' }; // Add markers to the map var image = { url: "Marker Green " + j + ".png", // This marker is 27 pixels wide by 40 pixels tall. size: new google.maps.Size(27, 40), // The origin for this image is 0,0. origin: new google.maps.Point(0, 0), // The anchor for this image is the base of the icon at 14, 39. anchor: new google.maps.Point(14, 39) }; var marker = new google.maps.Marker({ position: new google.maps.LatLng(requestArray[i].request.origin), map: map, icon: image, shape: shape, title: Labelarray[i] + ' - ' + requestArray[i].request.origin, zIndex: i }); //************************************** //end of code I am trying to get to work } // Use this new renderer with the result renderArray[i].setDirections(result); // and start the next request nextRequest(); } function nextRequest() { // Increase the counter i++; // Make sure we are still waiting for a request if (i >= requestArray.length) { // No more to do return; } // Submit another request submitRequest(); } // This request is just to kick start the whole process submitRequest(); } // Called Onload function init() { // Some basic map setup (from the API docs) //Map centre var mapOptions = { center: new google.maps.LatLng(-38.143567, 175.965254), zoom: 9, mapTypeControl: true, streetViewControl: true, zoomControl: true, panControl: true, mapTypeId: google.maps.MapTypeId.ROADMAP }; map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); // Start the request making generateRequests() } // Get the ball rolling and trigger our init() on 'load' google.maps.event.addDomListener(window, 'load', init);
-3878187 0 how to show link "send to" in a Document library in Sharepoint 2010 how to show link "send to" in a Document library in Sharepoint 2010
-16624689 0 Anyone with luck on getting KDevelop work under OSX 10.8.3I got KDevelop to install through macports with no issues, but it is very unstable and crashes straightaway. I tried getting it through fink, but fink is not able to find the package anymore?
So I am pretty much stuck with no solution. Maybe an alternative IDE suggestions?
Do not want textMate, have Sublime2 running, not very happy about Eclipse and Xcode. I see people working vert efficiently with GVIM, with lots of custom plugins. I know it is a steep learning curve but mat very well try it. Maybe a suggestion for a way to get GVIM smooth and functional under OSX? (Python, C++, bash, etc)
Thanks.
-39042083 0 Do I need do clean up after launching TPL tasksI have Windows service that needs to monitor different things in the system (connect to some WCF services, send some data, etc.) every minute.
For that I chose to use Quartz.NET jobs which look as follows:
internal class MonitorLaunchJob : IJob { public void Execute(IJobExecutionContext context) { MonitorBase[] monitors = GetAllMonitors(); foreach (var monitor in monitors) var task = monitor.Launch(); } }
monitor.Launch
is the method with the following signature:
public abstract Task Launch()
The overrides of this method may use long-running operations like await TcpClient.ConnectAsync()
and stuff like that. Those methods track their activity by themselves using a lot of logging, so I don't need to keep track of the Task
returned by monitor.Start()
. I need to just fire and forget.
Now, my question is: what do I do with this task
that Launch
method returns? I can't think of a reason to store it anywhere since it's a fire-and-forget operation. But on the other hand, if a method returns an object, it is weird to just ignore it. Do I need to do any sort of clean-up when the task
is completed? Will I face any performance issues if I just leave the task be and never track its state?
You can use AVMutableComposition
and AVAssetExportSession
Which are available in AVFoundation Framework
For more detail visit apple's reference library AVMutableComposition Class Reference and AVAssetExportSession Class Reference
AVAsset* asset = // Create your asset with source video url AVMutableComposition *videoComposition = [AVMutableComposition composition]; AVMutableCompositionTrack *compositionVideoTrack = [videoComposition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid]; AVAssetTrack *clipVideoTrack = [[asset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0]; AVMutableVideoComposition* videoComposition = [[AVMutableVideoComposition videoComposition]retain]; videoComposition.renderSize = CGSizeMake(320, 240); videoComposition.frameDuration = CMTimeMake(1, 30); AVMutableVideoCompositionInstruction *instruction = [AVMutableVideoCompositionInstruction videoCompositionInstruction]; instruction.timeRange = CMTimeRangeMake(kCMTimeZero, CMTimeMakeWithSeconds(60, 30) ); AVMutableVideoCompositionLayerInstruction* transformer = [AVMutableVideoCompositionLayerInstruction videoCompositionLayerInstructionWithAssetTrack:clipVideoTrack]; CGAffineTransform finalTransform = // setup a transform that grows the video, effectively causing a crop [transformer setTransform:finalTransform atTime:kCMTimeZero]; instruction.layerInstructions = [NSArray arrayWithObject:transformer]; videoComposition.instructions = [NSArray arrayWithObject: instruction]; CGSize videoSize = myVideoComposition.renderSize; CALayer *parentLayer = [CALayer layer]; CALayer *videoLayer = [CALayer layer]; NSLog(@"%f %f",_playerLayer.frame.origin.x,_playerLayer.frame.size.width); parentLayer.frame = CGRectMake( 0, 0 , cropsize.x , cropsize.y ); [videoLayer setPosition:CGPointMake(videoLayer.position.x, videoSize.height)]; [parentLayer addSublayer:videoLayer]; videoComposition.animationTool = [AVVideoCompositionCoreAnimationTool videoCompositionCoreAnimationToolWithPostProcessingAsVideoLayer:videoLayer inLayer:parentLayer]; exporter = [[AVAssetExportSession alloc] initWithAsset:saveComposition presetName:AVAssetExportPresetHighestQuality] ; exporter.videoComposition = videoComposition; exporter.outputURL=url3; exporter.outputFileType=AVFileTypeQuickTimeMovie; [exporter exportAsynchronouslyWithCompletionHandler:^(void){}];
-4718331 0 I had the same problem and finally found the solution. Hope it works for you too. Follow these steps and then try to install the plugin again.
Select Help > Install New Software... Select the Helios update site in the Work with dropdown. If it's not there, you can enter the URL directly: http://download.eclipse.org/releases/helios Install Helios > Web, XML, and Java EE Development > Eclipse Web Developer Tools.
-18607263 0Close the resources in a finally
block, not in a catch
block.
try { // actual code. } catch (IOException e) { // handle exception } finally { try { in.close(); } catch (IOException e) { // handle exception } }
-36107708 0 HTML hyperlink that updates a table field in an Access database I have created a hyperlink in an email that opens an access database.
<'a href='" & "C:\data.final\databaser\FE\shelfstatus_FE.mdb" & "'>LINK<'/a><'/p>
I want to include a statement in the HTML
hyperlink that updates a table in the access database when the user click on the hyperlink.
similar to
"UPDATE date = '2016-03-16' FROM register WHERE number = 1"
-22807565 0 Servlet file upload ismultipartcontent returns false I am trying to upload a selected file from the local file system to a folder within the application. Here technology used is jsp, servlet.
On clicking the Press button of Example.jsp, the control passes to the Request servlet. But the checking that if the request is multi part returns false. so "Sorry this Servlet only handles file upload request" is printed in the console.
Example.jsp
<form action="Request" method="Post" name = "invoices" target="_self"> <div class="invoicetable"> <table> <colgroup> <col class="first" span="1"> <col class="rest" span="1"> </colgroup> <tr> <td>Start date:</td> <td><input type = "text" name = "start_date" id="datepicker" size = "6" maxlength="10"/></td> </tr> <tr> <td>End date:</td> <td><input type = "text" name = "end_date" id="datepicker2" size = "6" maxlength="10"/></td> </tr> <tr> <form action="Request" enctype="multipart/form-data" method="post" name = "upload"> <table> <tr> <td>Input File:</td> <td><input type = "file" name ="datafile" size="30" maxlength="200"/></td> </tr> </table> <div> <input type ="submit" name="invoice" value="Press"/> to upload the file! <input type="hidden" name = "type" value="upload"> </div> </form> </tr> <tr> <td>Regular</td> <td> <input type = "radio" name ="input_type" value="regular"/> </td> </tr> <tr> <td>Manual</td> <td> <input type = "radio" name ="input_type" value="manual" checked/> </td> </tr> <tr> <td>Final</td> <td> <input type = "radio" name ="input_type" value="final"/> </td> </tr> </table> </div> <div style="margin-left: 20px"> <input type ="submit" name="invoice" value="Submit" class="button"/> <input type="hidden" name = "type" value="invoice"> </div> </form>
Request - doPost method
jsp_request = request.getParameter("type"); if (jsp_request.equalsIgnoreCase("upload")) { String file_location = request.getParameter("datafile"); ServletFileUpload uploader = null; //Checking if the request is multipart if(ServletFileUpload.isMultipartContent(request)){ try { String upload_location_holder = request.getServletContext().getRealPath(""); upload_location_holder = upload_location_holder.substring(0,upload_location_holder.indexOf(".")) + upload_location_holder.substring(upload_location_holder.lastIndexOf("/")+1); //excel file goes into the input files folder String excel_name = upload_location_holder + "/WebContent/input_files/" + file_location; File file = new File(excel_name); DiskFileItemFactory fileFactory=new DiskFileItemFactory(); fileFactory.setRepository(file); uploader = new ServletFileUpload(fileFactory); List<FileItem> fileItemsList = uploader.parseRequest(request); Iterator<FileItem> fileItemsIterator = fileItemsList.iterator(); while (fileItemsIterator.hasNext()) { FileItem item = (FileItem) fileItemsIterator.next(); if (!item.isFormField()) { String fileName = item.getName(); String root = getServletContext().getRealPath("/"); File path = new File(root + "/uploads"); if (!path.exists()) { boolean status = path.mkdirs(); } File uploadedFile = new File(path + "/" + fileName); System.out.println(uploadedFile.getAbsolutePath()); item.write(uploadedFile); } } //File uploaded successfully request.setAttribute("message", "File Uploaded Successfully"); } catch (Exception ex) { // request.setAttribute("message", "File Upload Failed due to " + ex); ex.printStackTrace(); } }else{ System.out.println("Sorry this Servlet only handles file upload request"); } }
I tried googling for a possible solution. but didnot land with any answer. Any help appreciated.
-15213345 0 Working example of mediaelement.js flash fallback working on IE9I basically can't get mediaelement.js working on IE9 (and, apparently, even mediaelement.js' home page can't seem to do it). A friend told me to look into forcing IE9 to fall back to flash, so I was hoping to find examples. That effort was both fruitless and futile. So any example site/page that shows that is appreciated.
-27060631 0You have to create an NSMutableParagraphStyle in combination with an NSAttributedString in order to display text as justified. The important part is to set NSBaselineOffsetAttributedName to 0.0.
Here's an example how to put everything together:
let sampleText = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = NSTextAlignment.Justified let attributedString = NSAttributedString(string: sampleText, attributes: [ NSParagraphStyleAttributeName: paragraphStyle, NSBaselineOffsetAttributeName: NSNumber(float: 0) ]) let label = UILabel() label.attributedText = attributedString label.numberOfLines = 0 label.frame = CGRectMake(0, 0, 400, 400) let view = UIView() view.frame = CGRectMake(0, 0, 400, 400) view.addSubview(label)
Credits for NSBaselineOffsetAttributedName: http://stackoverflow.com/a/19445666/2494219
-5032378 0Facebook will do a POST to the URL you specific in the form (http://apps.facebook.com/gcmobtest/). The POST will have a field called "ids" that will contain the user IDs that were selected. http://developers.facebook.com/docs/reference/fbml/multi-friend-input/
Facebook has released a non-FBML version (javascript) of the the friend request that returns the IDs directly, if any were selected. http://developers.facebook.com/docs/reference/dialogs/requests/
In typical Facebook fashion, they released v1.0 on Jan 26 (http://developers.facebook.com/blog/post/453) and released 2.0 on Feb 16 (http://developers.facebook.com/blog/post/464).
-39185255 1 Use pip to Install to a different interpreterI downloaded Python2.7 a while ago to my C:\ directory. After that I downloaded pip to install packages. After that I installed the Anaconda interpreter to a different directory within my user. I prefer to use the Anaconda interpreter but every time I install a package with pip it is put in C:\Python27\Lib\site-packages. Is there any way I can change the install command with pip or some pip config file so that it installs packages to C:\path_to_anaconda_interpreter_in_user\Lib\site-packages?
-30115187 0 Program which copies one string to another using pointers produces no outputI wrote following piece of code which copies from one string to another using pointers.
#include<stdio.h> int main() { char strA[80] = "A string to be used for demonstration purposes"; char strB[80]; char *ptrA; char *ptrB; ptrA = strA; ptrB = strB; puts(ptrA); while(*ptrA != '\0') { *ptrB++ = *ptrA++; } *ptrB = '\0'; puts(ptrB); // prints a new line. return 0; }
Why does puts(ptrB)
print nothing but just a newline ? However puts(ptrA)
prints the value of strA
.
I am assuming the following format:
word definitionkey : definitionvalue [definitionkey : definitionvalue …]
None of those elements may contain a space and they are always delimited by a single space.
The following code should work:
awk '{ for (i=2; i<=NF; i+=3) print $1, $i, $(i+1), $(i+2) }' file
Explanation (this is the same code but with comments and more spaces):
awk ' # match any line { # iterate over each "key : value" for (i=2; i<=NF; i+=3) print $1, $i, $(i+1), $(i+2) # prints each "word key : value" } ' file
awk
has some tricks that you may not be familiar with. It works on a line-by-line basis. Each stanza has an optional conditional before it (awk 'NF >=4 {…}'
would make sense here since we'll have an error given fewer than four fields). NF
is the number of fields and a dollar sign ($
) indicates we want the value of the given field, so $1
is the value of the first field, $NF
is the value of the last field, and $(i+1)
is the value of the third field (assuming i=2
). print
will default to using spaces between its arguments and adds a line break at the end (otherwise, we'd need printf "%s %s %s %s\n", $1, $i, $(i+1), $(i+2)
, which is a bit harder to read).
This works fine for me:
$(".tableClassName tbody tr").each(function() { $(this).find("td:eq(3)").remove(); });
-38275927 0 Make the dictionary value(s) compiled re
that can match your string:
import re productline = '8.H.5' pattern = re.compile(r'tata.xnl.\d\.\d-dev.1.0') pl_component_dict = {'8.H.5': pattern} component_branch = "tata.xnl.1.0-dev.1.0" if pl_component_dict[productline].match(component_branch): print "PASS" else: print "ERROR:Gerrit on incorrect component"
-2293189 0 Try this:
import pandas as pd df = pd.read_csv("email_addresses_of_ALL_purchasers.csv") all_emails = df["Email"] real_emails = [] test_domains = ['yahoo.com', 'gmail.com', 'facebook.com', 'hotmail.com'] for email in all_emails: email_separated = email.split("@") try: if email_separated[1] not in test_domains: real_emails.append(email) except IndexError: print('Mail {} does not contain a @ sign'.format(email)) print real_emails
-28006044 0 Building multiple platform targets at once for the same project I have a managed C# project (targeting Any CPU) that references an unmanaged C++ DLL. I want to deploy my C# project as Any CPU, but my C++ DLL does not have an Any CPU option. My C++ DLL can only target the ARM, Win32, and x64 platforms. For convenience, I would like to build all of those to the same directory as my C# project and have my C# project reference them dynamically; I would like my output directory to contain the ARM, Win32, and x64 versions of my unmanaged DLL. As such, how could I make my solution build multiple platform targets for the same project?
-11622734 0 make tooltip display on click and add a modal to itstrangely, I find it difficult to bind jquery's onclick event handler to this fiddle. I don't even know what I'm doing wrong. The html is as follows:-
<ul> <li><a id="tooltip_1" href="#" class="tooltip" >Trigger1</a><li> <li><a id="tooltip_2" href="#" class="tooltip" >Trigger2</a><li> <li><a id="tooltip_3" href="#" class="tooltip" >Trigger3</a><li> </ul> <div style="display: none;"> <div id="data_tooltip_1"> data_tooltip_1: You can hover over and interacte with me </div> <div id="data_tooltip_2"> data_tooltip_2: You can hover over and interacte with me </div> <div id="data_tooltip_3"> data_tooltip_3: You can hover over and interacte with me </div> </div>
styled this way:-
li { padding: 20px 0px 0px 20px; }
with a jquery like this:-
$(document).ready(function() { $('.tooltip[id^="tooltip_"]').each (function(){ $(this).qtip({ content: $('#data_' + $(this).attr('id')), show: { }, hide: { fixed: true, delay: 180 } }); }); });
you check out the fiddle page I created:- http://jsfiddle.net/UyZnb/339/.
Again, how do I implement a jquery modal-like appearance to it so the tooltip becomes the focus?
-40593732 0Here is a practical answer, courtesy of user Kirill Slatin. Practical use example at the bottom of the answer.
If, like me, you need to use that response object as a scope variable, here's the trick:
This will return "undefined" in the console, and like me, you probably won't be able to use that response data on your page:
$http.get(ArbitraryInput).then(function (response) {$scope.data = response;}); console.log($scope.data);
However, this should work:
$http.get(ArbitraryInput) .then(function (response) { $scope.data = response; $scope.$apply() });
$scope.$apply()
is what will persist the response object so you can use that data.
-
Why would you need to do this?
I'd been trying to create an "edit" page for my recipes app. I needed to populate my form with the selected recipe's data. After making my GET request, and passing the response data to the $scope.form, I got nothing... $scope.$apply()
and Kirill Slatin helped big time. Cheers mate!
Here's the example from my editRecipeController:
$http.get('api/recipe/' + currentRecipeId).then( function (data) { $scope.recipe = data.data; $scope.form = $scope.recipe; $scope.$apply() } );
Hope that helps!
-31230357 0Here is a pure JavaScript library that does just that:
https://github.com/orling/grapheme-splitter
It implements the Unicode UAX-29 standard in all its edge cases that you're likely to miss in a home-brew solution, like non-Latin diacritics, Hangul (Korean) jamo characters, emoji, multiple combining marks, etc.
-10198230 0 Simple way to solve a system of linear equations in Matlab?I'm looking for an easy and fast solution to the following problem: I have three 3D vectors x_i
, three 3D vectors y_i
, a 3D vector b
and a 3x3 matrix A with coefficients a11 - a33 (that are unknown).
The relation is as follows:
x_i = A * y_i + b
That resolves to
x_i_1 = ( a11 * y_1_1 + a12 * y_2_1 + a13 * y_3_1 ) + b_1
etc.
So there are 9 equations and 9 unknown variables a11 - a33, easy peasy math. But how do I solve this system using build in Matlab functions?
-30883783 0there's no such built-in functionality unless you utilize nested datasets that is. you should either implement some specific remote method wrapping all required modifications or enhance midas with extra means (see for example "KT Data Components" lib to get the idea how this could be implemented)
-20001097 0I had answer it in another topic, here is my answer: You are using fork(). It creates a process that is a exactly copy of your actual process, but it don't share the same memory. If you use threads all the memory addressing is going to be shared and you need to synchronized the access to the shared memory position in order to satisfy the data's consistency.
-13384631 0 use RSA private key generated in php to encrypt in cI have a RSA Private Key generated with openssl_pkey_new() in php. I save this in a txt file. Is it posible to use that key for decryptin in c. I tried this but with no success:
RSA *r = PEM_read_RSAPrivateKey("C:/xampp/htdocs/RSA/daten.txt", NULL, NULL, NULL); resultDecrypt = RSA_private_decrypt( 128 /* resultEncrypt*/ , encrypted, decrypted, r, RSA_PKCS1_OAEP_PADDING); printf("%d from decrypt: '%s'\n", resultDecrypt, decrypted); RSA_free ( r );
Thanks!!
-5070564 0 How can I get stumbleupon's database of websites?I'd like to get all the sites which have been added to Stumbleupon. I'd like to add PHP. Is there any API?
-13937077 0 Is it possible to access a private method of parent class from the child class in Java?How do I call a private method in this type of parent class? What I have done is an ugly peice of code but it works though I don't think it's a real solution.
Would really appreciate some advice on how this is done. I have looked to find solution but non that have given me some clarity on the matter.
public abstract class Car { public void passItOn(int a) { takesVariable(a); } private void takesVariable(int a) { //Process the variables }
the child:
public abstract class Wheel extends Car { boolean a = anotherMethod(); if(value() != a) { passItOn(a); } }
There is some issue with my accaptance rate but I am on it! All will give + marks for replies!!!
-4820593 0 How can I use .Net system.drawing.drawstring to write right-to-left string (project is a dll)?Hi I need to create a bitmap file from an string, currently I'm using
Bitmap b = new Bitmap(106, 21); Font f = new Font("Tahoma",5 ); StringFormat sf = new StringFormat(); int faLCID = new System.Globalization.CultureInfo("fa-IR").LCID; sf.SetDigitSubstitution(faLCID, StringDigitSubstitute.National); Brush brush = Brushes.Black; Point pos = new Point(2, 2); Graphics c = Graphics.FromImage(b); c.FillRectangle(Brushes.White, 0, 0, m_width, m_length); c.DrawString(stringText, f, brush, pos,sf);
it works but the problem is it is writing left to right. How can I make DrawString() to write right-to-left? thanx
-536695 0you including your own code. how safe is it?
-12678554 0Why are you talking generics here? And why is Sport knowing about all the sports there are?
You can do something like below, for starters:
public interface IBall { } public class BilliardBall : IBall { } public abstract class Sport { protected abstract IBall Ball { get; } } public class Billiards : Sport { protected override IBall Ball { get { return new BilliardBall(); } } }
-16991135 1 Problems with character-encoding when webscraping with scrapy I have problem with the encoding of the text, I am scraping from a website. Specifically the Danish letters æ, ø, and å are coming out wrong. I feel confident that the encoding of the webpage is UTF-8, since the browser is showing it correctly with this encoding.
I have tried using BeautifulSoup as many of the other posts have suggested, but it wasn't for the better. However, I probably did it wrong.
I am using python 2.7 on a windows 7 32 bit OS.
The code I have is this:
# -*- coding: UTF-8 -*- from scrapy.spider import BaseSpider from scrapy.selector import HtmlXPathSelector from scrapy.item import Item, Field class Sale(Item): Adresse = Field() Pris = Field() Salgsdato = Field() SalgsType = Field() KvmPris = Field() Rum = Field() Postnummer = Field() Boligtype = Field() Kvm = Field() Bygget = Field() class HouseSpider(BaseSpider): name = 'House' allowed_domains = ["http://boliga.dk/"] start_urls = ['http://www.boliga.dk/salg/resultater?so=1&type=Villa&type=Ejerlejlighed&type=R%%C3%%A6kkehus&kom=&amt=&fraPostnr=&tilPostnr=&iPostnr=&gade=&min=&max=&byggetMin=&byggetMax=&minRooms=&maxRooms=&minSize=&maxSize=&minsaledate=1992&maxsaledate=today&kode=&p=%d' %n for n in xrange(1, 3, 1)] def parse(self, response): hxs = HtmlXPathSelector(response) sites = hxs.select("id('searchresult')/tr") items = [] for site in sites: item = Sale() item['Adresse'] = site.select("td[1]/a[1]/text()").extract() item['Pris'] = site.select("td[2]/text()").extract() item['Salgsdato'] = site.select("td[3]/text()").extract() item['SalgsType'] = site.select("td[4]/text()").extract() item['KvmPris'] = site.select("td[5]/text()").extract() item['Rum'] = site.select("td[6]/text()").extract() item['Postnummer'] = site.select("td[7]/text()").extract() item['Boligtype'] = site.select("td[8]/text()").extract() item['Kvm'] = site.select("td[9]/text()").extract() item['Bygget'] = site.select("td[10]/text()").extract() items.append(item) return items
It is the items 'Adresse' and 'Salgstype' that contain æ, ø, and å. Any help is greatly appreciated!
Cheers,
-5019804 0You can compare the php bytecode with bytekit-cli (blogpost) / (github project).
To see if your new and old code produces the same php-bytecode. Knowing that you can be pretty sure everything will work. (If you are using annotations i'm not to sure how that works out with that)
-6610877 0as far as I can see you have a custom comparator (why does that keep a reference to the sorter? looks fishy) not a custom RowSorter.
The intended way to change sorting is to invoke toggleSortOrder(column) on RowSorter. For more fine-grained control you can need access to the DefaultRowSorter, f.i. its setSortKeys method.
-20800425 0JQuery(or any JS lib) needs to be loaded before you use can use it otherwise it will be threated as without jQuery... Load jQuery/jQuery UI in the head instead and you will be fine.
-31617163 0Might be a bit of a dirty fix, but I added the indicated folder to the tmp folder of the project. Still curious about why this happened and if making that actually solved anything.
-7809186 0You need this syntax:
depth := Default(Nullable<Double>);
-969192 0 Technically you can write recursive lambda expressions, but you need to be insane or insanely bright to try (I haven't figured out which). But you can cheat:
Func<Node, decimal> nodeSum = null; nodeSum = node => { decimal result = node.Amount; if (node.Children != null) { result = result + node.Children.Sum(nodeSum); } return result; }; var value = nodeSum(amounts);
-11912623 0 In order to submit POST data, the data must be sent to the server. A hyperlink alone cannot do this - however with a bit of JS magic, you can easily accomplish this.
If you're using something like jQuery, you can capture the click event - gather data from the link based on the click event, and submit to the server via $.post/$.ajax.
HTML:
<a href="javascript:void(0);" class="age-less-then-five">age<5</a>
Javascript:
$('a.classname').click(function(){ var that = $(this), value = that.text().trim(); //you can optionally store a value in the classname, or ID which is what I would do.. in this scenario.. I think XD $.post('yoururl.com/phpscript.php',{postName: value}, function(data){ //load whatever data you want, or redirect to list.html now that you've gathered desired data } });
To clarify the above answer, var that = $(this); refers to the link that's been clicked on. So you could grab the class name from the anchor by: that.attr('class') // which would equal age-less-then-five or simply do as above, and grab the text inbetween the anchor tags by using .text(). We trim here, this really isn't the best way to do this.. but it is one way to do it. When I'm using a link to perform any sort of post to the server, I'll typically use an ID if it holds a unique value, or class name.
-30374196 0 Skew Input Border Without Skewing Text InsideI have a text input
that I'd like to skew using transform:
skewX()`. I want to have the input's borders skewed, while keeping the text inside un-skewed.
Here's the code that I've tried:
#search{ border:2px solid #323232; border-radius: 0; padding:3px 10px; -moz-transform: skewX(-40deg); -webkit-transform: skewX(-40deg); -o-transform: skewX(-40deg); -ms-transform: skewX(-40deg); transform: skewX(-40deg); } ::-webkit-input-placeholder{ -moz-transform: skewX(40deg); -webkit-transform: skewX(40deg); -o-transform: skewX(40deg); -ms-transform: skewX(40deg); transform: skewX(40deg); } :-moz-placeholder { -moz-transform: skewX(40deg); -webkit-transform: skewX(40deg); -o-transform: skewX(40deg); -ms-transform: skewX(40deg); transform: skewX(40deg); } ::-moz-placeholder { -moz-transform: skewX(40deg); -webkit-transform: skewX(40deg); -o-transform: skewX(40deg); -ms-transform: skewX(40deg); transform: skewX(40deg); } :-ms-input-placeholder { -moz-transform: skewX(40deg); -webkit-transform: skewX(40deg); -o-transform: skewX(40deg); -ms-transform: skewX(40deg); transform: skewX(40deg); }
<form id="search-form" action="/idee" accept-charset="UTF-8" method="get"><input name="utf8" type="hidden" value="✓" /> <input type="text" name="search" id="search" placeholder="Search" /> </form>
because 0< bi3 <1, so an integer result is 0. Try BigDecimal
in place of BigInteger
No, there is no such default 'application console' attached to JWS apps.
-1306478 0 Where is the jar file for EJB3 annotations for JBoss 5?This should be simple, but I'm at a complete loss.
I'm working through a tutorial for setting up some MBeans in JBoss 5.0. It has an example like this:
@Remote public interface Calculator { public double getInterestRate(); public double calculateTotalInterest(double presentValue, int years); public double calculateFutureValue(double presentValue, int years); }
I'm trying to find the jar file that contains the data for the @Remote annotation, and I cannot seem to find which jar file I need. A google search gives me little to nothing that seems to apply to JBoss 5.0. Any help would be much appreciated.
-33158914 0 case-esac; syntax error: newline unexpected (expecting ")")I'm getting crazy for an easy case but can't find what I missing. they told me the next error:
name.sh: 21: name.sh: syntax error: newline unexpected (expecting ")")
my code is that one (the error is the line of the case):
#!/bin/bash while true do clear echo "________________________________________________________" echo "1) Encontraren el disco ficheros que contengan un patrón" echo "2) Tamaño de un directorio y su contenido" echo "3) Exit" echo "________________________________________________________" echo -e "\n" echo -e "Introduce una opción (1/2/3): \c" read answer case "$answer" in 1) ls ;; 2) cal ;; 3) exit ;; esac echo -e "pressiona enter per continuar \n" read input done
-40172465 0 Replace words in UITextView with custom view I'm dealing with a tricky situation related to an editable UITextView
. When the user writes certain words on a UITextView
I want to replace those words with a "tag" displaying an icon, the word (or words) and another icon.
just like this image:
I'm facing several problems here:
Already made some tests with DTRichTextEditor and was able to detect the target words to highlight them changing their attributes, but this is way different.
-6538571 0If you follow the link below you can import the number_format php function to javascript. The function has been helping me for years now.
Here is the function signature :
function number_format (number, decimals, dec_point, thousands_sep)
http://phpjs.org/functions/number_format:481
-15930810 0 METAPOST: using loop variables in labelsDear stackoverflowers,
recently, while playing around with the METAPOST enviroment, I encountered a problem. While drawing something using the loop 'for' macro I needed the value of the loop variable to be correctly displayed inside a label, however I could not figure out how to do that and Mr.Google was unable to help me. Below is an example of the code I used:
for i=1 upto N: label(btex $here should be the value of i$, some_position); endfor;
Any kind of help will be appreaciated :]
-9832772 0Calling strtotime("4pm")
will give you the time for today at 4pm. If it's already past 4pm, you can just add 60*60*24
to the given timestamp
// Example blatantly copied from AndrewR, but it uses strtotime $nextfourpm = strtotime("4pm"); if ($nextfourpm < time()) { $nextfourpm += 60*60*24; }
-10493252 0 I think you are having this problem because of restrictions imposed by the Google Content Security Policy. It mentions that iniline javascript like the one that you have mentioned in you code will not be executed. Try removing the onclick="getSite()"
from your HTML markup to content_script.js
. Use addEventListener
function to attach the event to the button.
A common use case is to provide the current loggedin user property to controllers and routes as in https://github.com/kelonye/ember-user/blob/master/lib/index.js and https://github.com/kelonye/ember-user/blob/master/test/index.js
-36333370 0You can download jar from below link
http://www.java2s.com/Code/Jar/d/Downloaddynamicreportscore310jar.htm
Or If you are using maven then just add below dependency to your pom.xml file
<dependency> <groupId>net.sourceforge.dynamicreports</groupId> <artifactId>dynamicreports-core</artifactId> <version>3.1.3</version> </dependency>
XHTML page
<h:commandLink id="summary_jasper" actionListener="#{workReportBean.prepareJasperReport()}"> <p:graphicImage name="/images/jasper.png" title="Jasper"/> </h:commandLink>
Managed Bean //Just provide DB_NAME, CREDENTIALS and TABLE_NAME, JASPER report will be created for you
public void prepareJasperReport(){ Map<String, String> columnNameNTypeMap = new HashMap<String, String>(); Connection connection = null; try { Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection( "jdbc:mysql://localhost:3306/DB_NAME", "USER", "PASSWORD"); ResultSet rsColumns = null; DatabaseMetaData meta = connection.getMetaData(); rsColumns = meta.getColumns(null, null, "TABLE_NAME", null); while (rsColumns.next()) { columnNameNTypeMap.put(rsColumns.getString("COLUMN_NAME"), rsColumns.getString("TYPE_NAME")); }} catch (SQLException e) { e.printStackTrace(); return; } catch (ClassNotFoundException e) { e.printStackTrace(); return; } // a new report JasperReportBuilder report = DynamicReports.report(); // populating new report with TABLE object report.setDataSource("select * from TABLE_NAME;", connection); // creating COLUMNS // add extra datatypes if your table have ex. long, float etc for (Map.Entry<String, String> entry : columnNameNTypeMap.entrySet()){ if(entry.getValue().equalsIgnoreCase("int")){ report.columns(Columns.column(entry.getKey(), entry.getKey(), DataTypes.integerType())); }else if(entry.getValue().equalsIgnoreCase("varchar")){ report.columns(Columns.column(entry.getKey(), entry.getKey(), DataTypes.stringType())); }else if(entry.getValue().equalsIgnoreCase("bit")){ report.columns(Columns.column(entry.getKey(), entry.getKey(), DataTypes.booleanType())); }else if(entry.getValue().equalsIgnoreCase("datetime") || entry.getValue().equalsIgnoreCase("date")){ report.columns(Columns.column(entry.getKey(), entry.getKey(), DataTypes.dateType())); } } report.title(Components.text("Summary Report").setHeight(40) .setStyle(DynamicReports.stl.style() .setBold(true).setFontSize(16).setForegroundColor(Color.BLUE) .setAlignment(HorizontalAlignment.CENTER, VerticalAlignment.MIDDLE))); report.setColumnTitleStyle(DynamicReports.stl.style().setBold(true)); report.setColumnStyle(DynamicReports.stl.style().setHorizontalAlignment(HorizontalAlignment.LEFT)); report.setHighlightDetailEvenRows(true); report.pageFooter(Components.pageXofY()); try { // show the report report.show(false); // export the report to a pdf file //report.toPdf(new FileOutputStream("d://report.pdf")); } catch (DRException e) { e.printStackTrace(); } /*catch (FileNotFoundException e) { e.printStackTrace(); }*/ }
-10009022 0 How to add subView to another view from third view? its pretty simple to understand the problem i have.
i have a view called "Menu" - which have few buttons. i have another view called "Main" - who need to show the view selected by the menu. and last one i have the view that i want to see in the main view.
i tried to work this out with this code -
-(IBAction)opertunity:(id)sender{ OpertunityViewController *temp = [[OpertunityViewController alloc]initWithNibName:@"OpertunityViewController" bundle:nil]; MainViewController *main = [[MainViewController alloc]init]; [main.handlerView addSubview:temp.view]; }
but it's not working at all.. i remember i done it many many times in the past but just cant get the answer in my projects... pretty strange /:
UPDATE - im trying something else. i made a method in my main class and i call it from the menu. but still it dosent work - and i NSLOG the method and its called perfectly. (when im calling the method from inside the class its working..)
what now ?! i've never had this kind of problem...
-36766308 0 Wrap recursive files/dirs iteration with PromiseI need to check some directories tree for files and then create same directories structure on the server, and also create files list to upload to server. So I realise I need to wrap my dirs iterators with promise so I can get final file list on ".then()":
export function uploadHandler(filesAndDirs, currentDirectory) { return (dispatch, getState) => { filesToUpload = []; iterate(filesAndDirs, currentDirectory).then((whatResolved) => { console.log(whatResolved + ' is resolved'); // console.log(filesToUpload); }); } }
But I faced some trouble while resolving my promise, cause working with recursion I dont know exactly which file/dir is the last one:
function iterate(filesAndDirs, currentDirectory) { return new Promise(function(resolve) { for (let i = 0; i < filesAndDirs.length; i++) { if (typeof filesAndDirs[i].getFilesAndDirectories === 'function') { let dir = filesAndDirs[i]; createDirectory(dir.name, currentDirectory._id).then((directory) => { dir.getFilesAndDirectories().then((subFilesAndDirs) => { iterate(subFilesAndDirs, directory).then(() => { if (i + 1 == filesAndDirs.length) resolve('+++ by dir'); }); }); }); } else { filesToUpload.push({ file: filesAndDirs[i], directory: currentDirectory }); // If last item is file then I need to resolve the main promise // but same time if I will resolve promise here then // whole chain will break couse subdirectories handling async } }; }); }
I made it works for [dir] input but I cant handle it if [dir, file] input. What can I do here? Maybe its just bad idea to use Promise here?
-24471126 0 How to track if location services is enabled or not enabled? titaniumI am able to turn it off.
code:
//get current Location // Titanium.Geolocation.accuracy = Titanium.Geolocation.ACCURACY_BEST; Titanium.Geolocation.distanceFilter = .25; var overlays = require('overlays'); //check if gps is enabled exports.checkGPS = function(windowCur) { Ti.Geolocation.accuracy = Titanium.Geolocation.ACCURACY_BEST; // make the API call var wrapperW = overlays.wrapperOverlay(windowCur); Ti.Geolocation.getCurrentPosition(function(e) { // do this stuff when you have a position, OR an error if (e.error) { Ti.API.error('geo - current position' + e.error); //put overlay on overlays.GPSError(windowCur); return; }else{ //alert(JSON.stringify(windowCur)); wrapperW.hide(); } }); };
This works fine at getting whether the user has turned on or off their location services. An overlay is put on the screen informing the user they need to turn it on, if they have turned it off.
However the problem is after the user has set it, and then goes into settings -> location services and enabled it, I am unable to take the overlay off as I have know way off tracking in real time if it has been turned on or off.
Does anyone know how this can be achieved, cheers.
UPDATE:
This did the trick
var wrapperW = null; Titanium.Geolocation.addEventListener('location', function(e) { if (e.error) { //put overlay on wrapperW = overlays.GPSError($.win); } else { //keep updating Ti.API.info(e.coords); if (wrapperW != null) { wrapperW.hide(); } } });
-18946558 0 Why don't you use the for
construct?
{% for user in all_entries_user %} Do your thing with {{ user }} {% endfor %}
-4711005 0 Boxing/unboxing - only value types? Ref.types - casting? From MSDN I read that boxing/unboxing is for treating value types as objects. But when I read about ArrayList, it reads that it does boxing as well. So I am quite confused as ArrayList holds value and reference types as objects. Also the following is not unboxing in terms of terminology, its just casting?
ArrayList a=new ArrayList(); a.Add(someClass); someClass x=(someClass)a[0];
-28373575 0 I fixed this by adding e.stopImmediatePropagation(); to the event handler:
$('.nav-tabs li a').click(function(e){ e.preventDefault(); e.stopImmediatePropagation(); $(this).tab('show'); });
edit: fixed class selector as per comment.
-4014523 0 Flash - image used in movie footageI saw this site, http://en.tackfilm2.se/, whereby a user is asked to upload an image, which is then used throughout the movie footage.
Can anyone provide some direction / guidance in how this is implemented?
Thanks in advance for any responses.
-11797898 0The AOT can be found in the development workspace. To open the development workspace, use Ctrl + Shift + W. To open the AOT, use Ctrl + D.
-4138515 0Technically speaking, a list is already a map keyed on the index of the item in the list.
-10425651 0Did you try Google? Seems like it could be caused by a few things. Since it only crashes on the server, my first guess would be that ASP.NET doesn't have write permission in the folder you're saving to. See here:
-34560773 0 Confuse terms in Angular JS tutorialI'm following a tutorial and I have difficulties to understand a certain sentence which talks about the problem that can occur when naming my properties in Angular:
It quietly tolerates all property access errors, including nested properties on nonexistent parents and out-of-bounds array access.
aliasing variables as a way to cope with variable shadowing
My english is good enough to know what is written, but I really don't understand what is "nested properties on nonexistent parents" and "aliasing variables as a way to cope with variable shadowing". I did some research, but couldn't clearly understand.
Could someone give me a clear explanation?
-37571384 0An easy option you can try is this method from the Bitmap
class.
You can select the compression format of a bitmap and to optimise either the quality, or the file size. A downside is that the you need to get a Bitmap
instance to start the compression, which may be something you don't want to do.
This query will give you all the results you need, you can change date to variables in case you need different dates.
SELECT Plate_Number, MAX(kilometer) as max,MIN(kilometer) as min, (max - min) as result, sum(litters) as litters, date FROM log_table WHERE date BETWEEN 5 AND 9 GROUP BY Plate_Number
EDIT
In case you always need max and min date, you can change it like
WHERE date BETWEEN (SELECT DISTINCT min(date) FROM log_table) AND (SELECT DISTINCT max(date) FROM log_table)
-18164218 0 jQuery .blur() does not fire nor does .focusout()? New to jquery so it is possible I've missed a vital element somewhere along the lines. I've been digging for the past couple of hours and have tried several solutions but nothing I've tried solves the delima. All I'm trying to do is execute some code once "textboxUsername" loses focus. In straight javascript I used to do this by adding an onblur() event to the specific input element and call a function. Any advice appreciated...
HTML:
<div> <div class="heading"> <span class="inside_heading">Register</span> </div> <div class="content_under_heading"> <div class="rounded_div"> <ul class="ulRegister"> <li class="descLabel"> Username: </li> <li class="inputInfo"> <input type="text" id="textboxUsername"/> </li> <li class="successCheck" id="usernameSuccessCheck"> <img id="usernameCheckImage" src="templates/images/check.png" class="noShow"/> <img id="usernameXImage" src="templates/images/check.png" class="noShow"/> </li> </ul> <label id="labelUsernameExists" class="registerIssue"></label> </div> </div> </div>
JavaScript
$(document).ready(function(){ //textboxUsername blur event $("#textboxUsername").blur(function(){ var possibleUsername = $("#textboxUsername").val(); if(possibleUsername.length != 0){ if(possibleUsername.length < 6){ //display message var message = "Usernames must be at least 6 characters"; $("#labelUsernameExists").text(message); } else{ //ajax } } }); });
-13243430 0 How to solve this variable pass into batch_date? I want to pass in @batch date into batch_date...But it shows error...The error is
Column 'dbo.tnx_tid_InvCheck_Details.Batch_Date' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
The InvCheck_Details
table has batch_date
for each and every part_no
. I want to group the part_no so that I can count(tid) and sum(tid_bal) by part_no. What should i do in order to run this script? TQ...
DECLARE @batch_date datetime SET @batch_date = '2012-10-13 00:00:00.000' CREATE TABLE #inv_check (batch_date datetime,part_no varchar(25),Number_of_tid int,Updated_DT int, Tot_Tid_Bal int) INSERT INTO #inv_check SELECT batch_date,part_no,COUNT(tid)as Number_of_tid,0,sum(Tid_Bal) FROM dbo.tnx_tid_InvCheck_Details where batch_date = @batch_date Group by part_no order by part_no UPDATE #inv_check SET Updated_DT = isnull(d.Updated_DT,0) --select i.part_no,i.Number_of_tid, isnull(d.Updated_DT,0) FROM #inv_check i LEFT OUTER JOIN (SELECT part_no, COUNT(LastUpdate_DT)as Updated_DT, sum(tid_bal) as Tid_bal_sum FROM dbo.tnx_tid_InvCheck_Details Where NOT LastUpdate_DT IS NULL Group by part_no) d on i.part_no=d.part_no DECLARE @sql int DECLARE @sql1 int SELECT @sql1 = count(part_no) FROM #inv_check SELECT @sql = count(part_no) FROM #inv_check WHERE number_of_tid= Updated_DT SELECT @sql AS Parts_Counted,@sql1 AS Full_Parts Drop table #inv_check
-26103949 0 table INSERT using While loop While I've read many answers here, this is my first question on stackoverflow and I'm reasonably new to SQL. I am trying to use a WHILE loop (SQL Server 2008) to insert some records into a table. Here's the data I'm starting with:
SeasID FacilityID PL Zone Section Row FromSeat ToSeat 11 17 1 g2 cf a 1 5 32 18 14 w13 r2 c 10 12
I need to insert a row for every unique seat into a new table. Here's what I'd like to insert:
SeasID FacilityID PL Zone Section Row Seat 11 17 1 g2 cf a 1 11 17 1 g2 cf a 2 11 17 1 g2 cf a 3 11 17 1 g2 cf a 4 11 17 1 g2 cf a 5 32 18 14 w13 r2 c 10 32 18 14 w13 r2 c 11 32 18 14 w13 r2 c 12
I've tried many things and I don't think I understand loops very well yet. Any help you can provide would be great. Thanks
Matt
-29865487 0 Drawing to the backgroundI'm creating a website that lets the user draw to the background with a color he chooses. I also want to let the user to change the background color with a hex color picker tool.
The latter is easy but how can I let the user draw to the background? Is it possible to use canvas as the background?
Should I create the whole background entire of small divs which color I would change when the user is drawing?
-36859468 0you can use item's tag, top,bottom to change item's height.
<?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@android:id/background" android:top="5dp" android:bottom="5dp"> <color android:color="@color/red"/> </item> <item android:id="@android:id/progress" android:top="5dp" android:bottom="5dp"> <clip> <color android:color="@color/blue"/> </clip> </item> </layer-list>
-10820922 0 You could save some trouble by using filter_var
instead.
if (false !== ($url = filter_var($url, FILTER_VALIDATE_URL))) { echo "$url is a valid url"; }
You can optionally add these options as the third parameter (use binary or to combine them):
FILTER_FLAG_PATH_REQUIRED
FILTER_FLAG_QUERY_REQUIRED
I wrote a blog post on this awhile back. The first part is about when a thread can be aborted, the second is about how it actually works.
I hadn't ever seen any correct (in this case, complete) documentation about how it actually works, so I wrote about about it.
The jist is that the CLR will use SetThreadContext (a win32 api) to hijack your current IP and move you into a special stub to set up the thread abort if you're thread isn't in an abortable wait.
-27508926 0I have the same problem remove legend in your code
legend: "Vendas Mensais"
Flw manolo
-30331828 0ImportError: No module named rest_client
-3103373 0I'm not very aware of MySQL specific data modeling tools, but there's no infrastructure to add columns to every table ever created in a database. Making this an automatic behavior would get messy too, when you think about situations where someone added the columns but there were typos. Or what if you have tables that are allowed to go against business practice (the columns you listed would typically be worthless on code tables)...
Development environments are difficult to control, but the best means of controlling this is by delegating the responsibility & permissions to as few people as possible. IE: There may be 5 developers, but only one of them can apply scripts to TEST/PROD/etc so it's their responsibility to review the table scripts for correctness.
-28421709 0 Why does the signature of deriveHCons declare `HK <: Symbol` when Symbol is a final classHere is the signature of deriveHCons
in LabelledProductTypeClassCompanion
of Shapeless:
implicit def deriveHCons[HK <: Symbol, HV, TKV <: HList] (implicit ch: Lazy[C[HV]], key: Witness.Aux[HK], ct: Lazy[Wrap[TKV] { type V <: HList }] ): Wrap.Aux[FieldType[HK, HV] :: TKV, HV :: ct.value.V] = ...
It seems strange to me that we declare a type parameter HK
that must derive from Symbol
when Symbol
is a final class. How can anything but Symbol
replace the type parameter HK
? If HK
is always Symbol
, this signature would be less imposing if it got rid of HK and substituted Symbol in the type signature directly would it not?
You can not to use prepare
result without check.
It able to return false
if any error occured.
if ($resolve = $data_base->prepare("INSERT INTO links VALUES('',?,?)")) { $resolve->bind_param("ss",$link, $short); // Problematic frame $resolve->execute(); } else { // You can get error message here printf("Error: %s.<br/>\n", $resolve->error); // assumed this is mysqli $resolve->close(); }
May be you get sql syntax error, about your insert query should be like this:
INSERT INTO links (long_url, title) VALUES (?, ?);
-34245177 0 What you are looking for is called
Structural Search/Replace
.It is not very well documented but it is Extremely Powerful once you grok it completely.
There are a few examples in the
Existing Templates
that you can probably modify and learn from, the following will do what you are asking for now.
Go to the Menu: Edit -> Find -> Replace Structurally
and use the following Search Template
.
System.out.println($EXPRESSION$);
Check Case Sensitive
and make File Type
= Java Source
Set the Scope
of the search to Project Files
for everything.
If you want to just remove it all you can just make sure the Replace Template
field is blank.
You could comment them all out with a Replace Template
of //System.out.println($EXPRESSION$);
or /* System.out.println($EXPRESSION$); */
Use the
Structural Search/Replace
to addprivate static final Logger L = LoggingFactory($Class$.class);
to all the classes with theSystem.out.println()
statements.
Then replace all the System.out.println($EXPRESSION$);
with L.info($EXPRESSION$);
You can even do things sophisticated things like the following:
This is just an example idea, the body of the catch
needs to only have the the System.out.println($EXPRESSION$)
a more sophisticated block to grab other expressions and keep them would be an exercise for the reader.
try { $TryStatement$; } catch($ExceptionType$ $ExceptionRef$) { System.out.println($EXPRESSION$); }
with
try { $TryStatement$; } catch($ExceptionType$ $ExceptionRef$) { L.error($EXPRESSION$); }
-24427857 0 How to add a specific event handler to a unspecified control?Always use a
Logger
instead ofSystem.out.println()
in everything. Even inscratch
classes used for experimenting, they eventually end up in production code at some point!
I'm looking to try and create something like the following:
If the user leaves the last textbox (for example let's say TextBox8), then a new textbox is created below textbox8 with the name textbox9. I have this part, but how would I make it so that if textbox9 is left, the same events happen, so on and so forth?
Private Sub TextBox8_LoseFocus(sender As Object, e As System.EventArgs) Handles TextBox8.LostFocus ' Textbox 9 creation code which then creates the next textbox etc. End Sub
If anybody can offer a better way of doing this sort of thing
-2302079 0What the commenters have suggested is that all the javascript should be placed on external files. According to my understanding what you are doing is:
<script language="javascript"> your code here </script>
Instead you should have.
<script src="myjavascript.js" type="text/javascript"></script>
Then your javascript files will be automatically cached by the browser.
MindFold also goes on to suggest using google's CDN . which is a good suggestion. Of course you can only use it for popular libraris like Jquery.
-7717753 0As far as I know, yes. One of the big improvements in GTK 3 was to make it much easier to automatically generate bindings to other languages.
In the meantime you might want to check out Vala, a C#-like language that supports GTK 3.
-10551149 0 link to external .js file does not workI currnently have my files place on a virtual server (USB Webserver V8.2). Now when go on the server, open the page nothing happens. I know its something to do with the link path name, but I have tried changing the link in many different ways but nothing.
<script type="text/javascript" src="/root/help_page_code.js"></script>
-3557179 0 Based on your final comment, can you have the destructor of your star
class do a delay? See for example the sleep
or usleep
functions.
You need to get the current <script>
tag, which in this case is the last one:
var thisScript = document.scripts[document.scripts.length - 1];
and insert the <iframe>
after it:
var parent = thisScript.parentElement; parent.insertBefore(iframe, thisScript.nextSibling);
http://jsfiddle.net/mattball/Tz75x/
Or simply replace the current script with the <iframe>
:
var parent = thisScript.parentElement; parent.replaceChild(iframe, thisScript);
http://jsfiddle.net/mattball/a23XE/
Alternately – if you can believe it – document.write()
is actually a suitable solution here, so long as you do it while the document is loading and not in a window.onload
callback:
function createIframe() { document.write('<iframe src="//example.com"></iframe>'); } createIframe();
http://jsfiddle.net/mattball/2YCcP
-34738403 0cherlietfl is right.
The problem is that you break the reference to the messages array since you assign a new array to messages inside your get function. But concat
is doing this as well.
Try this:
Restangular.all('/api/messages/').getList({'_id': userId}).then(function(docs){ messages.splice(0, messages.length); // clear the array messages.push.apply(messages, docs); //add the new content });
-2079615 0 Seeking good practice advice: multisite in Drupal I'm using multisite to host my client sites.
During development stage, I use subdomain to host the staging site, e.g. client1.mydomain.com.
And here's how it look under the SITES folder:
/sites/client1.mydomain.com
When the site is completed and ready to go live, I created another folder for the actual domain, e.g. client1.com. Hence:
/sites/client1.com
Next, I created symlinks under client1.com for FILES and SETTINGS.PHP that points to the subdomain
i.e.
/sites/client1.com/settings.php --> /sites/client1.mydomain.com/settings.php /sites/client1.com/files --> /sites/client1.mydomain.com/files
Finally, to prevent Google from indexing both the subdomain and actual domain, I created the rule in .htaccess to rewrite client1.mydomain.com to client1.com, therefore, should anyone try to access the subdomain, he will be redirected to the actual domain.
This above arrangement works perfectly fine. But I somehow feel there is a better way to achieve the above in much simplified manner. Please feel free to share your views and all advice is much appreciated.
-13861780 0 SVG: dynamic size based on text, merging objects<div style="float: left; padding: 10px; border: 1px solid; background: #ccc">random text</div>
Is there a way to achieve something like this in SVG? I mean to have a rectangle and a text and:
a) rectangle's width and height are dynamic, so when I change the text, the rectangle adjust its size
b) when I move the rectangle, the text goes with it
And would it be easier to achieve something like this in <canvas>
?
EDIT:
<defs> <text id="text1" x="90" y="100" style="text-anchor:start;font-size:30px;"> THIS IS MY HEADER</text> </defs> <filter x="0" y="0" width="1" height="1" id="background"> <feFlood flood-color="gray"/> <feComposite in="SourceGraphic"/> </filter> <use xlink:href="#text1" fill="black" filter="url(#background)"/>
Erik Dahlström proposed something like this. How to put padding to the background, how to add eg. shadow or border to the rectangle? And, this doesn't work in IE9, so I cannot accept it. I could just use <foreignObject>
if there was a support for it in IE.
And I just figured out the answer for b) point of my question. You have to put both elements in the group:
<g> <rect x="0" y="0" width="100" height="100" fill="red"></rect> <text x="50" y="50" font-size="14" fill="blue" text-anchor="middle">Hello</text> </g>
And then you can move the group using transform
param:
<g transform="translate(x, y)">
Seems to work correct in every browser.
-5771910 0The standard ListView has a property called checkboxes
that can be set to true.
If you use that then you don't have to mess with making your own checkboxes.
I've never had any problems with checkboxes not showing properly in this control.
This property works best in ViewStyle:= vsList
or ViewStyle:= vsReport
Alternatively if you want checkboxes on some items but not on others then make a picture of a checkbox (1 unchecked, 1 checked) and add both of them to an ImageList.
If an item needs a checkbox, set its ImageIndex property to that of the unchecked item. If it needs to be checked, set its ImageIndex property to the checked Image.
This works in ViewStyle:= vsReport
and ViewStyle:= vsList
.
You are using a custom ListView (TsListView
) control, try using a standard ListView instead and see if the strange behaviour shows up.
This does not explain why your method stops so soon, but you need to take care of it or you will have an even stranger problem with the result data being completely garbled.
From the APi doc of DataInputStream.read():
Reads some number of bytes from the contained input stream and stores them into the buffer array b. The number of bytes actually read is returned as an integer.
You need to use that return value and call the write() method that takes and offset and length.
-22904893 0You can not declare objects at runtime they way you art trying. You can store the week days in array / List<T>
starting Monday at index 0
and Sunday at index 6
, You can give id of element with the string name you want.
List<TextBox> weekList = new List<TextBox>(); weekList.Add(new TextBox()); weekList[0].ID = "txt" + ViewState["temp"].ToString();
-21200703 0 try this, use-
Intent intent = new Intent(Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_URI);
then, in your onAcitivityResult:
Uri contact = data.getData(); ContentResolver cr = getContentResolver(); Cursor c = managedQuery(contact, null, null, null, null); // c.moveToFirst(); while(c.moveToNext()){ String id = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID)); String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); if (Integer.parseInt(c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) { Cursor pCur = cr.query(Phone.CONTENT_URI,null,Phone.CONTACT_ID +" = ?", new String[]{id}, null); while(pCur.moveToNext()){ String phone = pCur.getString(pCur.getColumnIndex(Phone.NUMBER)); textview.setText(name+" Added " + phone); } } }
You can also check this link for more help- How to call Android contacts list?
-525803 0 How can I trust the behavior of C++ functions that declare const?This is a C++ disaster, check out this code sample:
#include <iostream> void func(const int* shouldnotChange) { int* canChange = (int*) shouldnotChange; *canChange += 2; return; } int main() { int i = 5; func(&i); std::cout << i; return 0; }
The output was 7!
So, how can we make sure of the behavior of C++ functions, if it was able to change a supposed-to-be-constant parameter!?
EDIT: I am not asking how can I make sure that my code is working as expected, rather I am wondering how to believe that someone else's function (for instance some function in some dll library) isn't going to change a parameter or posses some behavior...
-11429875 0Here is an example which works well:
C:\Program Files\WinRAR>rar a -hpabc h:\abc.rar c:\pdf
So you can follow the example in your codes.
p.StartInfo.Arguments = String.Format("a -hp{0} {1} {2}", your password, Destination, SourceFile); p.Start();
-36724305 0 Streams - Merge 2 Lists Issue faced on the way to merge 2 Lists using Streams. At present when I use the Stream.concat it is adding to the bottom of the list, which is not what I want.
List1:
List 2:
Ideal Merged Output:
If the above is not possible, then below also acceptable
Output I am getting at present, which is not what i want
Code:
List<List<XSSFCell>> listData1 = list1.stream().skip(1).collect(Collectors.toList()); List<List<XSSFCell>> listData2 = list2.stream().skip(1).collect(Collectors.toList()); Stream stream = Stream.concat(listData1.stream(),listData2.stream());
Hope the issue I face is clear, await guidance.
Added This question has been marked as duplicate of this question But am unable to find StreamUtils.zip method which is mentioned in the solution. The first answer in that question, states take it at your own risk. Can this be done with the standard available libraries or can I know how I can get zip method in StreamUtils
-4889540 0You could always create a service that returns a Stream and use the JsonSerializer
to serialize your objects into a MemoryStream
, and then return the MemoryStream
from the service:
public Stream GetSomeObject(int groupId) { byte[] bytes; var serializer = new JavaScriptSerializer(); switch(groupId) { case 2: var groups = GetGroups(); // fill the groups however bytes = Encoding.UTF8.GetBytes(serializer.Serialize(groups)); break; case 3: var customers = GetCustomers(); bytes = Encoding.UTF8.GetBytes(serializer.Serialize(customers)); break; } return new MemoryStream(bytes); }
In that case, you would simply load the appropriate object into memory based on the parameters and return the appropriate strongly typed object via the Stream
.
This is the same approach I've used in the past to return Json results from a WCF Service without the type information (the approach was suggested by a member Microsoft's WCF team, so I figured it was fairly reliable).
-9005697 0Grouping by Linn (town) and Nimi (name) tells the db engine to give you one row for each combination of town and name, and show you the maximum Vanus (age) for each of those combinations. And logically, that's not what you want. You want the name of each person whose age is the same as the maximum age in that town.
First verify you can retrieve the max age for each LinnID.
SELECT LinnID, Max(Vanus) As MaxOfVanus FROM Myyjad GROUP BY LinnID;
If that works, you can save it as "qryTownAge", then use it in another query where you join it (on LinnID) with Linnad. That will allow you to retrieve the matching Linn.
SELECT l.LinnID, l.Linn, q.MaxOfVanus FROM Linnad AS l INNER JOIN qryTownAge AS q ON l.LinnID = q.LinnID ORDER BY l.Linn;
If that works, save it as qryTownAge2. Then try this query.
SELECT q.Linn, q.MaxOfVanus, m.Nimi FROM qryTownAge2 AS q INNER JOIN Myyjad AS m ON ( m.LinnID = q.LinnID AND m.Vanus = q.MaxOfVanus ) ORDER BY q.Linn;
If that all works, you could create a single query which does it all. However, doing it step by step should help us pinpoint errors.
-34090865 0You can force this by avoiding the background image altogether as you replace it with a regular image in the <img>
tag. Layer containers of content (one with the image and another with text) on top of each other with absolute position and z-index. It's a workaround to the background image problems I've experienced similar to yours and the layers provide nice flexibility for managing content.
#z1 { z-index: 1; } #z2 { z-index: 2; padding: 5%; color: white; } #z1, #z2 { position: absolute; left: 0px; top: 0px; }
<div id="outer"> <div id="z1"> <img width="100%" src="http://www.verolago.com/blog/wp-content/uploads/2013/11/sailboat.jpg" /> </div> <div id="z2"> <p>I'm on a boat!</p> </div> </div>
While it is not free (but $39), FireDaemon has worked so well for me I have to recommend it. It will run your batch file but has loads of additional and very useful functionality such as scheduling, service up monitoring, GUI or XML based install of services, dependencies, environmental variables and log management.
I started out using FireDaemon to launch JBoss application servers (run.bat) but shortly after realized that the richness of the FireDaemon configuration abilities allowed me to ditch the batch file and recreate the intent of its commands in the FireDaemon service definition.
There's also a SUPER FireDaemon called Trinity which you might want to look at if you have a large number of Windows servers on which to manage this service (or technically, any service).
-21870733 0 How To Store Extension in a variable-Asterisk PBXDoes anyone know how to store the extension of an incoming caller (caller provisioned on the PBX) in a variable. I need to do this within the asterisk dialplan just after the call is answered.
;Answer call exten => 1234,1,Answer() ;Store caller's extension in a variable
-23900854 0 JS Variable from Form Input FYI: I have to use data-label
as a selector for other reasons..
I need to store values from a form to use later via js, so that when a user toggles a radio button the values will be re-inserted into the form inputs.
How do I store the values, then re-insert them when the user clicks a radio button? Here's where I am at:
// user clicks initially, then the values would be stored.. $('[data-label="FrenchCheckbox"] [data-label="State1"] [data-label="Checkbox"] [data-label="Unchecked"]').click(function() { // want to store the initial value now!! // ..then translating the form inputs to another lang $('[data-label="Create StepWizard"] [data-label="CreateAssetInput"]').each(function(i, ele) { var tString = $(ele).val(); if(tString.length <= 0) return; var tSrc = 'en'; var tDst = 'fr'; var key = 'my api key'; var tUrl = "https://www.googleapis.com/language/translate/v2?key=" + key + "&source=" + tSrc + "&target=" + tDst + "&q=" + tString; $.get(tUrl, function(response) { $(ele).val(response.data.translations[0].translatedText); }); }); });
Then when the user clicks the radio button (first line below) reinsert the initial values into the form fields?
$('[data-label="LanguageRadioButtons"] [data-label="French"] [data-label="Radio Button"] [data-label="Initial"] ').click(function() { // how do I reinsert the values from the initial input? });
Thanks for your ideas!
-832548 0 Code is displayed even with entries in the databaseThe following code continues to be displayed even if there are entries in my database and I don't understand why. Am I missing something? I'm not sure if this makes sense, but help would be great. :)
if($numrows==0) { echo"<h3>Results</h3>"; echo"<p>Sorry, your search: "".$escaped."" returned zero results</p>"; }
-26990895 0 how to make sql query with and in yii active record? I am new in Yii. Now i have encountered problem with active record in yii.
So , I have normal sql here :
$sqlText = "SELECT * FROM tbl_webservicetokens WHERE clienttoken = '{$appToken}' AND systimestamp < expiredate";
I want to use active record. But i endeavored
$post=TBLWEBSERVICETOKENS::model()->find( 'CLIENTTOKEN=:appToken AND EXPIREDATE>:systimestamp', array( ':appToken'=>$appToken, ':systimestamp'=>'systimestamp'));
But i had error! any idea?
-16014612 0 php mysql prepare statement not workingI'm currently learning php and mysql and am trying to build an authentication webpage where the user registers and is able to log in to a member protected page. The registration process works fine but for some reason I'm getting this error in my login execution script.
Fatal error: Call to a member function prepare() on a non-object in /homepages/8/d459264879/htdocs/tymbi_reg/login_exec.php on line 40
Line 40 is here if($stmt = $mysqli->prepare("SELECT * FROM member WHERE username=? AND password =?"))
I've been trying hard to find where the problem is without any success.
This is the code that I'm using in my login script
<?php session_start(); require_once('connection.php'); $errmsg_arr = array(); $errflag = false; $username = $_POST['username']; $password = $_POST['password']; if($username == '') { $errmsg_arr[] = 'Username missing'; $errflag = true; } if($password == '') { $errmsg_arr[] = 'Password missing'; $errflag = true; } if($errflag) { $_SESSION['ERRMSG_ARR'] = $errmsg_arr; session_write_close(); header("location: index.php"); exit(); } else { if($stmt = $mysqli->prepare("SELECT * FROM member WHERE username=? AND password =?")) { $stmt->bind_param("ss", $username, $password); $stmt->execute(); $stmt->store_results(); if($stmt->num_rows > 0) { $SESSION['username'] = $username; header("Location: home.php"); } else { $error['alert'] = "Username or password are incorrect"; } } } ?>
Here's my connection.php code
<?php $con=new mysqli("test","test","test","test"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } ?>
And yes, I have replaced the test values with my details
-32480591 0In Python 3.5, the async for
syntax is introduced. However, asynchronous iterator function syntax is still absent (i.e. yield
is prohibited in async
functions). Here's a workaround:
import asyncio import inspect class escape(object): def __init__(self, value): self.value = value class _asynciter(object): def __init__(self, iterator): self.itr = iterator async def __aiter__(self): return self async def __anext__(self): try: yielded = next(self.itr) while inspect.isawaitable(yielded): try: result = await yielded except Exception as e: yielded = self.itr.throw(e) else: yielded = self.itr.send(result) else: if isinstance(yielded, escape): return yielded.value else: return yielded except StopIteration: raise StopAsyncIteration def asynciter(f): return lambda *arg, **kwarg: _asynciter(f(*arg, **kwarg))
Then your code could be written as:
@asynciter def countdown(n): while n > 0: yield from asyncio.sleep(1) #or: #yield asyncio.sleep(1) n = n - 1 yield n async def do_work(): async for n in countdown(5): print(n) asyncio.get_event_loop().run_until_complete(do_work())
To learn about the new syntax, and how this code works, see PEP 492
-4377999 0 Mapping vs compositionIf I have two classes with a one-to-one relationship, when's a good time to use mapping.
class A { ... } class B { ... } class C { Map<A,B> a2b; }
And when's a good time to use composition?
class A { B myB; } class B { ... }
Would the answer change if the relationship was one-to-many and many-to-many?
-20352463 0.preformatted { white-space: pre-wrap; }
I think "pre-wrap" is better. It can help with long length in line.
-28691842 0Try this :
DateTime SelectedDate = MyDatePicker.Date.Date;
-254195 0 The accept attribute expects MIME types, not file masks. For example, to accept PNG images, you'd need accept="image/png". You may need to find out what MIME type the browser considers your file type to be, and use that accordingly. However, since a 'drp' file does not appear standard, you might have to accept a generic MIME type.
Additionally, it appears that most browsers may not honor this attribute.
The better way to filter file uploads is going to be on the server-side. This is inconvenient since the occasional user might waste time uploading a file only to learn they chose the wrong one, but at least you'll have some form of data integrity.
Alternatively you may choose to do a quick check with JavaScript before the form is submitted. Just check the extension of the file field's value to see if it is ".drp". This is probably going to be much more supported than the accept attribute.
-21290403 0 WebSockets and HTTPS load balancersI cannot find authoritative information about how WSS interacts with HTTPS proxies and load balancers.
I have a load balancer that handles the SSL (SSL off-loading), and two web servers that contains my web applications and handle the requests in plain HTTP. Therefore, the customers issue HTTPS requests, but my web servers get HTTP requests, since the load balancer takes care of the SSL certificates handling.
I am developing now an application that will expose WebSockets and SSL is required. But I have no clear idea about what will happen when the load balancer gets a secure HTTPS handshake for WSS.
Will it just relay the request as normal handshake to the web server? WebSockets use a "Upgrade:WebSocket" HTTP header that is only valid for the first hop (as there is also "Connection:Upgrade", will this be a problem?
Cheers.
-11465822 0 Zend_Validator_Regex throws error: Internal error while using the patternMessage: Internal error while using the pattern "(http://)?(www.)?(youtu)((be.com)|(.be))/.*"
$element = new Zend_Form_Element_Text($this->name); $element->setRequired(true) ->setLabel(FileTypes::$names[$this->fileType]) ->setDescription('Paste YouTube link here') ->setDecorators(FormDecorators::$simpleElementDecorators) ->addValidator('regex', false, '(http://)?(www\.)?(youtu)((be\.com)|(\.be))/.*');
Throws error even with simple regular expression.
-40914724 0The third parameter is a delegate
. So every iteration you could specify what your indexing variable shall do inside the delegate.
EDIT: Ok found a working solution: As already suggested by Dmitry Bychenko you should still start from 0 and just add the startValue
as an offset
int something = 16; int startValue = 3; int stepSize = 2; List<int> numbers = Enumerable.Range(0, 20).ToList(); Parallel.For(0, something / 2, i => { int ind = (stepSize * i) + startValue ; Console.WriteLine(numbers[ind]); });
-2816678 0 Do I need to rebuild application after adding a new iPhone in ad hoc distribution? I'm using Ad Hoc distribution to send preview/beta version of my iPhone apps to customers for approval. I'm always sending a zipped application and mobileprovision files.
Sometimes however I encountered situation when nothing in the application changed but we needed to add a new device for testing.
I've added a device in Provisioning portal and assigned it to a provisioning profile my application uses for ad hoc distribution. I've downloaded new mobileprovision file and imported it to xcode now the question is do I need to rebuild the application to enable the app on a new device or would it be enough to just send old build with updated mobileprovision file?
-2464709 0Regex can't parse XML and shouldn't be used to parse fake XML. You should do one of
ConfigParser
module.lxml.etree
.Implementing a bad solution now for future needs that you have no way of defining or accurately predicting is always a bad approach. You will be kept busy enough trying to write and maintain software now that there is no good reason to try to satisfy unknown future needs. I have never seen a case where "I'll put this in for later" has led to less headache later on, especially when I put it in by doing something completely wrong. YAGNI!
As to what's wrong with your snippet other than using an entirely wrong approach, angled brackets have a meaning in regex.
-5364113 0Since the only reason not to use Stream
s is that it can be tricky to ensure the JVM isn't keeping references to early conses around, one approach I've used that's fairly nice is to build up a Stream
and immediately convert it to an Iterator
for actual use. It loses a little of Stream
's nice properties on the use side especially with respect to backtracking, but if you're only going to make one pass over the result it's frequently easier to build a structure this way than to contort into the hasNext
/next()
model of Iterator
directly.
Just make use of arrays:
import java.util.Scanner; import java.util.Random; public class HangmanAssignment { static Scanner numIn = new Scanner(System.in); static Scanner strIn = new Scanner(System.in); // Used to hold the user's previous guesses into a string. static StringBuffer buffer = new StringBuffer(); public static void main(String[] args) { String category, word, displayWord = ""; int wordLength, position, lettersRemaining, totalLives = 10; boolean isGuessInWord; char guess; StringBuffer prevGuessedLetters; char temp []= new char [20]; category = getCategory(); word = getWord(category); // Gets the length of the word. wordLength = word.length(); for(int i =0; i <wordLength;i++) temp[i]='*'; lettersRemaining = wordLength; System.out.println("The length of your word is: " + wordLength + " characters."); // Generates as many '*' as long as word's length and stores it in 'displayWord'. for (int i = 0; i < wordLength; i++) { displayWord += "-"; // System.out.println(displayWord); /* Testing */ } while (lettersRemaining > 0 && totalLives > 0) { // Prompts user to guess a letter. System.out.println("Guess a letter (Note: there are " + wordLength + " letters)"); guess = strIn.findWithinHorizon(".", 0).charAt(0); // Checks if the letter guessed in within 'word'. isGuessInWord = (word.indexOf(guess)) != -1; // Checks if the guess is in within 'word'. if (isGuessInWord == false) { totalLives--; System.out.println("Sorry, but '" + guess + "' was not in the word."); if (totalLives < 1) { System.out.println("It seems like you have no lives left! :("); } else if (totalLives == 1) { System.out.println("Careful! You only have 1 life left!"); } else { System.out.println("You still have " + (totalLives) + " lives left!"); } } else { System.out.println("Nice one! The letter '" + guess + "' was in the word!"); for (position = 0; position < wordLength; position++) { for (position = 0; position < wordLength; position++) { if (word.charAt(position) == guess) { temp[position]=guess; /* displayWord.charAt(position).equals(word.charAt(position)); */ lettersRemaining--; } } } } for(int i = 0;i<wordLength;i++){ System.out.print(temp[i]); } // Holds the user's previously guessed letters and the number of letters in the word that are still unknown. System.out.println(); prevGuessedLetters = buffer.append(guess); System.out.println("Previously guessed letters: " + (prevGuessedLetters)); System.out.println("Letters remaining: " + (lettersRemaining)); System.out.println(""); // Checks win/lose conditions. if (lettersRemaining == 0) { System.out.println("Congratulations, '" + word + "' was the correct answer!"); } if (totalLives < 1) { System.out.println("Sorry, you lose!"); System.out.println("The correct answer was '" + word + "'."); { break; } } } } public static String getCategory() { String category; System.out.println("====================================="); System.out.println("Welcome to the Hangman Game!"); System.out.println("====================================="); while (true) { System.out.println("Choose from the following categories:"); System.out.println("1. Car Brands"); System.out.println("2. Countries"); System.out.println("3. Animals"); System.out.println("4. Fruit"); System.out.println(""); category = strIn.nextLine(); if (category.toLowerCase().equals("1") || (category.toLowerCase().equals("one"))) { category = "car brands"; } else if (category.toLowerCase().equals("2") || (category.toLowerCase().equals("two"))) { category = "countries"; } else if (category.toLowerCase().equals("3") || (category.toLowerCase().equals("three"))) { category = "animals"; } else if (category.toLowerCase().equals("4") || (category.toLowerCase().equals("four"))) { category = "fruit"; } if (category.toLowerCase().equals("car brands") || category.toLowerCase().equals("countries") || category.toLowerCase().equals("animals") || category.toLowerCase().equals("fruit")) { System.out.println(""); System.out.println("Nice Choice! You have chosen the '" + category + "' category!"); System.out.println(""); break; } else { System.out.println("Sorry, but '" + category + "' is not a valid input. Try Again!"); System.out.println(""); } } return category; } public static String getWord(String category) { String[] carBrandsWord = {"toyota", "ferrari", "honda", "hyundai", "lamborghini", "dodge", "ford", "chevrolet", "fiat", "lexus", "volkswagen", "acura", "audi", "bentley", "bugatti", "buick", "cadillac"}; String[] countriesWord = {"canada", "england", "france", "switzerland", "australia", "sweden", "greece", "italy", "mexico", "brazil", "india", "china", "russia", "japan", "spain", "ireland"}; String[] animalsWord = {"cat", "dog", "parrot", "bear", "tiger", "monkey", "zebra", "hippopotamus", "chicken", "horse", "cow", "starfish", "squid", "wolf", "hyena", "cheetah", "penguin"}; String[] fruitsWord = {"apple", "banana", "orange", "grapes", "grapefruit", "apricot", "cherry", "guava", "kiwi", "mango", "melon", "olive", "pineapple", "strawberry", "watermelon"}; String word = ""; if (category.toLowerCase().equals("car brands")) { Random random = new Random(); int index = random.nextInt(carBrandsWord.length); word = (carBrandsWord[index]); } else if (category.toLowerCase().equals("countries")) { Random random = new Random(); int index = random.nextInt(countriesWord.length); word = (countriesWord[index]); } else if (category.toLowerCase().equals("animals")) { Random random = new Random(); int index = random.nextInt(animalsWord.length); word = (animalsWord[index]); } else { Random random = new Random(); int index = random.nextInt(fruitsWord.length); word = (fruitsWord[index]); } return word; } }
-28024613 0 You can access object properties in two ways:
objectName.propertyName
or objectName[propertyName]
so in your case:
addeles[b].innerHTML = "<img src='"+ jsonLoader["slider1"][b].coverlink +"'/>"
or to make it dynamic:
var string = "slider1"; addeles[b].innerHTML = "<img src='"+ jsonLoader[string][b].coverlink +"'/>"
Source: http://www.w3schools.com/js/js_objects.asp
-16267760 0Edit: str::from_char
has been deprecated. Use String::from_char
or char::to_string()
instead:
fn main() { io::println(String::from_char(1, 'c')); }
Digging through the documentation a bit, I found the from_char
function. Try:
fn main() { io::println(str::from_char('c')); }
-19486719 0 you can add class active to your home link in your html, you don't need javascript to handle this.
<li><a href="#Home" class="scroll active">Home</a></li> //-^^^^^^--here
well if incase you want then you can use eq..
$('.scroll:eq(0)').addClass('active');
inside your document.ready function
-24118963 0 convert json file to string present in a sd cardand print it in a text view. so that every time i run the app if the folder is present in sdcard then it fetches json fron there else it makes the folder and we insert the json manually in to it.
-3930705 0I'm unsure if this would work, but you might try using a view that's the same size as the iPhone screen, set the autosize flags on that to keep it in the middle of the screen without stretching it, then put all of your views inside that view.
-1664824 0Dont know id its the best solution but for instance looks better than iterate.
DataRowView drv = (DataRowView)source.AddNew(); grupoTableAdapter.Update(drv.Row); grupoBindingSource.Position = grupoBindingSource.Find("ID", drv.Row.ItemArray[0]);
-25386436 0 Why don't you just call shellcode right away? Instead of getting it's pointer and calling it through the pointer.
If you want to do something similar in VB.NET it'll look like this.
Function Func() As Integer Return 1 End Function Delegate Function FuncDelegate() As Integer Sub Main() Dim ret As FuncDelegate ret = AddressOf Func Console.WriteLine(ret()) End Sub
-3529465 0 To my knowledge, there is no such rule. The rule is to hit the database as least as possible, and rails gives you the right tools for that, using the joins.
The example Sam gives above is exemplary. Simple code, but behind the scenes rails has to do two queries, instead of only one using a join.
If there is one rule that comes to mind, that i think is related, is to avoid SQL where possible and use the rails way as much as possible. This keeps your code database agnostic (as rails handles the differences for you). But sometimes even that is unavoidable.
It comes down to good database design, creating the correct indexes (which you need to define manually in migrations), and sometimes big nested structures/joins are needed.
-38518218 0Add padding:0
to nav ul #logo
.wrapper { max-width: 1120px; margin: 0 auto; } nav { background-color: #F7FDFE; } nav ul li { display: inline-block; color: #45494D; float: right; padding: 10px; font-size: 14px; } nav ul #logo { float: left; font-size: 30px; padding:0; }
<nav> <div class="wrapper "> <ul class="cf"> <li id="logo">LOGO</li> <li>SIGN IN</li> <li>LOCTION</li> <li>TEAM</li> <li>ABOUT</li> </ul> </div> <!-- wrapper end --> </nav>
I'm trying to write a Java RegEx that will extract the domain name from a list of domains, sub-domains, and multi sub-domains.
There are too many domains to maintain with the RegEx I have written, and there is a lot more out there. https://publicsuffix.org/list/effective_tld_names.dat
What is a better way to capture the domain name? The goal is to remove the subdomain, extract the domain name so I can resolve or ping it.
This is the RegEx I have come up with
(\w*.(?:\.co|\.org|\.net|\.int|\.edu|\.gov|\.mil|\.arpa|\.tv|\.aero|\.asia).*)
Here is a sample list I am testing against.
comnettest.google.com doubleclick.net googleapis.com imrworldwide.com bom.gov.au www.bom.gov.au googleapis.com www.google.com www.twiiter.com dynamic.t2.tiles.virtualearth.net domain.com 1-A.domain.com 1-A.2-B.domain.com 1-A.2-B.3-C.domain.com mt0.google.com twitch.tv stream.twitch.tv streamcom.com.au network.google.com
-24628444 0 The problem is that I had another <UI>
element later in Product.wxs
that I did not remember about.
Removing this second <UI>
block solved the problem.
Aside from the non-C++-ness of your code, the exact problem is that name
is a pointer to chars, and ""
is an array of chars. The code name == ""
returns false, since name does not point to the first char in the array. Instead, you'll want to check if already allocated array is empty, by checking if the NULL terminator is the first character. if (name[0] == '\0')
Now for the C++ ness: don't use char*
, use std::string
. Also, your code to keep prompting if you got invalid data is backwards.
You can use SASS or less for this. you have some variables and switch value on switching theme.
-18548901 0Seems like either the img has margin or it's container has padding set to non-zero. If you post a link to the page, where this bug is, it will be much easier to see where the problem is.
-24727701 0 adding a column to a table with different parametersI am trying to enter 2 tables into one output my problem is that the parameter is pulling from 2 different columns. I need to be able to show what was completed and the work ordered for a months period. I do not get any errors as the script is written but after 3 hours I stopped it from running.
If I change the join on the @Ordered
to iAuditID
from EffectiveDate
it takes a few seconds to run, but it does not pull the correct information then. I only need the count of ordered audits to be correct and in the @data
table and correct. Work may have been ordered a few months before it was completed, therefore I need to be able see how much work is coming in each month and what is being completed.
I am using SQL 2008.
DECLARE @StartDate datetime, @EndDate datetime, @iClientID int, @iServiceLevelID int SET @StartDate = '1-1-13' SET @EndDate = '12-30-13' SET DATEFIRST 7 DECLARE @TB1 TABLE (EffectiveDate datetime, iAuditID int, iClientID int, iServiceLevelID int) INSERT INTO @TB1 SELECT dateadd(month, datediff(month, 0, a.dtClosedDate),0) AS EffectiveDate, a.iAuditID, a.iClientID, a.iServiceLevelID FROM vwtblAudit a WHERE (a.dtClosedDate >= @StartDate) AND (a.dtClosedDate <= @EndDate) AND (a.iClientID = @iClientID OR @iClientID is null) AND (a.iServiceLevelID = @iServiceLevelID or @iServiceLevelID is null) GROUP BY dateadd(month, datediff(month, 0, a.dtClosedDate),0), a.iClientID, a.iAuditID, a.iServiceLevelID DECLARE @Ordered TABLE (EffectiveDate datetime, iAuditID int, iClientID int, iServiceLevelID int, dtOpenDate int) INSERT INTO @Ordered SELECT dateadd(month, datediff(month, 0, a.dtOpenDate),0) AS EffectiveDate, a.iAuditID, a.iClientID, a.iServiceLevelID, Count(a.dtOpenDate) as Ordered FROM tblAudit a WHERE (a.dtOpenDate >= @StartDate) AND (a.dtOpenDate <= @EndDate) AND (a.iClientID = @iClientID OR @iClientID is null) AND (a.iServiceLevelID = @iServiceLevelID or @iServiceLevelID is null) GROUP BY dateadd(month, datediff(month, 0, a.dtOpenDate),0), a.iClientID, a.iServiceLevelID, a.iAuditID order by iClientID, EffectiveDate DECLARE @DATA table(iclientID int, sClientCode varchar(8), sClientName varchar(50), iServiceLevelID int, sServiceLevelName varchar(50), EffectiveDate datetime, iAuditCount int, Completed int) SELECT tblClient.iclientID, tblClient.sClientCode, tblClient.sClientName, tblServiceLevel.iServiceLevelID, TB1.EffectiveDate, COUNT(*) AS iAuditCount, COUNT(Ordered.dtOpenDate) as Ordered FROM @TB1 TB1 INNER JOIN tblClient ON TB1.iClientID = tblClient.iClientID INNER JOIN tblServiceLevel ON TB1.iServiceLevelID = tblServiceLevel.iServiceLevelID join @Ordered Ordered on TB1.EffectiveDate=Ordered.EffectiveDate GROUP BY tblClient.iClientID, TB1.iServiceLevelID, tblclient.sClientCode, tblClient.sClientName, tblServiceLevel.iServiceLevelID, tblServiceLevel.sServiceLevelName, TB1.EffectiveDate return SET DATEFIRST 7
Every a from the @data
worked like it should, but I was ask to add the work coming in, so I added @ordered
table to bring in the correct information. The data is still correct except for the ordered column. See sample below:
clientID ClientCode ClientName iServiceLevelID EffectiveDate iAuditCount Ordered 0001 1001 Sample 1 Jan 2014 104 19(this number should be 134)
-40356893 0 You have one serious problem here:
struct sockaddr_in *local = malloc(sizeof (struct sockaddr_in *));
because you're just allocating the size of a pointer instead of the size of the struct itself.
This should of course be:
struct sockaddr_in *local = malloc(sizeof (struct sockaddr_in));
if (bind(s, (struct sockaddr *)&local, sizeof(local)) < 0)
This should be:
if (bind(s, (struct sockaddr *)local, sizeof(*local)) < 0)
-1194651 0 Just a thought, but perhaps referencing with the fully qualified path "http://..." is what's causing FF3 and Chrome to think you're attempting cross domain? Switch to using relative paths, and see what happens.
-33400097 0It seems when you try to add more elements to it, and it needs to allocate more space, it does so by copying the last element it currently holds. This seems to assume that any element in the vector is fully valid, and as such a copy will always succeed.
Both sentences are not really correct. When vector runs out of space it, yes, performs reallocation, but of all the elements and these are copied to the new location or possibly moved. When you push_back
or emplace_back
, and reallocation is needed, the element will generally by copied: if an exception is thrown during that, it will be treated as if you had never added the element. If vector
detects a noexcept
user-defined move constructor ( MoveInsertable
concept), elements are moved; if this constructor though is not noexcept
, and an exception is thrown, the result is unspecified.
The objects have guards, but I never considered adding guards to a copy constructor as I assumed we would never be copying an invalid object (which vector forces) :
vector
copies its value_type
: it does not care whether what it contains is valid or invalid. You should take care of that in your copy control methods, whose scope is exactly to define how the object is passed around.
CopiedClass::CopiedClass(const CopiedClass& other) : member(other.member) { member->DoSomething(); }
The obvious solution would be to check if member
is valid and act thereby.
if (member.internalData.isValid()) member->DoSomething() // acknowledge this.member's data is invalid
We don't know how member
is represented, but Boost.Optional is what you may be looking for.
Is it possible to prevent std::vector from copying that element?
Reallocation is something vector
is expected to commit so, no, you can't. reserv
-ing space could avoid that, but maintaining code to handle that would not really be painless. Rather, prefer a container like std::forward_list
/std::list
.
Other solutions:
unique_ptr<decltype(member)>
, but pointers are not often a real solutionSo my question is if translating a library into another language makes it “derivative work”
Yes.
and if so is it enough to open-source just the library, or must the entire application using it be published under LGPL as well?
If it is a good-faith translation (i.e. without any other changes), only the library needs to be open-sourced.
In the mean time the license was changed to LGPL (for the original JavaScript version), but does this affect the translated versions or are they still pure GPL?
Any translation or other derivative work based solely on version X of a software is not affected by the licenses of any other versions of the software, earlier or later. So yes they would still be GPL, unless explicitly changed.
This is not legal advice and I'm not a lawyer.
-7432425 0Riffing off Qerub's answer - if the arrays are sorted as in the example zip can be a great tool for this:
arr1 = [{:day => 12, :sum_src => 1234}, {:day => 14, :sum_src => 24543}] arr2 = [{:day => 12, :sum_dst => 4234}, {:day => 14, :sum_dst => 342334}] arr1.zip(arr2).map {|a,b| a.merge!(b)}
Result
[{:day=>12, :sum_dst=>4234, :sum_src=>1234}, {:day=>14, :sum_dst=>342334, :sum_src=>24543}]
-7266285 0 You could map it to ctrl
or shift
easily, which won't conflict with your OS like command
, via:
nmap <C-t> :CommandT<CR> # or nmap T :CommandT<CR>
In normal fuzzyfinder to search through a directory you can use file globs, like **
, e.g., at the fuzzyfinder prompt:
>File>**/yourpattern
Will search all directories under the current directory for your pattern. Just be wary not to try to do that on large filesystems, or you're going to be waiting a while and/or running out of memory. It will index the tree in memory after the first search though, and will be faster afterwards.
-3559511 0An alternative method is to host the file on your local IIS server. One problem I ran into when doing this was that the default IIS installation does not give your application the correct permissions when using "Pass Through Authentication". Therefore, make sure that the "Pass Through Account" has read access to the path where your video file is located. Usually, the "Pass Through Account" is the same account that your application's app pool is using. For normal installations this will be the Network Service built-in account.
-15293620 0 How to remove white lines when using Google Maps API on iPad?I'm using custom styling to create a blue map using Google Maps API V3.
It renders fine across different browsers on a desktop, but when I view it on an iPad there is a vertical white line present. Further, when scrolling there's a horizontal line, as shown in the photo above.
Here is a JSFiddle example of my code in action.
var myOptions = { zoom: 5, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP, disableDefaultUI: true, styles: styles };
JSFiddle of custom colour styling
Is there a way to remove or smooth out these lines?
-26620940 0 android camera error - error queuing buffer to SurfaceTexture, -32Does anyone have an idea what would cause the below error?
queueBuffer: error queuing buffer to SurfaceTexture, -32
I'm using SurfaceTexture and android.hardware.Camera in my app. The above error occurs when I try to start/stop preview and open/close camera too many times.
Below are the error logs:
10-27 15:39:54.173 I/ActivityManager( 2329): Process com.google.process.gapps (pid 20050) (adj 1) has died. 10-27 15:39:54.213 E/SELinux (23446): [DEBUG] seapp_context_lookup: seinfoCategory = default 10-27 15:39:54.213 D/dalvikvm(23446): Process 23446 nice name: com.google.process.gapps 10-27 15:39:54.213 D/dalvikvm(23446): Extra Options: not specified 10-27 15:39:54.213 I/ActivityManager( 2329): Process com.google.android.gms (pid 23282) (adj 1) has died. 10-27 15:39:54.243 D/SecCameraCoreManager( 1888): disableMsgType: 0xffff 10-27 15:39:54.243 D/Camera_HAL( 1888): atom_disable_msg_type msg_type=0x0000ffff 10-27 15:39:54.243 D/SecCameraCoreManager( 1888): stopPreview 10-27 15:39:54.243 D/SecCameraCoreManager( 1888): virtual void android::SecCameraCoreManager::stopPreview():stop IT Policy checking thread 10-27 15:39:54.243 D/ShotSingle( 1888): stopPreview 10-27 15:39:54.243 D/Camera_HAL( 1888): atom_disable_msg_type msg_type=0x000003c2 10-27 15:39:54.243 V/ShotSingle( 1888): stopPreview(1) 10-27 15:39:54.243 D/Camera_HAL( 1888): atom_stop_preview 10-27 15:39:54.243 E/Surface ( 1888): queueBuffer: error queuing buffer to SurfaceTexture, -32 10-27 15:39:54.243 E/Camera_PreviewThread( 1888): Surface::queueBuffer returned error -32
-30641308 0 Google app engine behind the scenes? Can someone please help me in understanding how the Google app engine actually works with Wordpress?
I have successfully deployed a project which uses wordpress - all my media files, and plugins work, I uploaded my DB with the correct paths - what I want to understand is that when I press deploy, where does the project actually deploy? If I want to modify a file in the installation on google, how do I do that? To sum it up, how does it work behind the scenes?
-37945089 0 CLR library dependency path, Java hostI'm writing a sort of device interface in C# and Java. The C# interfaces with the native device libraries and runs a long living worker thread that polls for data. It does some processing and stores its data in an internal queue.
The Java part starts the worker thread and polls its internal queue. The thread is separate from the main JVM thread.
The trouble is that when I load the C# library, it cannot find the device library dependency. It tries to look in the system dirs and the JVM dir (The Bridge.LoadAndRegisterAssemblyFrom method simply calls the system assembly loader). I resorted the manually opening and loading that dependency from the Java host.
Is there a way to set the CLR library path. I'm not too experienced with .Net, so there might be a generic way, not just for jni4net.
-18638125 0 How to properly use qRegisterMetaType with multidimensional arrays?I want to use something like
typedef double Matrix[4][4];
to represent transformations and also pass them around with the QT signal/slot mechanism. But when I use
Q_DECLARE_METATYPE(Matrix)
it throws an error in qmetatype.h at this function
void *qMetaTypeConstructHelper(const T *t) { if (!t) return new T(); return new T(*static_cast<const T*>(t)); }
saying: "error C2075: 'Target of operator new()' : array initialization needs curly braces"
-544979 0The Microsoft trained and best practice methodology is as follows:
Keep in mind that an MDF technically works similarly to a hard drive partition when it comes to storing data. The MDF is a randomly read file, whereas the LDF is a sequentially read file. Therefore splitting them into separate drives causes a huge performance gain, unless running solid state drives, in which case the gain is still there.
-30480178 0 innerText auto truncating long text inside a DOM elementI am trying to access the content inside a td element through the JavaScript innerText property (inside an excel VBA macro). It works perfectly for all cases except for this one case where the text inside the td element is very long (greater than 85982 characters).
Upon inspection of the text extracted by innerText, I found that innerText seems to be truncating the text after a certain length. Note that this doesn't happen for other cases where the text size is small.
Also, it seems that Mozilla's textContent property has a similar problem as well. I tried accessing the truncated part of the text using the developer console in Firefox for the aforementioned DOM element, but it seems that text isn't there in the extracted content (but the not truncated text is there - just like with innerText).
Does anyone know how to bypass this restriction? Is there some internal limit on these functions?
Here's my VBA code that has this problem:
MyInnerText = objElement.ChildNodes(3).innerText
Here's an equivalent code run in the Firefox console which has the same problem:
var t = document.getElementsByName("chapter11")[0].parentNode.children[3].textContent; t.match("some text that is in the part being truncated.");
For Firefox, this problem seems to go away if I inspect the element, and click "Show all 3396" nodes. After those nodes are visible, the textContent does not truncate the text anymore.
Please do note that I want to be able to extract the text from inside a VBA script using the Internet Explorer object.
-18690702 0 Find addresses within given radiusI have a requirement to find all the addresses within given radius. I have implemented following to get done this.
Google Places API
This only provide business addresses within the radius.And it accept radius as a parameter. https://maps.googleapis.com/maps/api/place/textsearch/json?key=myAPIKey&location=6.914701,79.973085&radius=100&sensor=false&hl=en&query=*
Google reverse geocoding
It's just converting given lat & lng to addresses. This doesn't actually meet my requirement.And it is not accepting radius as a parameter. http://maps.googleapis.com/maps/api/geocode/json?latlng=6.914701,79.973085&sensor=false
Is there any way to get all addresses within given radius. Specially resident addresses.
-37363465 0 Pass data from Application to the ActivityMy android Application class instance is listening to the third-party service for the event. Then the event is coming out, I need to notice my Activity about it. What is the right way to do that? I know about startActivity() method, but my Activity is running yet!
-9735526 0 MVC design for archived data viewImplementation of a standard archive process in ASP.Net MVC. Backend SQL Server 2005
We've an existing web app built in MVC. We've an Entity "Claim" and it has some child entities like ClaimDetails, Files, etc... A pretty standard setup in DB. Each entity has its own table and are linked via FK. Now, we need to have an "Archive" feature in web app which will allow admin to archive a Claim and its child entities. An archived Claim shud become readonly when visited again.
Here're some points on which I need your valued opinion -
To keep it simple and scalable (for a few million records) for now we plan to simply add a bit field "Archived" to the Claim table in db. And change the behavior accordingly in the web app.
We've a 'Manage claim' page which renders a bunch of diff views for Claim and its child entities. Now, for a readonly view we can either use the same views or have a separate set of views. What do you suggest?
At controller level, we can identify archived claim and select which view to render.
At model level, though it'd be great to be able to use the same model used for Manage Claim - but it might not get us the "text" of some lookup fields. For example, Claim.BrandId is rendered as a dropdown in Manage claim (requires only BrandId) but for readonly view we need 'BrandText'.
Any existing ref or architecture level example would be great.
Here's my prev SO post but its more about db level changes: Design a process to archive data (SQL Server 2005)
Thank you.
-20848524 0This turned out to be a mess: Nose pretty much exclusively uses the TestLoader.load_tests_from_names
function (it's the only function tested in unit_tests/test_loader
) so since I wanted to actually load things from an arbitrary python object I seemed to need to write my own figure out what kind of load function to use.
Then, in addition, to correctly get things to work like the nosetests
script I needed to import a large number of things. I'm not at all certain that this is the best way to do things, not even kind of. But this is a stripped down example (no error checking, less verbosity) that is working for me:
import sys import types import unittest from nose.config import Config, all_config_files from nose.core import run from nose.loader import TestLoader from nose.suite import ContextSuite from nose.plugins.manager import PluginManager from myapp import find_test_objects def load_tests(config, obj): """Load tests from an object Requires an already configured nose.config.Config object. Returns a nose.suite.ContextSuite so that nose can actually give formatted output. """ loader = TestLoader() kinds = [ (unittest.TestCase, loader.loadTestsFromTestCase), (types.ModuleType, loader.loadTestsFromModule), (object, loader.loadTestsFromTestClass), ] tests = None for kind, load in kinds.items(): if isinstance(obj, kind) or issubclass(obj, kind): log.debug("found tests for %s as %s", obj, kind) tests = load(obj) break suite = ContextSuite(tests=tests, context=obj, config=config) def main(): "Actually configure the nose config object and run the tests" config = Config(files=all_config_files(), plugins=PluginManager()) config.configure(argv=sys.argv) tests = [] for group in find_test_objects(): tests.append(load_tests(config, group)) run(suite=tests)
-13340679 0 Time Range Selection in C# How can I know current time(not date) is between JobStart & Job End Time
var JobStartTime = new DateTime(2012,1,1,9,0,0,DateTimeKind.Local); //09:00AM var JobEndTime = new DateTime(2012,1,1,18,0,0,DateTimeKind.Local); //06:00PM var CurrentTime = DateTime.Now;
-6928904 0 The backslash \
is an escape character in Python. So your actual filepath is going to be D:\work\Kindle\srcs<tab>est1.html
. Use os.sep, escape the backslashes with \\
or use a raw string by having r'some text'
.
I have a postgresql database with some table and a stored procedure which write on this table. Everything goes fine, when I call this stored procedure from psql
: I see my records inserted in my table. Although, when I call this stored procedure through JDBC, I get the log of stored procedure execution, the sequence is incremented, however my table is not updated.
Here are the SQL I executed from a fresh postgresql installation (9.5.1):
Table creation:
CREATE SEQUENCE atable_id_seq; CREATE TABLE IF NOT EXISTS "atable" ( "id" int NOT NULL DEFAULT NEXTVAL('atable_id_seq'), "name" varchar(250) DEFAULT NULL, PRIMARY KEY ("id") );
The creation of stored procedure:
CREATE OR REPLACE FUNCTION awrite(IN name character varying, OUT result character varying) AS $$ BEGIN INSERT INTO atable(name) VALUES (name) RETURNING atable.id INTO awrite.result; RAISE INFO 'Create awrite: %', name; END $$ LANGUAGE plpgsql;
Calling awrite stored procedure from psql
actually triggers the log in postgres and updates the table.
Then I wrote a java program to call the same stored procedure:
HikariConfig hikariConfig = new HikariConfig(); hikariConfig.setDriverClassName("org.postgresql.Driver"); hikariConfig.setJdbcUrl("jdbc:postgresql://127.0.0.1:5432/toto?charSet=UNICODE"); hikariConfig.setUsername("toto"); hikariConfig.setAutoCommit(false); hikariConfig.setMinimumIdle(0); hikariConfig.setMaximumPoolSize(2); JdbcTemplate jdbcTemplate = new JdbcTemplate(new HikariDataSource(hikariConfig)); SimpleJdbcCall call = new SimpleJdbcCall(jdbcTemplate).withProcedureName("awrite"); HashMap<String, Object> params = new HashMap<String, Object>(); params.put("name", "Foo"); call.addDeclaredParameter(new SqlOutParameter("result", Types.VARCHAR)); Map<String, Object> result = call.execute(params); jdbcTemplate.execute("COMMIT;"); System.out.println("Result: "); for (String s : result.keySet()) { System.out.println(s + ": " + result.get(s)); }
I get an ID and execution went well. However my table does not contain the record.
I don't get it, maybe someone could help me?
-14118750 0If you'd use only id's the selection would be faster, but you would also have to do more selections than if you would use classes. Provided that the css is clean. Problem with basing style on id's in general is that you forgo all reuse of that style.
The best way to go is to link style to classes. That gives you adequate speed and keeps the css file smaller. Smaller files are much more important for performance in most sites than faster execution on the client. Typical clients will render a complex page in microseconds, once they have all the resources that is.
The css you point out is using a sprite, which could very well be generated with compass or something similar. It's important to see the original code too before making harsh judgements about the quality.
-31601668 0 What's the purpose of QString?I'm a newcomer to C++ and Qt. I've been messing around with Qt Creator for a few days, and what really struck me was how the GUI components only accepted a const QString&
rather than a string
or an std::wstring
. To stay consistent with this, I've been trying to accept and return QString
from most of my function calls, however I find myself converting to and from std::string
a lot to use most of the standard library facilities.
My question here is, what's the purpose of QString
if std::string
is part of the standard library? I guess this would be beneficial to someone who was already using Qt and didn't want another dependency on #include <string>
, but to be honest you'll need std::string
if you want to do anything useful with your application. (This especially goes for QChar
, since char
is a builtin.)
Can someone explain to me why this is not reinventing the wheel and how this helps being cross-platform?
-17496867 0Many ways to persist these days...
localStorage()
If this intro could be annoying for repeat users and the site has a login, I'd persist it server side. You don't want the user being hit with it when they use a different browser or computer to access your site.
If not, use localStorage()
.
Try this:
virtual public IEnumerable<string> GetSelectedIds(){ if (_kids == null){ yield return null; yield break; } foreach (var current in _kids.Nodes) yield return current; }
-40011046 0 Whitespace is important; you need to separate the ==
operator from its arguments, and you need to separate the brackets from the condition.
if [[ "$1" == "sell" ]]
-10244637 0 If you want to keep record of all queries that are executed, you can enable either the General Query Log or the Slow Query Log and set the threshold to 0 seconds (any query that takes more than 0 seconds will be logged).
Another option is the Binary log. However, binary log does not keep record of queries like SELECT
or SHOW
that do not modify data.
Note that these logs get pretty big pretty fast in a server with traffic. And that both might contain passwords so they have to be protected from unauthorized eyes.
-12968132 0 OSMF Player issue in IOSIve designed a sample osmf player app. Its is working fine in laptop,desktop and android mobiles but in Iphone(IOS OS) the player is embedded, but its not visible. There is no audio as well. Any help on this?
Thanks
-30410853 0b
is not definied in your while (as a
). In fact a
and b
are only define in the F(n)
function and they are local variables.
You should read some documentation about Programming and python first. But the following code should works:
(I suppose that you want while a/b <= 536
as this is not clear in your question)
def F(n): a, b = 0, 1 for i in range(0, n): a, b = b, a+b return a, b for c in range(0, 70): a,b = F(c) print(a) while a/b <= 536: print('Ratio:{}/{}'.format(b,a)) a, b = F(a)
An other solution is to totaly rewrite your code:
def F(a, b): c = a + b return c,a a, b = 0, 1 for c in range (0,70): a, b = F(a,b) print (a) while a/b <=536: print(a/b) a,b = F(a, b)
-18648682 0 ctype_digit( (string) $score); preg_match('#^\d+$#', $score);
In b4 @EmilioGort
boolean false int 0
-17387338 0 This has nothing to do with Core Data.
You must ensure the number of rows in the table and the number of rows in the data source is always the same.
If you need to delete a row, you need to delete the row from the data source, delete it from the table, BUT -> you need to do it between those two lines of code:
[_tableView beginUpdates]; // here delete from data source, and from the table. [_tableView endUpdates];
-25913605 1 Generator comprehension which adds different numbers of the same item Given:
foo = (a,b,c,d,e,f) multi = (b,d)
What generator comprehension gives the following tuple:
((a, None), (b, True), (b, False), (c, None), (d, True), (d, False), (e, None), (f, None))
where items in multi
appear twice with True
and False
, while other appear as None
.
There might be a way to do this with less duplication, but the following should work, anyway. First, find out which columns we need to shift, and then replace those columns by the shifted versions.
to_shift = pd.isnull(df2.iloc[-1]) df2.loc[:,to_shift] = df2.loc[:,to_shift].shift(1)
Get the last row:
>>> df2.iloc[-1] one 5 two NaN three NaN Name: i, dtype: float64
See where there's missing data:
>>> pd.isnull(df2.iloc[-1]) one False two True three True Name: i, dtype: bool >>> to_shift = pd.isnull(df2.iloc[-1])
Select that portion of the frame:
>>> df2.loc[:, to_shift] two three a -0.447225 0.240786 b NaN NaN c 1.736224 0.191835 d NaN NaN e -0.310505 2.121659 f 2.542979 -0.772117 g NaN NaN h -0.350395 0.825386 i NaN NaN
Shift it:
>>> df2.loc[:, to_shift].shift(1) two three a NaN NaN b -0.447225 0.240786 c NaN NaN d 1.736224 0.191835 e NaN NaN f -0.310505 2.121659 g 2.542979 -0.772117 h NaN NaN i -0.350395 0.825386
And fill the frame with the shifted data:
>>> df2.loc[:, to_shift] = df2.loc[:, to_shift].shift(1) >>> df2 one two three a -0.691010 NaN NaN b NaN -0.447225 0.240786 c 0.570639 NaN NaN d NaN 1.736224 0.191835 e 2.509598 NaN NaN f -2.053269 -0.310505 2.121659 g NaN 2.542979 -0.772117 h 1.812492 NaN NaN i 5.000000 -0.350395 0.825386
-4161628 0 If the first letter is always lowercase:
/^[a-z]-[0-9]+\.html$/
If it can be lowercase or uppercase:
/^[a-zA-Z]-[0-9]+\.html$/
-30497665 0 How to sync a Git Repository Branches with FTP? Is there any way possible to sync git master and develop branch with different ftp servers so that i can see the develop branch changes on my stage server and when I merge the code with master branch so changes will done on live server ??
I just have begin working with git and have basic knowledge so really looking forward to your assistance.
-1926537 0Here are some guide-lines you may consider:
Don't put direct link of files such as:
<a href="mydoc.pdf">Download</a>
Instead, try to generate your pdf dynamically or put a another encrypted medium for downloading eg:
<a href="download.php?file_id=1111111">Download</a>
2: Don't allow directory browsing, use htaccess file with following commands:
Deny from ALL
3: Not sure, but you may possibly allow file opening this way too:
$filename="/path/to/file.jpg"; //<-- specify the image file if(file_exists($filename)){ header('Content-Length: '.filesize($filename])); //<-- sends filesize header header('Content-Type: image/jpg'); //<-- send mime-type header header('Content-Disposition: inline; filename="'.$filename.'";'); //<-- sends filename header readfile($filename); //<--reads and outputs the file onto the output buffer exit; //and exit }
Note: above is just an example of image not pdf but you can modify it for your needs.
-28726660 0$('#sort_by').on('change', function(){ $.ajax({ type: "GET", url: "/items", data: { sort: $('option:selected', this).val() }, dataType : "script" }).done(function(data) { console.log(data); }); });
-6053075 0 It's really a matter of how much risk are you willing to take.
XCode may take longer, but you know it'll get accepted and new iOS versions won't completely hose it up.
Corona will write less code getting to 90%. That last 10% may be a real pain though. If Apple comes out with iOS XXX and everything breaks. You're waiting on Corona to update their SDK until you can update your app. Or if Apple releases a new feature, you'll wait for the Corona update before you can take advantage of it.
Personally, I'm a native XCode guy. These frameworks do have their place though.
-16972145 0 Rendering with BackboneI am trying to learn backbone and I was following along the code school backbone.js course to build my own backbone app. So far I have this code but I am having problems with rendering anything.
var PostsApp = new (Backbone.View.extend({ Collections: {}, Models: {}, Views: {}, start: function(bootstrap){ var posts = new PostsApp.Collections.Posts(bootstrap.posts); var postsView = new PostsApp.Views.Posts({collection: posts}); this.$el.append(postsView.render().el); } }))({el : document.body}); PostsApp.Models.Post = Backbone.Model.extend({}); PostsApp.Collections.Posts = Backbone.Collection.extend({}); PostsApp.Views.Post = Backbone.View.extend({ template: _.template("<%= name %>"), render: function(){ this.$el.html(this.template(this.model.toJSON())); } }); PostsApp.Views.Posts = Backbone.View.extend({ render: function(){ this.collection.forEach(this.addOne, this); }, addOne: function(post){ var postView = new PostsApp.Views.Post({model:post}); this.$el.append(postView.render().el); } }); var bootstrap = { posts: [ {name:"gorkem"}, {name: "janish"} ] } $(function(){ PostsApp.start(bootstrap); });
I am just trying to create a very simple backbone app, CodeSchool is great but it not good at combining the pieces together and when I try to do that myself I am having problems.
So far the error I am getting is "Uncaught TypeError: Cannot read property 'el' of undefined" in the addOne function of the Posts View. Any help would be much appreciated.
edit: The answer below solved my initial problem, but I also set up an express server to send data to the front end with the code :
app.get('/tweet', function(req,res){ res.send([{ name: 'random_name' }, {name: 'diren_gezi'}] ); });
and then I am trying to fetch this data to my collection like this :
var PostsApp = new (Backbone.View.extend({ Collections: {}, Models: {}, Views: {}, start: function(bootstrap){ var posts = new PostsApp.Collections.Posts(bootstrap.posts); posts.url = '/tweet'; posts.fetch(); var postsView = new PostsApp.Views.Posts({collection: posts}); postsView.render(); this.$el.append(postsView.el); } }))({el : document.body});
But in the page the initial data (name: gorkem and name: janish) is displayed instead of the recently fetched data..
-23433690 0Change your SQL statement to include only fields you want to see:
Dim query As String = "SELECT City, Address, Country, Region FROM Customers"
-28627209 0 How can I put a icon inline with paper-input-decorator? This is what I would like to achieve.
Although when using this code.
<paper-input-decorator floatingLabel label="Name *"> <core-icon icon="account-circle"></core-icon> <input type="name"> </paper-input-decorator>
I end up with this,
I've noticed that in the code on their website (which can be seen here) they have just given the form soem padding on the left and then given the icon an absolute position. Is this the only way to do that set up?
Thank you.
-30758937 0TL;DR - In the code snippet shown above, there is no memory leak.
Do I need to use malloc instead of hardcoded size of array?
I think, you got confused by the possible underuse of char buffer[10000];
and char error_msg[10000];
. These arrays are not allocated dynamically. Even the arrays are not used to their fullest capacities, there is no memory leak here.
Also, as Mr. @Vlad metioned rightly about another much possible issue in your case, actual_error_msg
being a global, if the trimwhitespace()
function does not have a return value which is having a global scope, (i.e., stays valid after the a()
has finished execution), it may possibly lead to undefined behaviour.
To avoid that, make sure, trimwhitespace()
function is either returning (assuming return type is char *
)
static
array. (bad practice, but will work)To elaborate, from the Wikipedia article about "memory leak"
In computer science, a "memory leak" is a type of resource leak that occurs when a computer program incorrectly manages memory allocations in such a way that memory which is no longer needed is not released. ...
and
.. Typically, a memory leak occurs because dynamically allocated memory has become unreachable. ...
When memory is being allocated by your compiler, there is no scope of memory leak, as the memory (de)allocation is managed by the compiler.
OTOH, with dynamic memory allocation, allocation of memory is performed at runtime. Compiler has no information about the allocation, memory is allocated programatically, hence need to be freed programatically, also. Failing to do so leads to the "memory leak".
-25194045 0Your function introducir_datos()
is declared as follows:
void introducir_datos (struct agenda cliente[30]);
But in your nested switch
statement, you have this line:
introducir_datos(cliente);
where cliente
is declared as char cliente[30]
. So instead of providing introducir_datos()
with a struct agenda*
argument, you are giving it a char*
argument.
The function introducir_datos()
expects to be given an array of 30 struct agenda
items as its argument.
This means that the argument type is struct agenda*
, because you are sending a pointer to the first item in the array. (This is just how arrays work in C.)
You can't call this function with a char[]
array as the argument, because a char[]
array consists of char
variables. A char
doesn't have any nombre
, apellido
, direccion
, edad
or telefono
members.
So your code won't compile because the compiler can't figure out what you're trying to do.
Incidentally, although you declare the variable int x;
in introducir_datos()
, you don't initialize it anywhere, so you need to fix that too.
Assume you defined a object named Foo,
message Foo { ... }
If you want to send a list of Foo, you can make it a repeated field in another message,
message FooList { repeated Foo foos = 1; }
You can check the language guide ,
You specify that message fields are one of the following: required: a well-formed message must have exactly one of this field. optional: a well-formed message can have zero or one of this field (but not more than one). repeated: this field can be repeated any number of times (including zero) in a well-formed message. The order of the repeated values will be preserved.
-1358693 0 Do you have another thread that is iterating/modifying the key set of Selector? From the Selector's java doc, keys are NOT threadsafe.
Concurrency
Selectors are themselves safe for use by multiple concurrent threads; their key sets, however, are not. ...
You may get CME exception If you have a thread working on the key set while Selector.close() is being called. Looking at the stack trace, the exceptions are happening in Sun's common implementation codes, so it shouldn't be AIX specific implementation. My suggestion would be identifying the thread that is add/removing selector keys, and see if synchronized keyword needs to be applied, or you need to make a sync-copy before working on the keys. If the modifying thread is not your thread/codes, then it is AIX issue. However, I can't tell without seeing the codes that modifying the key set.
Good luck debugging. I hope it helps
-38250221 0Does it have to be django?
This traversal style layout looks more like a job for pyramid.
https://pypi.python.org/pypi/django-mptt seems a good starting point for your tree structure, but with the permission system you are on your own
-10045942 0 form submit button returns null if value contains non-latin wordsthis is my HTML:
<?php echo form_open(base_url().'admin'); ?> <div class="row username"> <span class="icon"></span> <input type="text" value="" name="username" placeholder="Όνομα" /> </div> <div class="row password"> <span class="icon"></span> <input type="password" value="" name="password" placeholder="Κωδικος Πρόσβασης" /> </div> <div class="row button"> <input type="submit" value="Σύνδεση" name="submit" /> </div> <?php echo form_close(); ?>
so the button has as value "Σύνδεση" and when i click the submit button it returns nothing(null string)...
if i replace it with a text like "Sign in" it will work...
why it wont allow me to use non-latin characters?
-6280836 0Instead of creating an object with {}, use [] since you are creating a simple array.
var myObj=[]; for(var index=0; index<10; index++){ myObj[index]='my'+index; }
-14314029 0 In Rails, what is the best way to return a RecordNotFound Error from a Model.find call in JSON? What should be the right response for a RecordNotFound Error when doing something like this:
def destroy @post = current_user.posts.find(params[:id]) @post.destroy head :no_content end
-9074279 0 You may disable the URL escape behavior using escapeAmp="false"
attribute. By default, this is enabled, so URL parameter &
will render &
. This will cause a problem on reading the parameter value with parameter name.
request.getParameter("amp;pageNumber_hidden")
escapeAmp
and set the value false as part of the <s:url>
tag (Recommended)<s:url id="loadReportsForAPageInitial" value="/loadReportsForAPage.action" escapeAmp="false">
-863040 0 The zxing library is primarily Java, but, includes a port of the QR Code detector and decoder to C++.
-38025882 0 How to compare arabic- and kana full-width digits?How can I compare in PHP the two strings
県19−1県225−3県96−1
and
県19-1県225-3県96-1
?
The first one contains kana full-width numbers, the comparison should treat them as equal to the arabic-numeral.
-38439225 0You do it like this by refering to var as a global in func():
var = 0 def func(): global var var = 1 def pr(): func() print(var) pr()
-40353192 0 As of version 1.5.1, I'm able to access all the sockets in a namespace with:
var socket_ids = Object.keys(io.of('/namespace').sockets); socket_ids.forEach(function(socket_id) { var socket = io.of('/namespace').sockets[socket_id]; if (socket.connected) { // Do something... } });
For some reason, they're using a plain object instead of an array to store the socket IDs.
-37903688 0 Disable marker in highchart on 6m, 1y zoom levelHow do I disable markers at a certain zoom level. Specifically I would not like to display markers when zooming at 6m, 1yr and All
plnkr here: http://plnkr.co/edit/gReLtSy0WhA49q0NinpD?p=preview
-6731120 0 Try this: http://jsfiddle.net/ptfKJ/
This example is using your original HTML code.
-34977826 0 Geolocation doesn't work with cordovaI'm currently working on a mobile application with Intel XDK (In background it's Cordova finally, that's why I put Cordova in title.)
With an Ajax request, I get some adresses and with these adresses I want to calculate the distance between them and the current position of user.
So, I get adresses, I convert them and I make the difference.
But actually, nothing is working !
function codeAddress(id, addresse) { geocoder.geocode( { 'address': addresse}, function(results, status) { if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) { setTimeout(function(){}, 100); } console.log(id); console.log(addresse); //document.addEventListener("intel.xdk.device.ready",function(){ if (navigator.geolocation) { if (status == google.maps.GeocoderStatus.OK) { navigator.geolocation.getCurrentPosition(function(position) { addressEvent = results[0].geometry.location; var pos = { lat: position.coords.latitude, lng: position.coords.longitude }; var position = new google.maps.LatLng(pos.lat, pos.lng) var resultat = google.maps.geometry.spherical.computeDistanceBetween(addressEvent, position); console.log(resultat); console.log(addressEvent); console.log(pos); console.log(position); var convert = Math.floor(resultat); var finalConvert = convert + " m"; var distance = document.createElement('span'); distance.innerHTML = finalConvert; distance.className = "geo"; document.getElementsByClassName('meta-info-geo')[id].appendChild(distance); }, function() { handleLocationError(true, infoWindow); }); } } //},false); }); }
In the console.log(id), console.log(addresse), I HAVE results !
Actually i'm getting 4 IDs and 4 adresses.
I checked on all the topics I could find on StackOverFlow, and I had normally to add the line in // with the addEventListener but it changes nothing.
Is there someone who knows how to change that ?
ps : Of course, cordova geoloc is in the build and permissions are granted !
EDIT : I'm targeting Android 4.0 min and iOS 5.1.1. I'm using SDK.
-4007391 0 Question regarding memory allocation of variables in a structure (In C)Possible Duplicate:
Why isn't sizeof for a struct equal to the sum of sizeof of each member?
#include <stdio.h> int main(){ struct word1{ char a; int b; char c; }; struct word2{ char a; char b; int c; }; printf("%d\t%d\n", sizeof(int), sizeof(char)); //Output : 4 1 printf("%d\t%d\n", sizeof(struct word1), sizeof(struct word2)); //Output: 12 8 return 0; }
The code is available at IDEONE.
Why is the size of struct 1 (word1) greater than the size of struct 2 (word2)?
Is this a compiler problem?
-5466896 0 Array not being assigned correctlyI'm trying to write a program that accepts user input for a file name. From there it stores the numbers in the file into an array, sorts them, then displays them. However, i'm getting large numbers similar to accessing an out-of-bounds array, but I can tell from the debugger i'm not.
#include <iostream> using namespace std; class TestScores { public: TestScores(); TestScores(int scores); ~TestScores(); void AddScore(int newScore); void DisplayArray(); void SortScores(); bool ArraySorted(); int AvgScore(); private: int *scoresArray; //Dynamically allocated array int numScores; //number of scores input by user int scoreCounter; const static int default_NumArrays=10; //Default number of arrays }; #include <iostream> #include "TestScores.h" TestScores::TestScores() { scoresArray=new int[default_NumArrays]; scoreCounter=0; numScores=default_NumArrays; } TestScores::TestScores(int scores) { scoresArray=new int[scores]; numScores=scores; scoreCounter=0; for(int i=0; i<scores;i++) scoresArray[i]=0; } TestScores::~TestScores() { delete[] scoresArray; } void TestScores::AddScore(int newScore) { if(scoreCounter<numScores){ scoresArray[scoreCounter]=newScore; scoreCounter++; } else cout<<"More scores input than number of scores designated"<<endl; } void TestScores::DisplayArray() { for(int i=0; i<numScores; i++) cout<<scoresArray[i]<<endl; cout<<endl<<"This is scoresArray"<<endl; } bool TestScores::ArraySorted() { for(int i=0; i<(scoreCounter-1);i++){ if(scoresArray[i]<=scoresArray[i+1]) continue; else return false; } return true; } void TestScores::SortScores() { int tempValue; while(ArraySorted()!=true){ for(int i=0; i<(scoreCounter-1); i++){ if(scoresArray[i]<=scoresArray[i+1]) continue; else{ tempValue=scoresArray[i+1]; scoresArray[i+1]=scoresArray[i]; scoresArray[i]=tempValue; } } } } int TestScores::AvgScore() { int sumScores=0; if(scoreCounter>0){ for(int i=0; i<scoreCounter; i++) sumScores+=scoresArray[i]; return (sumScores/scoreCounter); } else{ cout<<"There are no scores stored."<<endl; return 0; } } #include "TestScores.h" #include <iostream> #include <fstream> #include <string> using namespace std; //Function prototypes bool FileTest(ifstream& inData); void StoreScores(ifstream& inData, int& newNumScores, TestScores satScores); int main() { int newNumScores=0; string inputFile; //Contains name of the user file being used //Opening file stream ifstream inData; //User prompt for input file cout<<"Please enter the file name containing the student scores you wish to " <<"have stored, sorted, and displayed."<<endl; cin>>inputFile; //Opening file streams inData.open(inputFile.c_str()); while(FileTest(inData)==false){ cout<<"I'm sorry, the file you entered was not a valid file. " <<"Please enter another file name, or enter q to exit"<<endl; cin>>inputFile; if(inputFile=="q") return 0; //Opening file streams inData.open(inputFile.c_str()); } inData>>newNumScores; TestScores satScores(newNumScores); //Instantiating TestScores variable StoreScores(inData, newNumScores, satScores); //Storing scores into array satScores.DisplayArray(); satScores.SortScores(); satScores.DisplayArray(); cout<<endl<<"This is the array after sorting"<<endl<<endl; cout<<"This is the average score "<<satScores.AvgScore()<<endl; //Program pauses for user input to continue char exit_char; cout<<"\nPress any key and <enter> to exit\n"; cin>>exit_char; inData.close(); return 0; } bool FileTest(ifstream& inData) { if(!inData) { cout<<"Your file did not open.\n"; return false; } return true; } void StoreScores(ifstream& inData, int& newNumScores, TestScores satScores) { int userScore; while(inData>>userScore){ satScores.AddScore(userScore); } }
My test file is random.dat and contains the following:
15 67 76 78 56 45 234
Based on looking through the debugger, I can tell that scoreCounter is incrementing correctly and that newScore contains the next value, so why isn't it being stored in the array? Thanks for the help
-39776312 0var level=0; var levelarray=[]; function looptrough(obj){ for(key in obj){ if(typeof obj[key]=="object"){ level++; looptrough(obj[key]); level--; } levelarray[level]=levelarray[level] || {}; levelarray[level][key]=obj[key]; } } looptrough({a:true;b:{c:true}});
Levelarray should now contain:
0:{a:true;b:{c:true}} 1:{c:true}
I thought using jquery is quite unecessary in that case, thats why i used for in...
-26983931 0 Dynamic input form phpI am making a dynamic PHP form that interacts with a mySQL database for entering the scores of students on different assignments. So far I have successfully connected to the database and accessed the necessary data. The following code displays for each student first, their name, and then an empty text input box where the user enters the score said student earned on the assignment.
<?php if(isset($_POST["beginScoring"]) || isset($_POST['submitScores'])){ $result = $connection->query("SELECT id, firstname, lastname FROM student ORDER BY lastname"); if(!$result) { echo "Query Failure"; } else { $foo = array(); $c = 0; echo "<tr><td>Last Name</td><td>First Name</td><td>Points Earned</td></tr>"; while ($row = $result->fetch_assoc()) { echo "<tr><td>$row[lastname]</td><td>$row[firstname]</td>"; ?> <td><input type="text" size=8 name="" id="" value=""/></td></tr> <!-- I can maybe use an array to store scores . . . --> <?php } } ?>
The thing I am having issues with is how do I name the text input. Since there are going to be an undetermined amount of text boxes, I can't use a single static name for the input item, right? What would be a good way to name the text boxes so that I can easily access them using the POST array?
-24850279 0there are two :
in the classpath definition. try to remove on:
"classpath:*/com/springDemo/main/contextBean.xml"
-6545244 0 RichTextToolbar in GWT 2.3 I'm trying to create a RichTextArea (following the GWT Showcase : link )
When I do a code completion of RichTextToolbar, I'm not able to find it. Is this an external library?
And then I googled and found this : google code link. Is this the same library in the Google Showcase? Or is the RichTextToolbar is an old implementation that not being brought to version 2.3?
Update:I tested this and what I feel is although the implementation the same, the UI looks different though.
-4545449 0File: test.jsx
compiles to bundle.js
using Gulp and Browserify.
File: test.jsx
:
var $ = require('jquery'); $("div#addTagModal").modal("hide");
In browser when I load the page I get this error:
Uncaught TypeError: undefined is not a function
On this line:
$("div#addTagModal").modal("hide");
I have no clue what is wrong. :/
$.ajax
works fine so I assume that jQuery is loaded properly.
Bootstrap is included in html using a script tag and I have checked the ID of modal.
I have a button that once clicked opens that modal:
<button className="btn btn-success" data-toggle="modal" href="#addTagModal" type="button"> <i class="icon-plus"></i> </button>
Any ideas?
This is my gulp task:
gulp.task('browserify', function() { gulp.src('app/assets/js/main.js') .pipe(browserify({ debug : true, transform: ['reactify'] })) .on('error', gutil.log) .pipe(rename('public/js/bundle.js')) .pipe(gulp.dest('./')) });
And in main.js
I have this code:
var app = require('./test.jsx');
-34694547 0 Memory at runtime I have a problem which says I have to read an unknown number of text lines from a file in an array of pointers and allocate memory at runtime.
#include <stdio.h> #include <stdlib.h> int main() { FILE *fp = fopen("file.txt","r"); char *arrp[10]; int i=1; while(!feof(fp)) { arrp[i]=malloc(sizeof(char)*51); fgets(arrp[i],51,fp); i++; } return 0; }
I wrote this program but I don't know how to do it without initializing the array first (*arrp[10]).
-25350820 0Your first foreach()
is causing the issue, as it is looping through both subarrays before printing the second foreach loop. Try removing it, and just reference the first $v['kaupunki_id']
using $values[0]['kaupunki_id']
-
$numerointi =1; echo "<table class=\"zebra\">"; foreach($arrayTotals as $team=>$values){ echo "<tr class=\"" . $values[0]['kaupunki_id'] . "\"><td>".$numerointi ."."; echo "<td>" . $team; $sum1=0; $sum2=0; $numerointi ++; foreach($values as $v){ echo "<td class=\"pisteet\">" . $v['pisteet_1'] . "/" . $v['pisteet_2'] . "</td>"; $sum1 +=$v['pisteet_1']; $sum2 +=$v['pisteet_2']; } echo '<td class="summa">'.$sum1.'/'.$sum2."</td>"; echo "</tr>"; } echo '</table>';
-4837977 0 Show blog posts in sidebar (rails 3) I want create a blog posts list in the sidebar.
My BlogsController
def bloglist @blog = Blog.all render 'bloglist' end
And I call bloglist.html.erb in layout/application.html.erb:
<%= render "blogs/bloglist" %>
After, I got missing template error:
Missing partial blogs/bloglist with {:handlers=>[:erb, :rjs, :builder, :rhtml, :rxml], :formats=>[:html], :locale=>[:en, :en]} in view paths...
Whats wrong?
-18158051 0 Search Replace in MySQL: remove directory structure but keep filenameI am changing directory structures in a Drupal installation and need to remove all path data except the file name itself.
So the basic structure is:
+-------------+--------------+---------+-----------+-------------+----------+-------+----------------------------------------------------------------------------------+-----------------------+ | entity_type | bundle | deleted | entity_id | revision_id | language | delta | field_filename_value | field_filename_format | +-------------+--------------+---------+-----------+-------------+----------+-------+----------------------------------------------------------------------------------+-----------------------+
The filename is stored in field_filename_value
. Here's a sample record:
+-------------+--------------+---------+-----------+-------------+----------+-------+----------------------------------------------------------------------------------+-----------------------+ | entity_type | bundle | deleted | entity_id | revision_id | language | delta | field_filename_value | field_filename_format | +-------------+--------------+---------+-----------+-------------+----------+-------+----------------------------------------------------------------------------------+-----------------------+ | node | presentation | 0 | 11 | 11 | und | 0 | /really long path name/with lots of words/167 Clarence Ashley - Coo Coo Bird.mp3 | NULL | +-------------+--------------+---------+-----------+-------------+----------+-------+----------------------------------------------------------------------------------+-----------------------+
That ridiculous filename value needs to be changed from:
/really long path name/with lots of words/167 Clarence Ashley - Coo Coo Bird.mp3
To this:
167 Clarence Ashley - Coo Coo Bird.mp3
Setting aside the bad practice of using spaces in file/directory names, how would you correct this? Is it possible using MySQL features alone?
As an added challenge, some files may be more than 2 directories deep.
-39126917 0Because AJAX always make request & wait response from server, we must put HTML file to web server (Apache HTTP server or NGINX), AJAX will run.
-31139129 0I use process.on(uncaughtException)
, because all you're really trying to do is catch the output from the error and shut the server down gracefully (and then restart). I don't see any reason to do anything more complicated than that, because by nature of the exception, you don't want your application doing anything else in that state other than shutting down.
Domains are an alternative way of dealing with this, but it's not necessarily better than using the process handler, because you're effectively writing custom logic to handle things that you aren't anticipating. It does give you finer granularity in terms of what your error handler does for different error types, but ultimately you're still potentially running your application in an unknown state after handling it. I'd rather have my application log the exception, shut down, and then i'll fix the error so it never happens again, rather than risking my user's data on a domain solution which may or may not have handled the error correctly, depending on the nuance of the error it encountered.
-4027976 0Three observations.
The best speedups are not coming from optimizations but from good algorithms. So make sure you get that part right first. Often this means just using the right libraries for your specific domain.
Once you get your algorithms right it is time to Measure. Often there is an 80/20 rule at work. 20% of your code will take 80% of the execution time. But in order to locate that part you need a good profiler. Intel VTune can give you sampling profile from every function and nice reports that pinpoint the performance killers. Another free alternative is AMD CodeAnalyst if you have an AMD CPU.
The compiler autovectorization capability is not a silver bullet. Although it will try really hard (especially Intel C++) you will often need to help it by rewriting the algorithms in vector form. You can often get much better results by handcrafting small portions of the bottleneck code to use SIMD instructions. You can do that in C code (see VJo's link above) using intrinsics or use inline assembly.
Of course parts 2 and 3 form an iterative process. If you are really serious about this then there are some good books on the subject by Intel folks such as The Software Optimization Cookbook and the processor reference manuals.
-8190300 0a.toString() does not do what you think it does.
Use TextView a = (TextView)findViewById(R.id.authentication); (a.getText().equals(""))
You could also write an iterator for your matrix. This is not complete but gives you an idea:
#include <vector> #include <algorithm> template< class _T > class Matrix { public: std::vector< std::vector< _T > > m_matrix; void alloc( size_t rows, size_t cols ) { m_matrix.resize( rows ); std::for_each( m_matrix.begin(), m_matrix.end(), [cols](std::vector<_T> &t){t.resize(cols);}); } class iterator { public: iterator( std::vector< std::vector< _T > > & v ): m_vbegin( v.begin() ), m_vi( v.begin() ), m_i( m_vi->begin() ), m_vend( v.end() ) {} iterator& operator++() { if ( ++m_i == m_vi->end() ) { if ( ++m_vi != m_vend ) m_i = m_vi->begin(); } return (*this); } void gotobegin() { m_vi=m_vbegin; m_i=m_vi->begin(); } void gotoend() { m_vi=m_vend; } _T & operator*() { return *m_i; } bool operator==(const iterator & rhs ) { if ( m_vi==rhs.m_vi && (m_vi==m_vend || m_i==rhs.m_i) ) return true; return false; } bool operator!=(const iterator & rhs ) { return !( *this == rhs ); } private: typename std::vector< std::vector< _T > >::iterator m_vi; const typename std::vector< std::vector< _T > >::iterator m_vbegin; const typename std::vector< std::vector< _T > >::iterator m_vend; typename std::vector< _T >::iterator m_i; }; iterator begin(){ return iterator(m_matrix); } iterator end(){ iterator ret(m_matrix); ret.gotoend(); return ret;} }; int main( void ) { Matrix<double> matrix; matrix.alloc( 4000, 4000 ); std::for_each( matrix.begin(), matrix.end(), []( double &t){ t=1.0;} ); std::for_each( matrix.begin(), matrix.end(), []( double &t){ t+=1.0;} ); return 0; }
-24424704 0 You can't type cast int
to byte
implicitly. Call method as:
sum(1, (byte)2);
-10659869 0 Can.js has everything you need and weighs in at just 8 KB. It's taken the best bits from JavaScriptMVC and distilled it into one small, yet kickass framework with observers, widgets, binding, the works. It is compatible with major frameworks (jQuery, Dojo Toolkit, MooTools, etc.). Documentation is excellent and authors are responsive. It is definitely worth a look.
-27325380 0 Regex Match "words" That Contain Periods perlI am going through a TCPDUMP file (in .txt format) and trying to pull out any line that contains the use of the "word" V.I.D.C.A.M. It is embedded between a bunch of periods and includes periods which is really screwing me up, here is an example:
E..)..@.@.8Q...obr.f...$[......TP..P<........SMBs......................................NTLMSSP.........0.........`b.m..........L.L.<...V.I.D.C.A.M.....V.I.D.C.A.M.....V.I.D.C.A.M.....V.I.D.C.A.M.....V.I.D.C.A.M..............W.i.n.d.o.w.s. .5...1...W.i.n.d.o.w.s. .2.0.0.0. .L.A.N. .M.a.n.a.g.e.r..
How do you handle something like that?
-8410349 0Add the following before your call to the include
method:
renderRequest.setAttribute("sLang_Id", sLang_Id);
API available for reference at http://portals.apache.org/pluto/portlet-2.0-apidocs/index.html?javax/portlet/RenderRequest.html .
-11499879 0Count from 0 to 3n-1, and convert your number to an n-digit base-3 number (including leading zeros). Each digit in the result represents the value for one parameter.
-18047036 0Below regex can match any type of number, remember, I have assumed +
to be optional. However it does not handle number counting
^\+?(\d[\d-. ]+)?(\([\d-. ]+\))?[\d-. ]+\d$
Here are some valid numbers you can match:
+91293227214 +3 313 205 55100 99565433 011 (103) 132-5221 +1203.458.9102 +134-56287959 (211)123-4567 111-123-4567
-3301620 0 I use the following for sorting a 2d array on a number of columns
def k(a,b): def _k(item): return (item[a],item[b]) return _k
This could be extended to work on an arbitrary number of items. I tend to think finding a better access pattern to your sortable keys is better than writing a fancy comparator.
>>> data = [[0,1,2,3,4],[0,2,3,4,5],[1,0,2,3,4]] >>> sorted(data, key=k(0,1)) [[0, 1, 2, 3, 4], [0, 2, 3, 4, 5], [1, 0, 2, 3, 4]] >>> sorted(data, key=k(1,0)) [[1, 0, 2, 3, 4], [0, 1, 2, 3, 4], [0, 2, 3, 4, 5]] >>> sorted(a, key=k(2,0)) [[0, 1, 2, 3, 4], [1, 0, 2, 3, 4], [0, 2, 3, 4, 5]]
-31239623 0 Try like this:
var windowheight = $(window).height(); var dynamicContentHeight = $(window).height(); var headerHeight = $("#header").height(); var footerHeight = $("#footer").height(); var gridheight = windowheight - headerHeight - footerHeight - dynamicContentHeight; $("#gridheight").css("height", gridheight);
-29963338 0 If you are using KSOAP2 library (as you said in comments above) than you can do something like this:
SoapObject response = (SoapObject) envelope.getResponse(); for(int i=0; i<response.getPropertyCount(); i++){ YourObjectModel obj = new YourObjectModel(); SoapObject soapObj = (SoapObject) response.getProperty(i); obj.nome = soapObj.getPrimitivePropertyAsString("nome"); obj.cognome = soapObj.getPrimitivePropertyAsString("cognome"); //Add to list nursesList.add(obj); }
However if you show the code where are you getting those data maybe we can be more specific in our answers
-38761692 0 error 3021 when adding scalar propertyI have an error below after I add Scalar property on EDMX.
kindly help. thanks.
Error 4 Error 3021: Problem in Mapping Fragment starting at line 13750: Each of the following columns in table SystemUserDetails is mapped to multiple conceptual side properties: SystemUserDetails.COM_ID is mapped to
C:\Users\User\Desktop\New folder\CustCare with Frontliner System\RevTrackDAL\RevTrackModel2.0.edmx 13751 11 RevTrackDAL
-7463197 0 Is this the basic idea of what you're looking for:
$(document).ready(function(){ var toggler = $('div[id*="toggle-image"]'); toggler.attr("class", "toggle-image-expand"); //Hide (Collapse) the toggle containers on load $("div[class*='toggle-container']").hide(); $("h3[class*='trigger']").click(function(){ var toggler_inner = $(this).find(toggler); $(this).toggleClass("active").next().slideToggle("slow"); if (toggler_inner.attr("class") == "toggle-image-collapse") { toggler_inner.attr("class", "toggle-image-expand"); } else { toggler_inner.attr("class", "toggle-image-collapse"); } return false; }); });
-25455225 0 You could either use setInterval
:
window.setInterval(jTTrackPage, 10000); // call it every 10 000 ms = 10 s
or setTimeout
:
function trackPage() { jTTrackPage(); window.setTimeout(trackPage), 10000); // call the function again in 10 000 ms } trackPage();
The difference between both is that the first one calls it every 10s, and if one call takes more than 10s (unlikely here) the next one will be triggered just after, without waiting 10s. The second solution solves this problem.
You can clear an interval or a timeout using respectively clearInterval
and clearTimeout
:
var interval = window.setInterval(jTTrackPage, 10000); window.clearInterval(interval); // <-- stop it var timeout = window.setTimeout(trackPage, 10000); window.clearTimeout(timeout); // <-- stop it
-26811906 0 Swift is designed to take advantage of optional value's and optional unwrapping.
You could also declare the array as nil, as it will save you a very small (almost not noticable) amount of memory.
I would go with an optional array instead of an array that represents a nil value to keep Swift's Design Patterns happy :)
I also think
if let children = children { }
looks nicer than :
if(children != nil){ }
-571773 0 Answering the (original) question ("Does Perl have an equivalent to PHP's readline()
function ... ?"), the answer is "the angle bracket syntax":
open my $fh, '<', '/path/to/file.txt'; while (my $line = <file>) { print $line; }
Getting the content-length with this method isn't necessarily easy, though, so I'd recommend staying with Tie::File
.
NOTE
Using:
for my $line (<$filehandle>) { ... }
(as I originally wrote) copies the contents of the file to a list and iterates over that. Using
while (my $line = <$filehandle>) { ... }
does not. When dealing with small files the difference isn't significant, but when dealing with large files it definitely can be.
Answering the (updated) question ("Does Perl have an equivalent to PHP's readfile()
function ... ?"), the answer is slurping. There are a couple of syntaxes, but Perl6::Slurp
seems to be the current module of choice.
The implied question ("why doesn't the browser prompt for download before grabbing the entire file?") has absolutely nothing to do with how you're reading in the file, and everything to do with what the browser thinks is good form. I would guess that the browser sees the mime-type and decides it knows how to display plain text.
Looking more closely at the Content-Disposition problem, I remember having similar trouble with IE ignoring Content-Disposition. Unfortunately I can't remember the workaround. IE has a long history of problems here (old page, refers to IE 5.0, 5.5 and 6.0). For clarification, however, I would like to know:
What kind of link are you using to point to this big file (i.e., are you using a normal a href="perl_script.cgi?filename.txt
link or are you using Javascript of some kind)?
What system are you using to actually serve the file? For instance, does the webserver make its own connection to the other computer without a webserver, and then copy the file to the webserver and then send the file to the end user, or does the user make the connection directly to the computer without a webserver?
In the original question you wrote "this does not cause the browser to prompt for download before grabbing the entire file" and in a comment you wrote "I still don't get a download prompt for the file until the whole thing is downloaded." Does this mean that the file gets displayed in the browser (since it's just text), that after the browser has downloaded the entire file you get a "where do you want to save this file" prompt, or something else?
I have a feeling that there is a chance the HTTP headers are getting stripped out at some point or that a Cache-control header is getting added (which apparently can cause trouble).
-12504470 0found the solution. this seems to work great http://gridster.net
-14850836 0Inside the web.config file in the Views folder there is the host element under system.web.webPages.razor
This should be as follows for an MVC3 project:
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
While for MVC4 it is:
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
You also need to check the pages element is as follows for MVC3
<pages validateRequest="false" pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"> <controls> <add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" /> </controls> </pages>
and the sectionGroup element:
<sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"> <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" /> <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" /> </sectionGroup>
In the main web.config in the root directory of the project you need to make sure that the assemblies element is as follows:
<assemblies> <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> </assemblies>
There are more changes to make - best bet is to look at the web.config files for an MVC3 project and an MVC4 project and remove the stuff that shouldn't be there in yours.
-27501263 0The characters that represent decimal digits are laid out in ASCII space in numerical order.
'0'
is ASCII 0x30'1'
is ASCII 0x31'2'
is ASCII 0x32This means that you can simply subtract '0'
from your character to get the value you desire.
char a = ...; if (a >= '0' && a <= '9') { int digit = a - '0'; // do something with digit }
-20298283 0 MVVM approach, what's a good way? How to improve/speed up development? this post is meant to have a list of suggestions on MVVM approach... What tools do you use, what do you do to speed up development, how do you maintain your application, any special ways of finding defects in this design pattern......
here is what I do:
So first i create my model/db with EF.
Then I create Views (either user controls or windows) with their respective viewmodel. I usually place the viewmodel in the same location as my view. But while starting the name of my view with "UC-name", I call my viewmodel just "name-model".
In my viewmodel I implement InotifyPropertyChanged
in my xaml view I have a resource of my viewmodel, and bind my grids/controls via the itemsource to the staticresource.
I try to do a lot of front end logic with triggers and styles and also place some code in the xaml.cs file if it regards logic for behaviour of my controls.
I can reach my viewmodel from my view (xaml + xaml.cs).
for communiation between viewmodels I use MVVM lights.
that's pretty much it.
Things I'm thinking about
I'm thinking of using T4 templates for generating viewmodel/view. What do you guys think of this. is this worth it?
when using MVVM light Messenger, we get a subscription based communication, and sometimes I find it hard to track what has changed in my DataContext. Any suggestions on this?
any other improvements or suggestions are more than welcome !
if [ $ran -eq $num ] then echo "The size of file $fname in lines $sh is: $num" done
The if
there is missing a fi
.
You could use a make file to generate the .i files first, run your processing on them, then compile them.
-8302923 0 new created UIImageViews do not show up when added as subviewupon a tap, I want to let a few UIImageView objects appear on an underlaying UIView. So I created the following action:
- (IBAction)startStars: (id) sender { UIView* that = (UIView*) sender; // an UIButton, invisible, but reacting to Touch Down events int tag = that.tag; UIView* page = [self getViewByTag:mPages index:tag]; // getting a page currently being viewed if ( page != nil ) { int i; UIImage* image = [UIImage imageNamed:@"some.png"]; for ( i = 0 ; i < 10 ; ++i ) { // create a new UIImageView at the position of the tapped UIView UIImageView* zap = [[UIImageView alloc] initWithFrame:that.frame]; // assigning the UIImage zap.image = image; // make a modification to the position so we can see all instances CGPoint start = that.layer.frame.origin; start.x += i*20; zap.layer.position = start; [page addSubview:zap]; // add to the UIView [zap setNeedsDisplay]; // please please redraw [zap release]; // release, since page will retain zap } [image release]; } }
Unfortunately, nothing shows up. The code gets called, the objects created, the image is loaded, even the properties are as expected. Page itself is a real basic UIView, created with interface builder to contain other views and controls.
Still, nothing of this can be seen....
Has anyone an idea what I am doing wrong? Do I need to set the alpha property (or others)?
Thanks
Zuppa
-13334295 0ed
is the standard text editor.
#!/bin/bash { ed -s file.json <<EOF /\"fruit\": \[ a { "fruit":"apple" , "amount":"10" } #object to add . wq EOF } &> /dev/null
Don't know why you want to use bash for that, though, there are much better tools around!
Done.
-36526756 0You can use:
private float x; public float X { get { return x; } }
Now you only set x from within your class.
-10701272 0 iTextSharp cyrillic lettersI used http://www.codeproject.com/Articles/260470/PDF-reporting-using-ASP-NET-MVC3 to generate pdf files from my razor views and it works great but i can't display cyrillic letters like č,ć . I tried everything and i can't get it working.
I must somehow tell the HtmlWorker to use different font:
using (var htmlViewReader = new StringReader(htmlText)) { using (var htmlWorker = new HTMLWorker(pdfDocument)) { htmlWorker.Parse(htmlViewReader); } }
Can you help?
EDIT:
I was missing one line
styleSheet.LoadTagStyle(HtmlTags.BODY, HtmlTags.ENCODING, BaseFont.IDENTITY_H);
The rest was the same as the answer.
-6415740 0 Rails 3 update routing errorI am having trouble with my routing in a Rails application.
My routing file has:
resources :translations
Which should create several routes, including update.
Doing a rake routes shows the update route is there:
PUT /translations/:id(.:format) {:action=>"update", :controller=>"translations"}
However, when I use the following code to link to the update:
<% form_tag( {:controller => "translations", :action => "update"}, {:multipart => true}) do %> <p><%= label_tag "upload", translate("UI_TEXT_FORM_SELECT_AUDIO_FILE") %>: <%= file_field_tag "upload" %></p> <%= submit_tag translate("UI_TEXT_FORM_SAVE") %> <% end %>
I get this result:
Routing Error No route matches "/translations/10"
Any help would be appreciated.
-22126212 0 Wrap text in syllables TextView located in TableRowText that does not fit into the width cropped. Can I get the text to wrap to the next line in syllables?
Another TextView wraps lines. I suspect that there is no transfer because the TextView is inside TableRow
Style.xml
<style name="ContactTextView"> <item name="android:layout_width">match_parent</item> <item name="android:layout_height">wrap_content</item> <item name="android:textSize">14sp</item> <item name="android:textColor">@android:color/white</item> <item name="android:layout_margin">5dp</item> <item name="android:background">@drawable/textview_border</item> <item name="android:singleLine">false</item> </style>
Contact_view.xml
<?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:background="@color/back_black" > <TableLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:stretchColumns="1" > <TableRow android:id="@+id/nameTableRow" android:layout_width="match_parent" android:layout_height="wrap_content" > <TextView android:id="@+id/nameLabelTextView" style="@style/ContactLabelTextView" android:text="@string/label_name" > </TextView> <TextView android:id="@+id/nameTV" style="@style/ContactTextView" > </TextView> </TableRow> <TableRow android:id="@+id/phoneTableRow" android:layout_width="match_parent" android:layout_height="wrap_content" > <TextView android:id="@+id/phoneLabelTextView" style="@style/ContactLabelTextView" android:text="@string/label_phone" > </TextView> <TextView android:id="@+id/phoneTV" style="@style/ContactTextView" > </TextView> </TableRow> <TableRow android:id="@+id/birthdayTableRow" android:layout_width="match_parent" android:layout_height="wrap_content" > <TextView android:id="@+id/birthdayLabTV" style="@style/ContactLabelTextView" android:text="@string/date_birthday" > </TextView> <TextView android:id="@+id/birthdayTV" style="@style/ContactTextView" > </TextView> </TableRow> <TableRow android:id="@+id/passportTableRow" android:layout_width="match_parent" android:layout_height="wrap_content" > <TextView android:id="@+id/passportLabTV" style="@style/ContactLabelTextView" android:text="@string/passport_min" > </TextView> <TextView android:id="@+id/passportTV" style="@style/ContactTextView" > </TextView> </TableRow> <TableRow android:id="@+id/adressTableRow" android:layout_width="match_parent" android:layout_height="wrap_content" > <TextView android:id="@+id/adressLabTV" style="@style/ContactLabelTextView" android:text="@string/label_city" > </TextView> <TextView android:id="@+id/adressTV" style="@style/ContactTextView" > </TextView> </TableRow> <TableRow android:id="@+id/siteTableRow" android:layout_width="match_parent" android:layout_height="wrap_content" > <TextView android:id="@+id/siteLabTV" style="@style/ContactLabelTextView" android:text="@string/site_min" > </TextView> <TextView android:id="@+id/siteTV" style="@style/ContactTextView" > </TextView> </TableRow> </TableLayout> </ScrollView>
-4803271 0 Try changing viewController = [[PhotoViewController alloc] init];
to
viewController = [[PhotoViewController alloc] initWithNibName:@"PhotoViewController" bundle:nil];
(of course change the text string to whatever you called your xib file).
-11756766 0All associated data with an extension is removed when the extension is uninstalled. You can verify this by visiting your Chrome profile directory, and descend in Local Storage
. You'll see a SQLLite database (eg. chrome-extension_lndfmdleiloedhcbmjofibnflfbjhpha_0.localstorage
).
After removing the extension, this database disappears.
-17919674 0If you need to receive sms during application opened (not as service), you can put Receiver in Main activity as mentioned in hewwcn answer.
For example:
public class MainActivity extends Activity { /* * Variables for BroadcastReceiver */ boolean isRegistered = false; // check if BroadcastReceiver registered private IntentFilter filterSmsReceived = new IntentFilter( "android.provider.Telephony.SMS_RECEIVED"); /** * Create BroadcastReceiver */ private BroadcastReceiver smsReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals( "android.provider.Telephony.SMS_RECEIVED")) { /* get the SMS message passed in */ Bundle bundle = intent.getExtras(); SmsMessage[] msgs = null; String msgFrom = null; String msgBody = null; if (bundle != null) { /* retrieve the SMS message received */ try { Object[] pdus = (Object[]) bundle.get("pdus"); msgs = new SmsMessage[pdus.length]; for (int i = 0; i < msgs.length; i++) { msgs[i] = SmsMessage .createFromPdu((byte[]) pdus[i]); msgFrom = msgs[i].getOriginatingAddress(); msgBody = msgs[i].getMessageBody(); } /* * TODO Show dialog */ } catch (Exception e) { // Log.d("Exception caught",e.getMessage()); } } } } }; /** * Button - register BroadcastReceiver when clicked (or put it to onCreate) */ public void onButtonClicked(View v) { this.registerReceiver(smsReceiver, filterSmsReceived); isRegistered = true; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override protected void onPause() { /* * Unregister BroadcastReceiver */ if (isRegistered) { this.unregisterReceiver(smsReceiver); isRegistered = false; } super.onPause(); } @Override protected void onDestroy() { /* * Unregister BroadcastReceiver */ if (isRegistered) { this.unregisterReceiver(smsReceiver); isRegistered = false; } super.onDestroy(); } }
-6928335 0 Apache Mina , create my own IoSession: How to? I'm playing for a few days with apache mina and I want to ask you how can I create by extending (or implementing) IoSession to create something like MyIoSession.
The reason why I want to do this is because in the Handler class I want something like this:
public class MyHandler extends IoHandlerAdapter{ public void messageReceived( MyIoSession session, Object message ) throws Exception { // here I have MyIoSession instead of IoSession which will have more info something // like an unique ID } }
This way MyIoSession will have some unique ID and this way I'll identify which client is sending messages to server.
Also if there are other better ways to achieve this feel free to tell me.
Thanks
-22963338 0- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return exampleArray.count; } -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return 50; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [exampleTableView dequeueReusableCellWithIdentifier:@"cell"]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CellWithSwitch"]; cell.selectionStyle = UITableViewCellSelectionStyleNone; cell.textLabel.font = [UIFont systemFontOfSize:14]; } cell.textLabel.text = [exampleArray objectAtIndex:indexPath.row]; } -(IBAction)exampleButtonAction:(id)sender { exampleArray=[[NSMutableArray alloc]initWithObjects:@"example1",@"example2",@"example3",@"example4",nil]; [exampleTableView reloadData]; }
-21788574 0 If I was you, I would keep the last fetched id
from the dataset.
Therefore you need to change your Controllers.OdbcController.GetRecords()
to accept an id
and return the latest one.
In the GetRecords
check for that id
using a where
clause.
EDIT:
According to your update: are you sure the ID
gets passed to the config correctly?
You use two different calls to save and retrieve:
ConfigurationManager.AppSettings["LastId"]
vs.
Common.UpdateConfigFile.UpdateAppSetting("LastId", _lastId)
Why not use this?
ConfigurationManager.AppSettings["LastId"] = _lastId;
-14842016 0 To achieve a pause of x milliseconds between each restart:
myAnimation.setAnimationListener(new AnimationListener(){ @Override public void onAnimationStart(Animation arg0) { } @Override public void onAnimationEnd(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { myAnimation.setStartOffset(x); } });
-40438224 0 In general, thrust operations dispatched on the "host" are not run in parallel. They use a single host thread.
If you want to run thrust operations in parallel on the CPU (using multiple CPU threads) then the recommended practice would be to use the thrust OpenMP backend.
A fully worked example is here.
Another worked example is here.
-33198428 1 jwt: 'module' object has no attribute 'encode'I am getting Module not found error when using jwt. Here is how I declared it:
def create_jwt_token(): payload = { "iat": int(time.time()) } shared_key = REST_API_TOKEN payload['email'] = EMAIL payload['password'] = PASSWORD jwt_string = jwt.encode(payload, shared_key) encoded_jwt = urllib.quote_plus(jwt_string) # url-encode the jwt string return encoded_jwt
The error message says encode is not found in jwt. I did a tab on jwt and found that the encode is a method inside jwt.JWT. I tried changing it to
jwt_string = jwt.JWT.encode(payload, shared_key)
and it gives an error "unbound method encode() must be called with JWT instance as first argument (got dict instance instead)"
What am I doing it wrong? Here is the version info of my python environment:
2.7.10 |Anaconda 2.3.0 (64-bit)| (default, May 28 2015, 16:44:52) [MSC v.1500 64 bit (AMD64)]
-2907911 0Also, http://snapframework.com/docs/tutorials/heist from Haskell's snap seems to fit.
-16149906 0 proximity profile api for iosI want to generate alert sound, if iPhone goes beyond the specific distance from my BLE enabled Tag. For that I need proximity sensor profile to implement. I searched for Proximity sensor profile API for ios, but didn't get any successful result.
-8804373 0For the XSLT part I recommend using the "Fill-in the blasnks" technique -- see a simple example here: http://stackoverflow.com/a/8674694/36305.
The form skeleton will look like this:
<form name="formRoot" xmlns:gen="my:gen"> <gen:name/> </form>
The XSLT code will contain a template matching gen:name
that produces:
<p>Name</p><input name="name" value="Name"/>
The URL to the form-skeleton is passed as an external parameter to the XSLT transformation.
The source XML document (URL or itself) is passed as another external parameter.
Thus the XSLT transformation can process any source XML document and insert the results of processing into any form-skeleton document.
-20760914 0 Program not asking expected number of values#include <stdio.h> main() { int n,i; FILE *fptr; fptr=fopen("f3.txt","w"); if(fptr==NULL) { printf("Error!"); exit(1); } printf("Enter n: "); for(i=0;i<=2;i++) { scanf("%d \n",&n); fprintf(fptr,"%d ",n); } fclose(fptr); return 0; }
EDIT: *In the above program, I am entering 3 values, but why this is asking for 4 values? Although its writing only three times but its asking for the values 4 times. Can u tell d reason? And what to do to make it to take exact number of values which I am typing.?* thanks in advance..
So this is known that it was due to space next to %d in loop. Can someone explain Carriage Return in a little detail, I searched but could not understand exactly what that is.
-4543459 0I had the same problem in a different way.After I updated the row in the 3. page, the table used to go back to 1. page automatically.. The forth parameter of the fnUpdate takes true/false to update the table and default value is true. I changed it as false then it has started working. Not exactly the same situation you experienced but might help to solve your problem. Have a look at the parameters of the functions that you used in your code.Regards. Ozlem.
$('#rulesTable').dataTable().fnUpdate(suburb_name, rowNo, 3, false );
-12756608 0 see XMPP: http://www.amazon.com/Professional-Programming-JavaScript-jQuery-Programmer/dp/0470540710
-31494131 0Here's one way using regular expressions. First, make sure the price column is a character vector and not a factor
DB1$price<-as.character(DB1$price)
Then define your desired replacements
replacewith<-c("Jan"="1.", "Feb"="2.", "Mrz"="3.", "Apr"="4.", "Mai"="5.", "Jun"="6.", "Jul"="7.", "Aug"="8.", "Sep"="9.", "Okt"="10.", "Nov"="11.", "Dez"="12.")
Now turn those into a regular erxpression and match against your price column
re <- paste0("^(",paste(names(replacewith),collapse="|"), ") ") m <- regexpr(re,DB1$price, perl=T) mm <- regmatches(DB1$price, m)
Now we do a look up for the replacement
regmatches(DB1$price, m) <- replacewith[substr(mm, 1, nchar(mm)-1)] DB1$price # [1] "12.90" "8.90" "3.40" "79.95" "12.45" "7.99" "6.90" "129.90" "7.90" "49.95"
-31822889 0 The css-width/-height of the canvas have to get set to something else than they would be with 100%. (e.g. 101%)
Only this (after trying 9 other methods of a redraw/repaint) induces Safari to render it correctly.
Hi i have a c++ class with some private members as follows
template <typename V, typename E> class Vertex { public: Vertex(); ~Vertex(); typedef std::pair<int, E> edgVertPair; typedef std::vector<edgeVertPair> vectEdges; void setVertexID(int data); int getVertexID(); void setEdgeVertPair(int vertID, E edge); edgVertPair getEdgeVertPair(); void setEdgeList(edgeVertPair edgeVert); vectEdges getEdgeList(); private: int vertexID; edgVertPair evp; vectEdges edgeList; };
Now i want to create a pair i.e. something like
evp.first="someint"; evp.second="somestring";
and then push this evp into the edgeList i.e. edgeList.push_back(evp); Now the problem is in the setter function i did something like this:
template<typename V, typename E> void Vertex<V, E>::setEdgeVertPair(int vertID, E edge){ ...populate evp;... }
now i don't know how to populate the evp pair with vertID, edge.
-4366397 0what you can do is every step, save out the form state to some serialised object in db ForeignKeyed to the user.
then when hooking up the formwizard, wrap the formwizard view in a custom view which checks if the user has a saved form and if so deserialises and redirects to the appropriate step.
Edit: seems formwizard saves state in POST. only need to save postdata.
models.py:
class SavedForm(Model): user = ForeignKey(User) postdata = TextField()
views.py:
import pickle class MyWizard(FormWizard): def done(self, request, form_list): SavedForm.objects.get(user=request.user).delete() # clear state!! return render_to_response('done.html',) formwizard = MyWizard([Form1, Form2]) <- class name, not instance name def formwizard_proxy(request, step): if not request.POST: #if first visit, get stored data try: prev_data = SavedForm.objects.get(user=request.user) request.POST = pickle.loads(prev_data.postdata) except: pass else: # otherwise save statet: try: data = SavedForm.objects.get(user=request.user) except: data = SavedForm(user=request.user) data.postdata=pickle.dumps(request.POST) data.save() return formwizard(request)
edit: changed formwizard constructor
-9250139 0You can do as follows :
add javascript into local.xml
<layout version="0.1.0"> <default> <reference name="head"> <action method="addJs"><script>jquery/jquery-1.7.1.min.js</script></action> <action method="addJs"><script>jquery/carouFredSel.js</script></action> </reference> </default> </layout>
then make a custom home page template ( take reference from 1column.phtml ), select this template for homepage from CMS.
Put the following content in home page "XML Layout Update" section from Design tab. Here is mine setting which I remove whole prototype scripts from homepage is because didn't want.
<reference name="head"> <action method="removeItem"><type>js</type><script>prototype/prototype.js</script></action> <action method="removeItem"><type>js</type><script>prototype/validation.js</script></action> <action method="removeItem"><type>js</type><name>scriptaculous/builder.js</name><params/></action> <action method="removeItem"><type>js</type><name>scriptaculous/effects.js</name><params/></action> <action method="removeItem"><type>js</type><name>scriptaculous/dragdrop.js</name><params/></action> <action method="removeItem"><type>js</type><name>scriptaculous/controls.js</name><params/></action> <action method="removeItem"><type>js</type><name>scriptaculous/slider.js</name><params/></action> <action method="removeItem"><type>js</type><name>lib/ccard.js</name><params/></action> <action method="removeItem"><type>js</type><name>varien/menu.js</name><params/></action> <action method="removeItem"><type>js</type><name>varien/js.js</name><params/></action> <action method="removeItem"><type>js</type><name>mage/translate.js</name><params/></action> <action method="removeItem"><type>js</type><name>varien/form.js</name><params/></action> <action method="removeItem"><type>skin_js</type><script>js/prototype.formalize.min.js</script></action> <action method="removeItem"><type>skin_css</type><name>css/formalize.css</name><params/></action>
Also, don't create a specific noConflict page, just put end of the jQuery script which is working well.
For instance, here is mine :
jQuery&&define("jquery",[],function(){return f})})(window);var $jQuery = jQuery.noConflict();
Also, yu should create jquery
folder in root js
directory, not in skin folder js
directory.
That's a floating point number. Unlike any other language I've ever encountered, all numbers in Javascript are actually 64-bit floating numbers. Technically, there are no native integers in Javascript. See The Complete Javascript Number Reference for the full ugly story.
-24742959 0 C# Get BIOS Events using C#I am trying to retrieve BIOS Event log so I can see low level hardware errors such as thermal events from recent model Dell Laptops. I know they have their own tool to do this but it doesn't do specifically what I need.
I know I can get some high level BIOS data using Win32_BIOS via WMI however I don't see the BIOS event log data that way which is what I am after. Anyone know how to get this or what WMI branch this is under in C# via Winforms (.Net 4.0) ?
(PS. Please don't suggest an alternative tool or discussing it with Dell as those options have already been explored and are not a direction I want to go. Thanks)
-39924973 0of course you can store it in a local variable and assign only if valid. But since you're calling exit(0)
if invalid it doesn't change anything. I suppose you want to break
from the loop instead.
BTW your loop is wrong. you have to divide sizeof(numArray)
by the size of one element otherwise you'll loop too many times and you'll crash the machine if there are too many numbers in your input file (yes, I also added a test for end-of-file)
if (myFile != NULL) { for (int i = 0; i < sizeof(numArray)/sizeof(numArray[0]); i++) { int x; //insert int to array if (fscanf(myFile, "%d", &x)==0) { printf("Invalid number found / end of file, closing application...\n"); exit(0); // end of file / not a number: stop } //Validate number if (x > 25) { printf("Invalid number found, closing application...\n"); exit(0); } numArray[i] = x; } //close file fclose(myFile); }
-4509624 0 How to limit depth for recursive file list? Is there a way to limit the depth of a recursive file listing in linux?
The command I'm using at the moment is:
ls -laR > dirlist.txt
But I've got about 200 directories and each of them have 10's of directories. So it's just going to take far too long and hog too many system resources.
All I'm really interested in is the ownership and permissions information for the first level subdirectories:
drwxr-xr-x 14 root root 1234 Dec 22 13:19 /var/www/vhosts/domain1.co.uk drwxr--r-- 14 jon root 1234 Dec 22 13:19 /var/www/vhosts/domain1.co.uk/htdocs drwxr--r-- 14 jon root 1234 Dec 22 13:19 /var/www/vhosts/domain1.co.uk/cgi-bin drwxr-xr-x 14 root root 1234 Dec 22 13:19 /var/www/vhosts/domain2.co.uk drwxr-xrwx 14 proftp root 1234 Dec 22 13:19 /var/www/vhosts/domain2.co.uk/htdocs drwxr-xrwx 14 proftp root 1234 Dec 22 13:19 /var/www/vhosts/domain2.co.uk/cgi-bin drwxr-xr-x 14 root root 1234 Dec 22 13:19 /var/www/vhosts/domain3.co.uk drwxr-xr-- 14 jon root 1234 Dec 22 13:19 /var/www/vhosts/domain3.co.uk/htdocs drwxr-xr-- 14 jon root 1234 Dec 22 13:19 /var/www/vhosts/domain3.co.uk/cgi-bin drwxr-xr-x 14 root root 1234 Dec 22 13:19 /var/www/vhosts/domain4.co.uk drwxr-xr-- 14 jon root 1234 Dec 22 13:19 /var/www/vhosts/domain4.co.uk/htdocs drwxr-xr-- 14 jon root 1234 Dec 22 13:19 /var/www/vhosts/domain4.co.uk/cgi-bin
EDIT:
Final choice of command:
find -maxdepth 2 -type d -ls >dirlist
-13044958 0 Use Sql Server to Store Asp.NET Session State http://support.microsoft.com/kb/317604
-39557151 0 Android Google plus friend listI having some confusion on google plus friends list ,
Before following (google plus - people method deprecated)
https://developers.google.com/+/web/api/rest/latest/people/list
We used following method for getting google plus friend list,
loadVisiblePeople(...)
but now a day it is deprecated.
So any one tell me , now in a new method of google plus , how to exactly get google friends list and which step follow for the same , and any other gradle file/compile library required for it ?
I study google plus document well but still having same confusion , So any one please remove my this confusion.
-13820741 0 Share or replicate Couchdb to MysqlI'm trying on a piece of software the uses couchdb. I'm not a coder, I don't understand how couchdb works, etc... So for that software, I wanted to use a website in php, that was built to work with mysql.
Is there a way that I can replicate the data that I need and delete those documents from couchdb, as couchdb grows a lot and fills my webspace in a flash.
For those who may know what software and what I want to do, I'm trying to get ecoinpool to work with a php frontend like simplecoin. If that fails how hard is it to get a php, already developed and working with mysql, website working with couchdb?
Thanks.
-33569165 0For me the error was that I tried to save an unserialisable object in the session so that an exception was thrown while trying to write the session. But since all my error handling code had already ceased any operation I never saw the error.
I could find it in the Apache error logs, though.
-4360581 0sorry, I should've read further in the tutorial I'm following. Apparently, the custom fields aren't part of the node object until you've retrieved them using hook_load(). Works fine now.
-22335272 0 Exception handling Try Catch blockI have been reading about exceptions for the past couple of hours and have a basic understanding. However the book I'am reading hasn't got the best examples when it comes to showcasing the coding aspects. I know that if I have code that could fail I wrap it in a try block and the catch the exceptions specifically i.e FormatException etc.
However the confusing part is when it comes to call stack were for e.g Method A calls Method B and Method B calls method C etc.
For example a exception occurs in Method c but it doesn't have a catch handler so it propagates back to the calling method so on and so fourth until one way or another the exception is handled.
What I was wondering is does execution continue in the method that caused the error or does execution continue in the method that handles the error.
Any basic examples would be great.
-2908729 0Even thought it's an old post, has anyone got an idea why not using the following concept:
Any input?
-13374351 0This article on Silverlight tabcontrol with scrollable tabItems may help
-37326885 0you have to make different layouts for both android phone and tablet.
Look at this link
-37034923 0NOTE: My previous answer was wrong. It has now been corrected.
C/C++ do not implement anything like Call-By-Value-Result (natively). As I understand it, that's an ADA term (Working on government code?). Call-By-Value would result in 15, Call-By-Reference is the trickiest one, because you would be modifying a
in line 3 as well as line 4 of your example.
--EDIT--
I have implemented the following code, which I believe to be a valid representation of the syntax described (I'm not familiar enough with ADA to do the test directly, maybe someone else can). As you will see, the result for By-Value-Result is 15.
#include <iostream> int a_v, a_r, a_vr; void foo_by_val(int x) { x = x + 10; a_v = a_v + x; } void foo_by_ref(int &x) { x = x + 10; a_r = a_r + x; } void foo_by_value_result(int &x_ref) { int x = x_ref; x = x + 10; a_vr = a_vr + x; // x = x_ref; <-- My previous mistake x_ref = x; } void fie( ){ a_v = 5; a_r = 5; a_vr = 5; foo_by_val(a_v); foo_by_ref(a_r); foo_by_value_result(a_vr); std::cout << "By Value: " << a_v << std::endl; std::cout << "By Refference: " << a_r << std::endl; std::cout << "By Value Result: " << a_vr << std::endl; } int main() { fie(); return 0; }
Result:
By Value: 20 By Reference: 30 By Value Result: 15
-17801477 0 I think you should shorten your code like this http://jsfiddle.net/DreamBig/tA7qw/4/. I put backgound-image in the div so you don't have to write it again in the keyframes definition like 6 or 10 times.
background-image: url('http://www.rotateweb.com/images/WebDesignB1.jpg');
I've tested and it runs perfectly in FF.
-33891961 0Thank you for your kind answer. I tried the Robot class this morning, but it wasn't able to cope with local files. I eventually found this video, and I'm now working my problem out. Fortunately AutoIt (which is a little bit like Sikuli I guess) can be plugged in Selenium. Thanks anyway!
-29214428 0The answer is much simpler than I thought. :)
You can try a jquery-ui.ruler . Is a simple jqueryUI plugin that have nive features:
Replace your current code to force HTTPs
and WWW
with this:
RewriteEngine On #Force SSL and WWW RewriteCond %{HTTP_HOST} !^www\. [NC,OR] RewriteCond %{HTTPS} !=on RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC] RewriteRule ^ https://www.%{SERVER_NAME}%{REQUEST_URI} [R=301,L,NE]
This will force WWW
and SSL
on everything.
Xcode has a built-in tool called agvtool. Agvtool only works if you have "Apple generic" version system in settings.
Change the version system to "Apple generic" in target settings.
Array indices start from 0 and are upto [upperbound-1]. Since your loop starts at 0, it must end at < the limit value rather than <= limit value. So, change the "<=" to "<" in the loop. Eg:
col <= _maxColIndex
should be changed to
col < _maxColIndex
-6216649 0I suspect that inside the script, your working directory is elsewhere, thus you cannot cd. Try this: instead of
cd "$DIREC"
replace it with
echo current directory is $PWD cd "m25.1240_m22.1250_m5.1540"
and see if you still have the same problem.
-31735092 0add the following line of code:
app.listen(443);
Also, try getting rid of all of the http module, as express handles most of that for you. Look at the beginning Hello World for Express, http://expressjs.com/starter/hello-world.html and look for the part where it handles the port.
-18928967 0 Vertically center a table usingI want to center align a Table VERTICALLY in html. I am using the following code which is working on all browsers except SAFARI. I need this to work in safari too. What is going wrong? Any help will be appreciated.
HTML:
<div tabindex="0" title="Style1" class="button_class size_class" role="button" aria-pressed="false" style="display: table;" unselectable="on"> <div class="Container" aria-hidden="true" style="text-align: center; vertical-align: middle; display: table-cell;"> <table class="Preview"> <tbody> <tr><td style="">—</td><td style="">—</td><td style="">—</td><td style="">—</td><td style="">—</td></tr> <tr><td style="">—</td><td style="">—</td><td style="">—</td><td style="">—</td><td style="">—</td></tr> <tr><td style="">—</td><td style="">—</td><td style="">—</td><td style="">—</td><td style="">—</td></tr> <tr><td style="">—</td><td style="">—</td><td style="">—</td><td style="">—</td><td style="">—</td></tr> <tr><td style="">—</td><td style="">—</td><td style="">—</td><td style="">—</td><td style="">—</td></tr> </tbody> </table> </div> </div>
CSS:
.button_class { border:1px solid transparent; display:inline-block; margin-left:0px; margin-right:2px; } .size_class { width:74px; height:58px; overflow:hidden; } .container { height: 48; width: 64; white-space: nowrap; overflow: hidden; } .preview { height: 32px; width: 64px; white-space: nowrap; overflow: hidden; vertical-align: baseline; display: block; }
-38705235 1 redis not working in my python django app I first followed the tutorial on the heroku site. I did this
pip install rq
then in a worker.py file
import os import redis from rq import Worker, Queue, Connection listen = ['high', 'default', 'low'] redis_url = os.getenv('REDISTOGO_URL', 'redis://localhost:6379') conn = redis.from_url(redis_url) if __name__ == '__main__': with Connection(conn): worker = Worker(map(Queue, listen)) worker.work()
and then
python worker.py
and I got the following error
Traceback (most recent call last): File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/redis/connection.py", line 439, in connect sock = self._connect() File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/redis/connection.py", line 494, in _connect raise err File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/redis/connection.py", line 482, in _connect sock.connect(socket_address) ConnectionRefusedError: [Errno 61] Connection refused During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/redis/client.py", line 572, in execute_command connection.send_command(*args) File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/redis/connection.py", line 563, in send_command self.send_packed_command(self.pack_command(*args)) File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/redis/connection.py", line 538, in send_packed_command self.connect() File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/redis/connection.py", line 442, in connect raise ConnectionError(self._error_message(e)) redis.exceptions.ConnectionError: Error 61 connecting to localhost:6379. Connection refused. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/redis/connection.py", line 439, in connect sock = self._connect() File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/redis/connection.py", line 494, in _connect raise err File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/redis/connection.py", line 482, in _connect sock.connect(socket_address) ConnectionRefusedError: [Errno 61] Connection refused During handling of the above exception, another exception occurred: Traceback (most recent call last): File "worker.py", line 15, in <module> worker.work() File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/rq/worker.py", line 423, in work self.register_birth() File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/rq/worker.py", line 242, in register_birth if self.connection.exists(self.key) and \ File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/redis/client.py", line 855, in exists return self.execute_command('EXISTS', name) File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/redis/client.py", line 578, in execute_command connection.send_command(*args) File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/redis/connection.py", line 563, in send_command self.send_packed_command(self.pack_command(*args)) File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/redis/connection.py", line 538, in send_packed_command self.connect() File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/redis/connection.py", line 442, in connect raise ConnectionError(self._error_message(e)) redis.exceptions.ConnectionError: Error 61 connecting to localhost:6379. Connection refused.
I then went to google and found the package index which I also followed which is
>>> import redis >>> r = redis.StrictRedis(host='localhost', port=6379, db=0) >>> r.set('foo', 'bar')
hit enter and got the following message
Traceback (most recent call last): File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/redis/connection.py", line 439, in connect sock = self._connect() File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/redis/connection.py", line 494, in _connect raise err File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/redis/connection.py", line 482, in _connect sock.connect(socket_address) ConnectionRefusedError: [Errno 61] Connection refused During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/redis/client.py", line 572, in execute_command connection.send_command(*args) File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/redis/connection.py", line 563, in send_command self.send_packed_command(self.pack_command(*args)) File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/redis/connection.py", line 538, in send_packed_command self.connect() File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/redis/connection.py", line 442, in connect raise ConnectionError(self._error_message(e)) redis.exceptions.ConnectionError: Error 61 connecting to localhost:6379. Connection refused. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/redis/connection.py", line 439, in connect sock = self._connect() File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/redis/connection.py", line 494, in _connect raise err File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/redis/connection.py", line 482, in _connect sock.connect(socket_address) ConnectionRefusedError: [Errno 61] Connection refused During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/redis/client.py", line 1072, in set return self.execute_command('SET', *pieces) File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/redis/client.py", line 578, in execute_command connection.send_command(*args) File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/redis/connection.py", line 563, in send_command self.send_packed_command(self.pack_command(*args)) File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/redis/connection.py", line 538, in send_packed_command self.connect() File "/Users/ray/Desktop/myheroku/practice/lib/python3.5/site-packages/redis/connection.py", line 442, in connect raise ConnectionError(self._error_message(e)) redis.exceptions.ConnectionError: Error 61 connecting to localhost:6379. Connection refused.
I have done no more or less then what these tutorials ask. How can I make this work?
-36785542 0 How to change the position of My Location Button in Google Maps using android studioI am working on google maps, and I need to change position of My Location(current location button). Presently current location button is at top-right side. So please help me how to re-position the current location button on google maps screen. Thanks in advance.
my sample code:
final GoogleMap googleMap = mMapView.getMap(); googleMap.setMyLocationEnabled(true);
-6034205 0 Login to iTunes Connect. Select Manage Applications and create or select your app in development. Then you can see the AppStore-Link (click View in App Store).
-40507132 0You have multiple problems here:
r
simply means treat the string as a raw string, it looks like you might think it creates a regular expression object; (in any case, zip.extract()
only accepts strings)*
quantifier at the start of the regex has no character before it to matchYou need to manually iterate through the zip file index and match the filenames against your regex:
from zipfile import ZipFile import re zip = ZipFile('myzipfile.zip') for info in zip.infolist(): if re.match(r'.*test.*\.xlsx$', info.filename): print info.filename zip.extract(info)
You might also consider using shell file globbing syntax: fnmatchcase(info.filename, '*.test.*.xls')
(behind the scenes it converts it to a regex but it makes your code slightly simpler)
Only for the sake of completeness: It has been found that it has something to do with the virtual machine in which the Windows runs. I use a network bridge to connect it to my local network. After adding a host-only network adapter, my windows service received all expected commands. No idea why!?
-14665748 0 Differences between p-values in summary and from the anova in R lm()I am seeing differences in the p-value for the anova depending on how I access this.
Is there a way to get the same value that is returned by the summary?
One easy to represent case returns < 2.2e-16 in the summary and in the anova but gives me 8.129959e-100 when I access the value directly:
x <- lm(formula = eruptions ~ waiting, data = faithful) summary(x) anova(x) anova(x)$"Pr(>F)"[1]
In another more difficult to represent case (there is a lot more data) I get p-value: < 2.2e-16 in the summary but 0 from anova.
Is there any way to get the actual value that is returned in the summary and anova?
I really appreciate your help -
-11681825 0i would rather go jquery..this jquery function will always center the image
jQuery.fn.center = function () { this.css("position","absolute"); this.css("top", (($(window).height() - this.outerHeight()) / 2) + $(window).scrollTop() + "px"); this.css("left", (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft() + "px"); return this; }
-27113111 0 Your fetch XML looks correct to me. When you set up the subgrid did you set "Records" = "All Record Types" in the Data Source section? If you did not then the subgrid will append a condition to your fetchxml so that it returns only records related to the specific relationship that you specified.
-13257966 0You can do this:
[Flags] enum Options { Option1 = 1, Option2 = 2, Option3 = 4, Option4 = 8, AllOptions = Option1 | Option2 | Option3 | Option4 }
This approach literally means Option1 and Option2 and Option3 and Option4. You can use this as:
Options.AllOptions;
or
Options.Option1 | Options.Option2 | Options.Option3 | Option.Option4
Both of the above will end up as the same result.
-23628064 0If you want to create instance of your class from name = Paul AND age = 16 AND country = china
that kind of script, then you could create yourself method
public <T> T builder(Class<T> clazz, String line) throws InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException { T instance = clazz.newInstance(); String[] exps = line.split("AND"); for (String exp : exps) { String[] tokens = exp.split("=", 2); // TODO check if token has length==2 tokens[0] = tokens[0].trim(); tokens[1] = tokens[1].trim(); String methodName = "set" + (("" + tokens[0].charAt(0)).toUpperCase()) + tokens[0].substring(1); Method m1 = instance.getClass().getMethod(methodName, String.class); m1.invoke(instance, tokens[1]); } return instance; }
and when you call it builder(Person.class,"name = Paul AND age = 16 AND country = china")
you will get instance of Person
class with populated fields name
, age
and country
.
Is that what you are looking for?
-39787024 0Its becasue,Java CLASSPATH points to current directory denoted by "."
and it will look for classes in the current directory.
In case we have multiple directories defined in CLASSPATH variable, Java will look for a class starting from the first directory and only look the second directory in case it did not find the specified class in the first directory. Multiple directories are added in classpath with the help of ":"
you have set classpath like
javac -classpath .:/path/to/graph/*:/path/to/graph/lib/* ErrorTest*.java
so using this command you are setting multiple directories in classpath.
JVM search directory in the order they have listed in CLASSPATH variable.
In your case seems some classes are present in the current directory so if you are not providing current directory in classpath JVM searches in second path and then third but required class is not present so seems that it is not working
-28126915 0 select data from 3 tables in laravel by using Eloquent ORMI am new to laravel and stuck on getting data using Eloquent ORM.
My Scenario is I have 3 tables
Now a user can visit a location multiple times and a location can be visited by multiple users.
I want to get all location name that a user visited on particular date.
But unable to get.
Below is the db structure
location_user table - id user_id location_id visitedtime
location table - id latitude longitude locality
user table - id name phone email
and In user model I have defined the relation
public function locations() { return $this->belongsToMany('Location')->withPivot('visitedtime'); }
when i use this function in controller then i get all the locations visited by that user
User::find(2)->locations()->select('locations.locality',locations.id')->get()
How can put condition on visitedtime on the above function
-8377059 0 Which character is Ctrl+Backspace?There are several places that you can enter this character by typing ctrl-backspace, including windows loggon password.
Which character is this and can I use it in a password?
-21040643 0I'm getting confused of seeing other's Answer. Then I searched a lot and get some idea about that. While searching only, I have learnt about new concept of A-GPS. I would like to share those things with you.
There are three
location providers.
1. GPS Provider 2. Network Provider (AGPS, CellID, WiFi MACID) 3. Passive Provider.
Note: I refer this from this site. As you asked question related to network provider, I will share regarding to that.
Network provider, name itself says that it needs network connection. Refer this article. It need network or WIFI connection to proceed.
A-GPS
GPS on cell phones is a bit more murky. In general, it won't cost you anything to turn on the GPS in your cell phone, but when you get a location it usually involves the cell phone company in order to get it quickly with little signal, as well as get a location when the satellites aren't visible (since the gov't requires a fix even if the satellites aren't visible for emergency 911 purposes). It uses up some cellular bandwidth. This also means that for phones without a regular GPS receiver, you cannot use the GPS at all if you don't have cell phone service.
For this reason most cell phone companies have the GPS in the phone turned off except for emergency calls and for services they sell you (such as directions).
This particular kind of GPS is called Assisted GPS
(AGPS).
Note: Even if phone supports it, and network does not then this does not work
-23239638 0 Youtube brandingI want to place YouTube video on my site with no branding . also I don't want any one to right click and grabbing the vid URL. JW player will support this but ppl still can click the YT watermark. is thire any way I could add allow networking internal only function to jw play. basically I don't want any onto go to YouTube and also to copy the url
-34555244 0I checked your website and i found following javascript error in console.
Mixed Content: The page at 'https://cypherbeats.com/' was loaded over HTTPS, but requested an insecure stylesheet 'http://fonts.googleapis.com/css?family=Oswald:300italic,400italic,600italic…0|&subset=latin,latin-ext,cyrillic,cyrillic-ext,greek-ext,greek,vietnamese'. This request has been blocked; the content must be served over HTTPS.
It means, your website loads using https and you are trying to fetch fonts from google fonts url using http.
Solution : Change path of the css which would included in your theme :
From :
<link href='http://fonts.googleapis.com/css?family=Oswald:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800|&subset=latin,latin-ext,cyrillic,cyrillic-ext,greek-ext,greek,vietnamese' rel='stylesheet' type='text/css'>
To :
<link href='https://fonts.googleapis.com/css?family=Oswald:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800|&subset=latin,latin-ext,cyrillic,cyrillic-ext,greek-ext,greek,vietnamese' rel='stylesheet' type='text/css'>
-17243437 0 Media Foundation: How to Decode Compressed AVI? folks!
I'm trying to transcode a compressed .avi file to .wmv using Media Foundation. While I've succeeded in using MSDN's sample for transcoding to handle an uncompressed .avi, I've had no luck with several different types of compressed .avi (Windows Video 1 is one example of compression).
Does anyone have experience with this? I have had little luck searching, other than MSDN (which does not clearly handle this particular case).
One route I'm leaning toward is writing a custom Media Foundation Transform to decode using Video For Windows internally, but it seems like I -must- be reinventing the wheel. A sample of something similar can be found here.
Please tell me I'm foolish and show me what I'm missing! Thanks. :)
-3593236 0how the code would be written greatly depends on where this array of 2 letter strings you have is coming from...but here is a self-contained example with some randomly generated 2 letter strings:
$strings = range('A','Z'); for ($a = 0;$a < 100; $a++) { $array[] = $strings[rand(0,25)] . $strings[rand(0,25)]; } for ($table = 1; $table <= 4; $table++) { $count = 0; $tarray = $array; echo "table " . $table . "<br/>"; echo "<table border='1'>"; for ($x = 0; $x < 10; $x++) { echo "<tr>"; for ($y = 0; $y < 10; $y++) { $alpha = array_splice($tarray,rand(0,count($tarray)-1),1); echo "<td>" . $count . $alpha[0] . "</td>"; $count++; } echo "</tr>"; } echo "</table>"; }
could shorten this with completely random generated 2 letter strings but i particularly wanted to show use of array_splice() if you have an actual array of 100 (or 400?) 2 letter strings and wanted to do a "pick once" deal, where you randomly select it and can only use it on one cell.
-25462693 0first of all put any ttf file in your asset folder then put on your textview like this
Typeface face = Typeface.createFromAsset(getAssets(), precious.ttf);//or any other ttf you want
String edittextString = title.getText().toString(); title.setText(""); title.setTypeface(face); title.setTextColor(Color.parseColor(hexColor)); if (edittextString != null) { title.setText(edittextString); }
-8552788 0 No. Email is not part of the operating system.
-10012046 0The problem is that you have no template. Your XAML should look somehow like this:
<Window x:Class="HKC.Desktop.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="487" Width="765.924" Loaded="Window_Loaded"> <Window.Resources> <ControlTemplate x:Key="buttonTemplate" TargetType="{x:Type Button}"> <Ellipse Name="el1" Fill="Orange" Width="100" Height="100"> <ContentPresenter VerticalAlignment="Center" HorizontalAlignment="Center" Content="{TemplateBinding Button.Content}" /> </ControlTemplate> </Window.Resources> <Grid x:Name="mainGrid" Background="#FF252525"> <Button Content="Push Me" Template="{StaticResource buttonTemplate}" Name="button1" Height="100" Width="100"/> </Grid> </Window>
-28980422 0 See This Demo
.Img{border: 2px solid grey;} .Img a:hover{ outline: 2px solid black;}
Note: Class Name can not start with integer.
Refer This for Rules regarding naming.
-13031542 0 algorithms to emulate human movement in a stick figureI need to make a program that lets you animate a stick figure, so I'm looking for some information on algorithms to emulate human movement. I found some software that lets you create animations with stick figures, but are hard to use because basically they don't help you emulate realistic movement, so the animator is responsible for everything. That's cool when you are or have an animator, but I'm not, I'm only a programmer.
I would really appreciate if someone knows about a library, or text with an explanation of these kinds of algorithms.
-22503592 0During the search for an answer i found many people with the same issue. I figured it out myself so here is my solution. I hope it is useful for other people.
Step 1. Create a SplitViewController project. If you have a project already skip this step ;)
Step 2. Add two different viewControllers. In this case i call them AbcViewController and XyzViewController.
Step 3. Go to the ipad storyboard, remove the DetailViewController from the storyboard. Then add two new viewControllers.
Step 4. Set the class and the Storyboard ID for your viewControllers.
Step 5. Go to your MasterViewController.h and replace the code with the code below.
#import <UIKit/UIKit.h> @class AbcViewController; @class XyzViewController; @interface MasterViewController : UITableViewController @property (strong, nonatomic) AbcViewController *abcViewController; @property (strong, nonatomic) XyzViewController *xyzViewController; @end
Step 6. Now go to your MasterViewController.m file and replace with this code:
Note: If you have an existing project and don't want to replace use the code in step 7.
#import "MasterViewController.h" #import "DetailViewController.h" @interface MasterViewController () { NSMutableArray *_objects; } @end @implementation MasterViewController - (void)awakeFromNib { if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) { self.clearsSelectionOnViewWillAppear = NO; self.preferredContentSize = CGSizeMake(320.0, 600.0); } [super awakeFromNib]; } - (void)viewDidLoad { [super viewDidLoad]; self.detailViewController = (DetailViewController*)[[self.splitViewController.viewControllers lastObject] topViewController]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } #pragma mark - Table View - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return 2; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath]; if (indexPath.row == 0) { cell.textLabel.text = @"ABC"; } if (indexPath.row == 1) { cell.textLabel.text = @"XYZ"; } return cell; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { self.abcViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"ABC"]; self.xyzViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"XYZ"]; if (indexPath.row == 0) { NSArray *newVCs = [NSArray arrayWithObjects:[[[self splitViewController ] viewControllers ] firstObject ] , self.abcViewController, nil]; self.splitViewController.viewControllers = newVCs; } if (indexPath.row == 1) { NSArray *newVCs = [NSArray arrayWithObjects:[[[self splitViewController ] viewControllers ] firstObject ] , self.xyzViewController, nil]; self.splitViewController.viewControllers = newVCs; } } @end
Step 7.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { self.abcViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"ABC"]; self.xyzViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"XYZ"]; if (indexPath.row == 0) { NSArray *newVCs = [NSArray arrayWithObjects:[[[self splitViewController ] viewControllers ] firstObject ] , self.abcViewController, nil]; self.splitViewController.viewControllers = newVCs; } if (indexPath.row == 1) { NSArray *newVCs = [NSArray arrayWithObjects:[[[self splitViewController ] viewControllers ] firstObject ] , self.xyzViewController, nil]; self.splitViewController.viewControllers = newVCs; } }
Thats it, run your project and enjoy :)
-16197557 0If you can specify what kinds of search strings this method will accept, you can use regular expressions. Here's an example which also uses Linq for brevity:
public IList<String> GetMatchingRemoteFiles(String SearchPattern, bool ignoreCase) { var options = ignoreCase ? RegexOptions.IgnoreCase : RegexOptions.None; return thirdPartyTool.ftpClient.GetCurrentDirectoryContents() .Where(fn => Regex.Matches(fn, SearchPattern, options)) .ToList(); }
Even if you cannot control what kinds of search strings this method accepts, it's still probably easier to convert the search string to a regular expression than write your own algorithm for matching the patterns. See Bobson's answer for details on how to do this.
-14441548 0Do you mean something like this?
<html> ... <?php include('codesnippet.php') ?> ... </html>
or the other way (showing the code up in a HTML document)?
<pre> <code> <!-- your snippet goes here, with escaped characters --> </code> </pre>
-1745256 0 I've omitted the dummy implementations I used but this compiled for me:
template< class T > class MyList { public: class const_iterator { public: const T& operator*(); bool operator!=( const const_iterator& ) const; const_iterator& operator++(); }; const_iterator begin() const; const_iterator end() const; };
-5924591 0 Added my comment as an answer:
You might want to look into the HTML5 Audio Data API. Other than that, you're going to need Flash if you want a legit spectrum analyzer (which, by the way, is what you're asking for. not an equalizer).
Edit:
For anyone interested, I have a quick and dirty demo here: http://kevincennis.com/audio/ (Chrome only)
Source is un-minified, but not particularly well commented. Feel free to steal whatever you want.
-16461895 0 scp folder structure and only files with a specific extensionI have a huge folder structure with deep subfolders, and inside these folders there is files with different extensions (.txt, .pdf, ...
).
what i want to do is to copy the whole folder structure along with the files with only the .pdf
extension.
I'm using scp
but there is no option to specify which extension to copy.
i tried rsync
with exclude and include options but it also did not worked and the shell window forze
P.S: I'm on MacOSX
Mountain Lion and i'm trying to copy from Fedora
16
what is the best way to do this ?
-24059510 0Posting comment as an answer since Bury says it works:
It appears your vr is a character string. If you go this route, you'll need to do the infamous eval(parse(text= paste0('subset(frame,' , vr,')' )))
construction.
TCP has no concept of packets. A TCP stream is a continuous stream of bytes - if you want a structure within that stream of bytes, you have to impose it yourself, by implementing some kind of framing mechanism. A simple one is the "length prefix" - when sending an application-level frame, you first send the length of the frame, then the data.
-20959054 0 Why is there a dramatic difference between aov and lmer?I have a mixed model and the data looks like this:
> head(pce.ddply) subject Condition errorType errors 1 j202 G O 0.00000000 2 j202 G P 0.00000000 3 j203 G O 0.08333333 4 j203 G P 0.00000000 5 j205 G O 0.16666667 6 j205 G P 0.00000000
Each subject provides two datapoints for errorType (O or P) and each subject is in either Condition G (N=30) or N (N=33). errorType is a repeated variable and Condition is a between variable. I'm interested in both main effects and the interactions. So, first an anova:
> summary(aov(errors ~ Condition * errorType + Error(subject/(errorType)), data = pce.ddply)) Error: subject Df Sum Sq Mean Sq F value Pr(>F) Condition 1 0.00507 0.005065 2.465 0.122 Residuals 61 0.12534 0.002055 Error: subject:errorType Df Sum Sq Mean Sq F value Pr(>F) errorType 1 0.03199 0.03199 10.52 0.001919 ** Condition:errorType 1 0.04010 0.04010 13.19 0.000579 *** Residuals 61 0.18552 0.00304
Condition is not significant, but errorType is, as well as the interaction.
However, when I use lmer, I get a totally different set of results:
> lmer(errors ~ Condition * errorType + (1 | subject), data = pce.ddply) Linear mixed model fit by REML Formula: errors ~ Condition * errorType + (1 | subject) Data: pce.ddply AIC BIC logLik deviance REMLdev -356.6 -339.6 184.3 -399 -368.6 Random effects: Groups Name Variance Std.Dev. subject (Intercept) 0.000000 0.000000 Residual 0.002548 0.050477 Number of obs: 126, groups: subject, 63 Fixed effects: Estimate Std. Error t value (Intercept) 0.028030 0.009216 3.042 ConditionN 0.048416 0.012734 3.802 errorTypeP 0.005556 0.013033 0.426 ConditionN:errorTypeP -0.071442 0.018008 -3.967 Correlation of Fixed Effects: (Intr) CndtnN errrTP ConditionN -0.724 errorTypeP -0.707 0.512 CndtnN:rrTP 0.512 -0.707 -0.724
So for lmer, Condition and the interaction are significant, but errorType is not.
Also, the lmer result is exactly the same as a glm result, leading me to believe something is wrong.
Can someone please help me understand why they are so different? I suspect I am using lmer incorrectly (though I've tried many other versions like (errorType | subject) with similar results.
-27212097 0The first one gets filename from the path, but second one will directly give the uploaded filename via upload control PostedFile
property whose properties have information about uploaded file like name,size and extension .
I suggest to use second one, no need of System.IO as control has property which returns filename.
-4769388 0 How to define that float is half of the number?What would be the most efficient way to say that float value is half of integer for example 0.5, 1.5, 10.5?
First what coming on my mind is:
$is_half = (($number - floor($number)) === 0.5);
Is there any better solutions?
-17445332 0You don't want to change an include. That's not an option.
It seems that you want to use AJAX. You could load the content of the include in any element of the site using $.load
.
For example. To load link1.php
in the element #links
, we could do:
$(document).ready(function() { $('.allbuttons #button1').click(function() { $('#links').load("http://"+ document.domain + "/includes/link1.php"); }); $('.allbuttons #button2').click(function() { $('#links').load("http://"+ document.domain + "/includes/link2.php"); }); });
-35901004 0 Failing to deliver Azure NotificationHub push messages to (Android) devices from .NET console app I have configured a .NET App Service using the "Quick Start" instructions in the newer Azure Portal to publish an app service to use as my mobile back end. I have also configured a notification hub for it and am able to send push notifications from a Xamarin.Forms Android app via the Azure mobile back end endpoint. I can also receive the push notification on a registered Android device.
I need to be able to send push notifications to registered devices from a C# console application but no matter what I try, the push messages are not delivered.
I am using the following code to attempt to send push messages. When I run it, the execution ends on...
var result = await hub.SendTemplateNotificationAsync(templateParams);
...and console app terminates without waiting for the response and the push notification is never delivered to the registered device.
public async void PushSmartAlerts() { string notificationHubName = "DevXXXXNotificationHub"; string notificationHubConnection = "Endpoint=sb://devXXXXXnotificationhubnamespace.servicebus.windows.net/;SharedAccessKeyName=DefaultFullSharedAccessSignature;SharedAccessKey=SnXXXXXXXXXXXXXXXXXXXXXXXX9N8="; hub = NotificationHubClient .CreateClientFromConnectionString(notificationHubConnection, notificationHubName); Dictionary<string, string> templateParams = new Dictionary<string, string>(); templateParams["messageParam"] = "Hello"; var result = await hub.SendTemplateNotificationAsync(templateParams); }
Can anyone tell me what is wrong or if I am going about it the wrong way?
-4150771 0Nope, not possible, at least not for class constants.
You cannot use any of the following [reserved] words as constants, class names, function or method names.
I don't know about C#, but there isn't any special symbol in PHP to transform a keyword into an identifier. As long as you don't name it exactly the same as a keyword (barring letter case), it'll just be any normal constant name.
How about a (different since it's not just CSS) prefix? Gets repetitive to type, but is a nice workaround. I realize this may be redundant as well if your class is named something like HTMLAttribute
, but it's the easiest way out.
const A_ID = 'id'; const A_CLASS = 'class'; // etc
-16654332 0 DO NOT use htmlUnit.
You would've thought that you would only need a couple of core jars. Nah, you might need all of them otherwise you might run into some class not found errors.
Just take a look at how many jars you have to load into Eclipse before you can run it! A total of 21 jars, over 10mb! Bear in mind that you can also package up to 50mb for Android Market. It just slows Eclipse down and you probably have to increase the memory when you debug.
Use Jsoup instead!
-40597026 0 regex character appears exactly x timesI'm working in bash and I have a large file in which I want to remove all the lines that do not match a certain regex, probably using $ grep -e "<regex>" <file> > output.txt
What I want to keep is any line that contain exactly x times a specified character, for example in the binary sequence
0000, 0001, 0010, 0011, 0100, 0101, 0111, 1000, 1001, 1010, 1011, 1100, 1101, 1110, 1111
I would like to keep only those who have 2 1, leaving me with
0011, 0101, 0110, 1001, 1010, 1100
I would then use a bash variable to vary the amount I need (always exactly half of the length, working with strings of the same length) I'm litterally looking for lines that are half 0 and half 1
I have this right now. It's not using regex. It works, but is very slow:
($1
is the length of every string, $d
is just a directory)
sed -e 's/\(.\)/\1 /g' < $d/input.txt > $d/spaces.txt awk '{c=0;for(i=1;i<=NF;++i){c+=$i};print c}' $d/spaces.txt > $d/sums.txt grep -n "$(($1/2))" $d/sums.txt | cut -f1 -d: > $d/linenums.txt for i in $(cat $d/linenums.txt) do sed "${i}q;d" $d/input.txt done > $d/valids.txt
In case you wonder this puts spaces in between every digit turning 1010
into 1 0 1 0
, then it adds the values together, saves the results in sums.txt, grep for length/2 and save only the line numbers in linenums.txt, then it reads linenums.txt and outputs the corresponding line from input.txt to output.txt
I need something quicker, the for loop is what's taking way too long
Thanks for your time and for sharing your knowledge with me.
-25129810 0zerkms's answer cuts to the gist of what you actually need to know, and is correct. Transaction isolation will make sure you're not affected by concurrency issues in this simple case (but note, it's not a magic solution to all concurrency).
To answer your question literally as written: they're actually interleaved.
If you write:
SELECT SUM(field1)+SUM(field2)+SUM(field3)-SUM(field4) FROM mytable;
then Pg reads mytable
once. It reads each row and feeds the mytable.field1
to the first sum, mytable.field2
into the second sum, etc. Then it repeats for each row.
So all the aggregation is done in parallel (though not using multiple CPUs).
-34591094 0 How to keep a golang.org/x/net/websocket open?I'm naively use _, err := ws.Read(msg) to keep a Web socket open in my code. I don't think it works reliably.
In other code I've noticed people doing a sleep loop. What's the correct way to keep a Web socket open & stable? I assume the underlying library does ping/pongs?
Update: I'm pretty confident that the client.go is to blame since it doesn't seem to redial after a disconnect is seen on the server. I made a video demonstrating the issue.
-19638245 0 C# service: setup returns error 1001. Source MyService already exists on the local computer. EventID 11001Currently I try to create a C# (2010) service.
I have created a visual studio setup project. Whenever I try to install the service I get the message
Error 1001. Source MyService already exists on the local computer.
In the eventlog I find the following info:
- System - Provider [ Name] MsiInstaller - EventID 11001 [ Qualifiers] 0 Level 2 Task 0 Keywords 0x80000000000000 - TimeCreated [ SystemTime] 2013-10-28T14:28:23.000000000Z EventRecordID 206256 Channel Application Computer <MyComputer> - Security [ UserID] S-1-5-21-703477020-2137377117-2121179097-8027 - EventData Product: MyServiceSetup -- Error 1001. Error 1001. Source MyService already exists on the local computer. (NULL) (NULL) (NULL) (NULL) (NULL) 7B30353636304544462D374645372D344243312D414442422D4534424244343645393646457D
I have tried the following commands (in a command window with admin-rights):
InstallUtil /u MyService.exe
and
sc delete MyService
But I keep getting this error. I install with sufficient rights. And I have absolutely no idea where I have to look for the solution.
Can somebody please help me? I have almost no hair left to pull out...
Thanx!!!
-1461672 0 Sorting Two Combo Boxes Differently in WPFI have in a form two combo boxes that have the exact itemssource property. Both combo boxes need to be sorted, but in two different ways. One is sorted by the ID (numeric), the other one by Name(Alphabetic).
Is it possible to do such a thing?
Thanks
-17143749 0Android native Traceview will help you measuring the time and also will give you more information. Using it is as simple as:
// start tracing to "/sdcard/calc.trace" Debug.startMethodTracing("calc"); // ... // stop tracing Debug.stopMethodTracing();
A post with more information in Android Developers Blog
Also take @Rajesh J Advani post into account.
-39514294 0 C# Interop.Outlook: Folder.AddToPFFavorites() without adding all subfolders?In Outlook, I'm trying to add a shared public folder (provided by Exchange) to the list of favorite folders programmatically. I've written an Outlook-AddIn for this, that uses the Microsoft.Office.Interop.Outlook library. In this library, there's only one way to add public folders to the favorite list:
Folder.AddToPFFavorites().
The problem: When calling this method, Outlook not only adds the folder itself to the favorites list, but also ALL subfolders. In our company, we have a huge tree of subfolders attached to some folders, so I get major performance problems (Outlook completely crashes when the folder to add has too many subfolders).
Do you know a way to programmatically add only the folder itself to the favorites, without any subfolders?
-33100847 0 Global variable inside of functionCode below prints produces error:
Notice: Undefined variable: x in C:\wamp\www\h4.php on line 9
and output:
Variable x inside function is: Variable x outside function is: 5
Code:
<html> <body> <?php $x = 5; // global scope function myTest() { // using x inside this function will generate an error echo "<p>Variable x inside function is: $x</p>"; } myTest(); echo "<p>Variable x outside function is: $x</p>"; ?> </body> </html>
What gets wrong with x
global variable inside of myTest
function?
I've created a fiddle based on your code https://jsfiddle.net/d24z9ka4/ It's lousy but it works :-), and here is how:
text.onkeyup = function(evt) { // get how many times 'Brasil' occurs var counter = this.textContent.split(/(Brasil)/ig).length; // lastCount is the place of the last occurrence, or nothing if (counter > 1 && (!this.lastCount || this.lastCount < counter) ) { this.lastCount = counter; // get's all places where 'Brasil' is written this.innerHTML = this.textContent.replace(/(Brasil)/ig, "<b class='green'>Brasil</b> "); // this moves cursor to last position available // based on this https://stackoverflow.com/questions/6249095/how-to-set-caretcursor-position-in-contenteditable-element-div var range = document.createRange(); var sel = window.getSelection(); // this is last node available, we'll go there var lastNode = text.childNodes.item(text.childNodes.length -1) range.setStart(lastNode, 1); range.collapse(true); sel.removeAllRanges(); sel.addRange(range); } };
-35912561 0 To answer the edit part :
adding a pre-slash to my css routes fixed the problem.
ie from href="something/myfile.css" to href="/something/myfile.css"
I don't really understand why though.
-9008252 0To start an app you need to call CeCreateProcess
. Registry access starts with CeRegOpenKeyEx
(there are reads, writes, etc too). All of these are also wrapped in managed code in this open-source library.
Where will the variable 123 come from? what is the variable input to compute 123?
you can do the following
RewriteRule de/(.+) de/123/$1
than de/somepage will be redirected to de/123/somepage.
In addition of course you can do redirects without htaccess on server side using php
header("Location: http://www.example.com/"); /* Redirect browser */
-29298688 0 Add all the spans to your HTML, but hide them initially. Then use an if
statement to show the one you want.
function calculate() { var myBox1 = document.getElementById('box1').value; var myBox2 = document.getElementById('box2').value; var myBox3 = document.getElementById('box3').value; var result = document.getElementById('result'); var divide = (document.getElementById('changeValue').checked ? 35 : 25); var myResult = myBox1 * myBox2 * myBox3 / divide; var links = document.getElementsByClassName("link"); for (var i = 0; i < links.length; i++) { links[i].style.display = "none"; } var linkToShow; if (myResult < 30) { linkToShow = 0; } else if (myResult < 50) { linkToShow = 1; } else if (myResult < 70) { linkToShow = 2; } else { linkToShow = 3; } links[linkToShow].style.display = "inline"; result.value = myResult.toFixed(2) + ' eggs'; }
.link { display: none; }
<input type="text" id="box1" oninput="calculate()" /> <input type="text" id="box2" oninput="calculate()" /> <input type="text" id="box3" oninput="calculate()" /> <input id="result" /> <a class="link" href="link-1">link-1</a> <a class="link" href="link-2">link-2</a> <a class="link" href="link-3">link-3</a> <a class="link" href="link-4">link-4</a> <br /> <br /> <br /> <input type="checkbox" name="changeValue" id="changeValue" /> <label for="changeValue">Divide with 35</label>
The way you are storing data breaks normalization rules. Only a single atomic value should be stored in each field. You should store each item in a single row.
-35300792 0That's an HTML specific encoding so:
echo html_entity_decode('für'); // returns für
http://php.net/manual/en/function.html-entity-decode.php
-2450634 0function combined(curtext, curimage){ if(curtext == "View large image"){ document.getElementById("boldStuff").innerHTML = "View small image"; curtext="View small image"; } else{ document.getElementById("boldStuff").innerHTML= "View small image"; curtext="View large image"; } if(curimage == "cottage_small.jpg"){ document.getElementById("myImage").src="cottage_large.jpg"; curimage="cottage_large.jpg"; } else{ document.getElementById("myImage").src="cottage_large.jpg"; curimage="cottage_small.jpg"; } }
-36582704 0 We're using NUnitLite to run NUnit tests in our ASP.NET Core applications. My main issue was actually finding the documentation for this package, which is available at https://github.com/nunit/docs/wiki/NUnitLite-Runner.
The minimal Main
method to run the tests could look like this:
using NUnitLite; public class Program { public int Main(string[] args) { return new AutoRun().Execute(args); } }
Create a command to start the project (i.e. the console application). In the example project.json
file shown below the command Test
will run all tests except those annotated with [Category("SlowTest")]
.
{ "version": "1.0.0-*", "description": "Tests for the SelfServicePortal", "dependencies": { "SelfServicePortal": "1.0.0-*", "NSubstitute": "1.9.2", "NUnit.Runners": "3.0.1", "NUnitLite": "3.0.1", "NUnit.Console": "3.0.1", "Microsoft.Dnx.Runtime": "1.0.0-rc1-final" }, "commands": { "Test": "SelfServicePortal.Tests -where \"cat != SlowTest\"" }, "frameworks": { "dnx451": { } } }
Hope this helps. Here's a test run with some unnecessary censoring:
-15627355 0From the error log i.e. MediaPlayer Event 11 was not found in the queue, already cancelled
is a warning and not an error. Please refer to this link. Hence, if your MediaPlayer
is exiting, then there should be some other issue.
This warning is printed when an event
which was expected to be triggered
gets removed from the queue
before it actually triggered. This can happen in multiple cases. For example, in case of pause
, all player events are cancelled as shown here.
In your case, I feel that one of the potential scenario would be thus. AwesomePlayer
would have triggered an event
to read the next video frame from the video decoder i.e. mVideoSource
. In between you pressed pause
which caused all events to be removed. So when TimedEventQueue
triggered in this threadRun
loop, it would observe that this event
has been removed and hence, the log.
The structure you want for
((te.TeamId in (1) and ar.TeamReadOnly = 1) or te.TeamId is null)
will be something like:
Restrictions.or( Restrictions.and( Restrictions.in(x, x), Restrictions.eq(x, x) ), Restrictions.eq(x,x) )
-2510115 0 jQuery: Can I call delay() between addClass() and such? Something as simple as:
$("#div").addClass("error").delay(1000).removeClass("error");
doesn't seem to work. What would be the easiest alternative?
-21965615 0 PayPal related policy and integrationI am currently developing an auction website and I am wondering if I can hold payments. I need to do this to avoid unfair deals. For example:
A seller didn't deliver the item to the buyer. I need to hold the payment and then once the buyer has confirmed that the item has been delivered the payment will be transferred to the account of the seller. Is there any possible way to attain this logic?
Thanks
-22499820 0With Bing Ajax 7 the QuadKey in not the only item provided, it also provides x, y, and levelOfDetail, a.k.a Zoom.
Until I spotted this I too thought about a server side transformation, but it is available to you in javascript.
Bing maps comes with x,y, and z that can be used for OSM web requests directly:
var map = new Microsoft.Maps.Map( <snip> ) function useZXY(tile) { return "http://tile.openstreetmap.org/" + tile.levelOfDetail + "/" + tile.x + "/" + tile.y +".png"; } var omsTS = new Microsoft.Maps.TileSource({ uriConstructor: useZXY }); var omsTL = new Microsoft.Maps.TileLayer({ mercator: omsTS, opacity: 0.5 }); map.entities.push(omsTL) ;
-32539296 0 As the OP mentioned that both player play the game optimally,I am going to present an algorithm under this assumption.
Definitely if both players play optimally,then definitely the sum they obtain at the end would be maximum,otherwise they are not playing optimally.
There are two different cases here:
I make the first move and pick element at position x
Now because we have to obey the condition that only adjacent elements could be picked,let me define two arrays here.
left[x]: It is the sum of elements that can be obtained by adding
array[0],array[1]....array[x-1],the elements left to x.
right[x]: It is the sum of elements that can be obtained by adding
array[x+1],array[x+2]....array[n-1],the elements right to x.
Now,because the other player also plays optimally,what he will do is he will check what I can possibly achieve and he finds that,I could achieve the following:
array[x] + left[x] = S1
OR
array[x] + right[x] = S2
So what the other player does is finds the minimum of the S1 and S2.
If S1 < S2 this means that if the other player picks element at x+1,he just took away the better part of array from us because now we are left with a lesser sum S1
If S1 > S2 this means that if the other player picks element at x-1,he just took away the better part of array from us because now we are left with a lesser sum S2
Because I am also playing optimally I would in the very first move pick such x which has minimum absolute value of (right[x]-left[x]),so that even if our opponent takes the better part of array from us,he is only able to take away minimum
Therefore,If both players play optimally, the maximum sums obtained are:
Update.
x + left[x] and right[x]//when second player in his first move picks x+1
Therefore,in this case the moves made are:
Player 1:Picks element at position x,x-1,x-2....0. Player 2:Picks element at position x+1,x+2,....n-1
Because each player has to pick adjacent element to the previously picked element by him.
OR
x + right[x] and left[x]//when second player in his first move picks x-1
Therefore,in this case the moves made are:
Player 1:Picks element at position x,x+1,x+2....n-1. Player 2:Picks element at position x-1,x-2,....0.
Because each player has to pick adjacent element to the previously picked element by him.
where x is such that we obtain minimum absolute value of (right[x]-left[x]).
Since OP insisted on posting pseudocode,here is one:
Computing the left and right array.
for(i = 0 to n-1) { if(i==0) left[i]=0; else left[i] = left[i] + array[i-1]; j = n-1-i; if(j==n-1) right[j]=0; else right[j]= right[j] + array[j+1]; }
The left and right arrays initially have 0 in all positions.
Computing max_sums.
Find_the_max_sums() { min = absoulte_value_of(right[0]-left[0]) x = 0; for(i = 1 to n-1) { if( absolute_value_of(right[i]-left[i]) < min) { min = absolute_value_of(right[i]-left[i]); x=i; } } }
Clearly Both space and time complexity of this algorithm is linear.
-40063205 1 pdfkit - python : 'str' object has no attribute decodeI am attempting to use pdfkit to convert string html to a pdf file. This is what I am doing
try: options = { 'page-size': 'A4', 'margin-top': '0.75in', 'margin-right': '0.75in', 'margin-bottom': '0.75in', 'margin-left': '0.75in', } config = pdfkit.configuration(wkhtmltopdf="/usr/local/bin/wkhtmltopdf") str= "Hello!!" pdfkit.from_string(str,"Somefile.pdf",options=options,configuration=config) return HttpResponse("Works") except Exception as e: return HttpResponse(str(e))
however at from_string
I get the exception 'str' object has no attribute decode. Any suggestions on how I can fix this ? I am using Python 3.5.1
I use fmdatabase for my sqlite project, i add lib to my frameworks and could run on simulator, when i want to release my project have a linking error. does anyone know how to fix it? Thanks
-10222772 0I'm new with WTForms but it seems to me that the solution could be improved instead of using :
{{ form.field(autofocus=true, required=true, placeholder="foo") }}
use :
{% if field.flags.required %} {{ field(autofocus=true, required=field.flags.required, placeholder="foo") }} {% else %} {{ field(autofocus=true, placeholder="foo") }} {% endif %}
WTForms seems not to handle correctly required=false
for 100% HTML5 and sets in the HTML an attr required="False"
instead of removing the attr. Could this be improved in next version of WTForms?
I have a box that is initiated without a frame so it has 0 center and size.
let blackBox = UIView() blackBox.backgroundColor = .blackColor() blackBox.translatesAutoresizingMaskIntoConstraints = false view.addSubview(blackBox) view.addConstraint(NSLayoutConstraint(item: blackBox, attribute: .Width, relatedBy: .Equal, toItem: view, attribute: .Width, multiplier: 0.1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: blackBox, attribute: .Height, relatedBy: .Equal, toItem: view, attribute: .Height, multiplier: 0.5, constant: 0)) view.addConstraint(NSLayoutConstraint(item: blackBox, attribute: .CenterX, relatedBy: .Equal, toItem: view, attribute: .CenterX, multiplier: 1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: blackBox, attribute: .CenterY, relatedBy: .Equal, toItem: view, attribute: .CenterY, multiplier: 1, constant: 0))
Is there anyway to insert a centered subview into the blackBox
without using autolayout or is there a neater way I could/should use it. The only way I can see this happening is:
let blueBox = UIView() blackBox.addSubview(blueBox) blueBox.translatesAutoresizingMaskIntoConstraints = false blueBox.backgroundColor = UIColor.blueColor() view.addConstraint(NSLayoutConstraint(item: blueBox, attribute: .CenterX, relatedBy: .Equal, toItem: blackBox, attribute: .CenterX, multiplier: 1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: blueBox, attribute: .CenterY, relatedBy: .Equal, toItem: blackBox, attribute: .CenterY, multiplier: 1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: blueBox, attribute: .Width, relatedBy: .Equal, toItem: blackBox, attribute: .Width, multiplier: 0.4, constant: 0)) view.addConstraint(NSLayoutConstraint(item: blueBox, attribute: .Height, relatedBy: .Equal, toItem: blackBox, attribute: .Height, multiplier: 0.4, constant: 0))
-38393992 1 Error while creating folder using google drive api I have activated drive api using this link:https://developers.google.com/drive/v3/web/quickstart/python. Quickstart.py is working fine and can read metadata.
Now i am trying to create a folder in a parent folder using parent id.Program is working fine till verification but no folder is getting created.I am just stuck here.Even console is not giving any errors. Plz find full code below and if possible suggest somthing.
import os import httplib2 # pip install --upgrade google-api-python-client from oauth2client.file import Storage from apiclient.discovery import build from oauth2client.client import OAuth2WebServerFlow # Copy your credentials from the console # https://console.developers.google.com CLIENT_ID = 'xxxxxxxxxx.apps.googleusercontent.com' CLIENT_SECRET = 'yyyyyyyyyyyyy' OAUTH_SCOPE = 'https://www.googleapis.com/auth/drive' REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob' OUT_PATH = os.path.join(os.path.dirname(__file__), 'out') CREDS_FILE = os.path.join(os.path.dirname(__file__), 'credentials.json') storage = Storage(CREDS_FILE) credentials = storage.get() if credentials is None: # Run through the OAuth flow and retrieve credentials flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, REDIRECT_URI) authorize_url = flow.step1_get_authorize_url() print 'Go to the following link in your browser: ' + authorize_url code = raw_input('Enter verification code: ').strip() credentials = flow.step2_exchange(code) storage.put(credentials) # Create an httplib2.Http object and authorize it with our credentials http = httplib2.Http() http = credentials.authorize(http) drive_service = build('drive', 'v2', http=http) def createRemoteFolder(self, folderName, parentID = '0B-mk9lmuB70PTkIwUmtMeEREaEU'): # Create a folder on Drive, returns the newely created folders ID body = { 'title': folderName, 'mimeType': "application/vnd.google-apps.folder" } if parentID: body['parents'] = [{'id': parentID}] root_folder = drive_service.files().insert(body = body).execute() return root_folder['id']
-4622416 0 I know I'm coming really late to the game, but we were struggling with this exact same problem and here is how we solved it.
First, we edited the csproj files of all non-merged or satellite projects to use a conditional reference to an external assembly based upon existence of a file. In this case, we're going to test for the existence of the merged assembly. Then we ran a build script which does the following:
I have a Junction table with clustered index
CREATE TABLE [dbo].[MeetingTags] ( [MeetingId] INT NOT NULL, [TagId] INT NOT NULL, CONSTRAINT [FK_MeetingTags_Tags] FOREIGN KEY ([MeetingId]) REFERENCES [dbo].[Meetings] ([Id]), CONSTRAINT [FK_Tags_MeetingTags] FOREIGN KEY ([TagId]) REFERENCES [dbo].[Tags] ([Id]) ); GO CREATE CLUSTERED INDEX [cdxMeetingTags] ON [dbo].[MeetingTags]([MeetingId] ASC, [TagId] ASC);
Obviously, it has common field of the table Meetings and Tags so that I can add record on it by this way
var tag= new Tag() { Title = "Meeting Title", }; meeting.Tags.Add(tag);
Looks good, however I'm getting this error in Context.SaveChanges()
when Inserting new Tags record.
Unable to update the EntitySet 'MeetingTags' because it has a DefiningQuery and no <InsertFunction> element exists in the <ModificationFunctionMapping> element to support the current operation
Tags has Primary Key.
I think putting a Primary Key in the MeetingTags
is not possible as it will break the Many-to-Many relationship of Meeting and Tags in the EF, and it will also add Meeting.MeetingTags.Tags
in the syntax instead of just Meeting.Tags
Any workaround on this?
-5174867 0function getWordAt(str, pos) { // Perform type conversions. str = String(str); pos = Number(pos) >>> 0; // Search for the word's beginning and end. var left = str.slice(0, pos + 1).search(/\S+$/), right = str.slice(pos).search(/\s/); // The last word in the string is a special case. if (right < 0) { return str.slice(left); } // Return the word, using the located bounds to extract it from the string. return str.slice(left, right + pos); }
This function accepts any whitespace character as a word separator, including spaces, tabs, and newlines. Essentially, it looks:
/\S+$/
/\s/
As written, the function will return ""
if the index of a whitespace character is given; spaces are not part of words themselves. If you want the function to instead return the preceding word, change /\S+$/
to /\S+\s*/
.
Here is some example output for "This is a sentence."
0: This 1: This 2: This 3: This 4: 5: is 6: is 7: 8: a 9: 10: sentence. // ... 18: sentence.
Modified to return the preceding word, the output becomes:
0: This 1: This 2: This 3: This 4: This 5: is 6: is 7: is 8: a 9: a 10: sentence. // ... 18: sentence.
-30226168 0 Chrome ignores prefer-online
or at least it used to. Firefox honors it, or at least it used to. So test it with Firefox.
Generally, do not rely on prefer-online
as the user agent can choose to ignore it. Think of it more as advisory than compulsory.
Try this:
if(states != null) { return PartialView(states.ToList()); } return PartialView();
-37281977 0 But Haskell doesn't seem to be too happy with:
thecolour:leftofcurrent:rightofcurrent
That's because leftofcurrent
is a List. If you want to combine those lists, it needs to be:
(thecolour:leftofcurrent) ++ rightofcurrent
Likewise, (leftofcurrent:current:[])
is impossible because leftofcurrent
is a List, but this is probably what you're after:
leftofcurrent ++ [current]
The cons operator :
expects a single element on the left and a list on the right. But because of its fixity, you can chain them together so that a bunch of single items are separated by :
and ended with a list. That is,
item1:item2:item3:[] -- is the same as item1:(item2:(item3:[]))
Also, your pattern matching is non-exhaustive. You need to handle the case where the second list parameter is empty.
putfront leftofcurrent [] thecolour = ...
-30923524 0 Not really doable without CSS. The easiest way to handle a scenario is to wrap the three divs in a container, then use display: inline-block
on the three divs.
At the beginning of the new year, I buy a domain: danielpan.me. After creating a droplet in digitalocean, I deployed wordpress on my remote server. The tutorial I followed is here. But something I didn't understand happened. After removing the file of /var/www/html/index.html, my server displayed like this:
You know, this is not a right result. It should display something like this:
This confused me a lot. I don't know how to do next after that much googling. Even so I don't want a solution about redirections. Could anyone who ever run into such a scene help me? Thanks very much in advance.
-6567405 0Download Web Matrix from
http://www.microsoft.com/web/webmatrix/
http://www.microsoft.com/web/post/add-a-photo-gallery-to-your-website-using-lightbox-and-javascript
-25607090 0There is no significant difference between these, you will get pretty much the same results:
str.Split(';').First() vs. str.Split(';')[0]
For your second comparison, here you are asking only the first element
list.Where(x => x > 1).First()
So as soon as WhereIterator
returns an item it's done. But in second you are putting all results into list then getting the first item using indexer , therefore it will be slower.
First of all - in your sql you have:
`product_id` = '1'
do not use id value as a string:
`product_id` = 1
About your problem:
Add another condition:
if ('POST' == $_SERVER['REQUEST_METHOD']) { if ( !empty($_POST['submitType']) && ( $_POST['submitType'] == 'like' ) ) { $sql = "UPDATE table set `likes` = `likes`+1 where `product_id` = '1'"; $result=mysql_query($sql); } }
and in html:
<input type = "submit" name="submitType" value = "like"/>
-35948805 0 You Should use Cookie
not Set-Cokkie
. Others are fine
req = urllib2.Request(url) req.add_header('Content-Type', 'application/json') req.add_header('Cookie', 'session=value=') response = urllib2.urlopen(req, data=json.dump(data))
When Server response, it uses Set-Cookie
to persist a cookie in client, when client want to callback, it just use Cookie
as header.
The reason this doesn't work is because the deprecated Date
constructor that you're using expects year - 1900
as the first argument.
You should either use a SimpleDateFormat
or a GregorianCalendar
to do this conversion instead. Since there is already an excellent answer here, showing the use of SimpleDateFormat
, here's how you use GregorianCalendar
for 1:39am on 14 March 2014.
new GregorianCalendar(2014, 2, 14, 1, 39, 0).getTime().getTime();
Beware that the month uses 0 for January and 11 for December.
-23476802 0To position something absolutely (which is what you want to do), it has to have container that also has positioning set to position itself against. Sounds complex, but it's not really.
If you set your container to position:relative (meaning keep it in the flow of the document where it would normally be), then you can set descendant elements to position: absolute.
So, in your case, if you wrap your image and button in a div and set the div to position: relative, you can set the button to position: absolute like this:
<div style="position: relative;"> <img src="yourimagename.jpg" alt=""> <button style="position: absolute; top: 0; right: 0; z-index: 1;">×</button> </div
-40393257 0 I agree with JDillon's answer to set the data-src and then switch the src when ready to init the player. Like so:
html
<iframe id="sc-widget" width="0" height="0" scrolling="no" frameborder="no" src="" data-src="https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/3333333%3Fsecret_token%3Dx-xxxx&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&visual=true"></iframe>
js (es6)
let widgetIframe = document.getElementById('sc-widget') widgetIframe.src = widgetIframe.dataset.src let $embedPlayer = SC.Widget(widgetIframe) /* example of using soundcloud embed player */ $embedPlayer.bind(SC.Widget.Events.PLAY, () => { $embedPlayer.getDuration((duration) => setDuration(duration)) }) $embedPlayer.bind(SC.Widget.Events.PLAY_PROGRESS, () => { $embedPlayer.getPosition((position) => setPosition(position)) }) function setPosition(pos) { console.log(pos) } function setDuration(dur) { console.log(dur) }
Then I also agree with adi's answer that you cannot use display: none;
to hide the player if you are creating your own player to control the soundcloud embed player. In this case you need to hide it with the following styles:
css
iframe { max-width: 10rem; opacity: 0; position: absolute; visibility: hidden; }
-13687898 0 @TableGenerator : how to use i will try to generate the primary keys using table generator. but when i insert the 6 records in my table, the primaryKey table show only one on value. here is the following code
My Entity class
package com.generatorvaluetest.domain; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.SequenceGenerator; import javax.persistence.TableGenerator; @Entity public class Snufu { private int autoId; private int identityId; private int sequenceId; private int tableId; private String name; public int getAutoId() { return autoId; } public void setAutoId(int autoId) { this.autoId = autoId; } public int getIdentityId() { return identityId; } public void setIdentityId(int identityId) { this.identityId = identityId; } public int getSequenceId() { return sequenceId; } public void setSequenceId(int sequenceId) { this.sequenceId = sequenceId; } @Id @TableGenerator(name="tg" , table="pk_table", pkColumnName="name" , valueColumnName="vlaue" , allocationSize=10) @GeneratedValue(strategy=GenerationType.TABLE , generator="tg") public int getTableId() { return tableId; } public void setTableId(int tableId) { this.tableId = tableId; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
This is my main class
package com.generatorvaluetest.main; import org.hibernate.HibernateException; import org.hibernate.Session; import com.generatorvaluetest.domain.Snufu; import com.generatorvaluetest.util.HibernateUtil; public class GeneratorValueTest { public static void main(String[] args) throws HibernateException{ HibernateUtil.recreateDatabase(); Session session = HibernateUtil.beginTransaction(); for(int i = 0 ; i< 5 ; i++){ Snufu snufu = new Snufu(); snufu.setName("jimmy"+i); session.saveOrUpdate(snufu); } new Thread(new Runnable() { @Override public void run() { Session session = HibernateUtil.beginTransaction(); Snufu snufu = new Snufu(); snufu.setName("jimmykalra"); session.saveOrUpdate(snufu); HibernateUtil.commitTransaction(); } }).start(); HibernateUtil.commitTransaction(); } }
in database when i select the values from pk_table the values are
|name | value| |snuf | 1 |
but in snufu tables there are 6 records
-1994963 0Did you take a look at the Go tutorial at http://golang.org/doc/go_tutorial.html
Here's how to compile and run our program. With 6g, say, $ 6g helloworld.go # compile; object goes into helloworld.6 $ 6l helloworld.6 # link; output goes into 6.out $ 6.out Hello, world; or Καλημέρα κόσμε; or こんにちは 世界 $ With gccgo it looks a little more traditional. $ gccgo helloworld.go $ a.out Hello, world; or Καλημέρα κόσμε; or こんにちは 世界-40566573 0 Adding